text
stringlengths
0
13M
dart:collection shuffle method void shuffle( [Random? random] ) override Shuffles the elements of this list randomly. final numbers = <int>[1, 2, 3, 4, 5]; numbers.shuffle(); print(numbers); // [1, 3, 4, 5, 2] OR some other random result. Implementation void shuffle([Random? random]) { random ??= Random(); if (random == null) throw "!"; // TODO(38493): The `??=` should promote. int length = this.length; while (length > 1) { int pos = random.nextInt(length); length -= 1; var tmp = this[length]; this[length] = this[pos]; this[pos] = tmp; } }
Bluetooth Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers. Experimental: This is an experimental technologyCheck the Browser compatibility table carefully before using this in production. The Bluetooth interface of the Web Bluetooth API returns a Promise to a BluetoothDevice object with the specified options. EventTarget Bluetooth Properties Inherits properties from its parent EventTarget. Bluetooth.referringDevice Read only Returns a reference to the device, if any, from which the user opened the current page. For example, an Eddystone beacon might advertise a URL, which the user agent allows the user to open. A BluetoothDevice representing the beacon would be available through navigator.bluetooth.referringDevice. Methods Bluetooth.getAvailability() Returns a Promise that resolved to a boolean value indicating whether the user-agent has the ability to support Bluetooth. Some user-agents let the user configure an option that affects what is returned by this value. If this option is set, that is the value returned by this method. Bluetooth.getDevices() Returns a Promise that resolved to an array of BluetoothDevices which the origin already obtained permission for via a call to Bluetooth.requestDevice(). Bluetooth.requestDevice() Returns a Promise to a BluetoothDevice object with the specified options. Events availabilitychanged An event that fires when Bluetooth capabilities have changed in availability. Specifications Specification Web Bluetooth # bluetooth Browser compatibility Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Bluetooth 56 Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default. 56 In Linux and versions of Windows earlier than 10, this flag must be enabled. 79 Supported by default only on macOS and Windows 10. Linux support is not enabled by default. 79 In Linux and versions of Windows earlier than 10, this flag must be enabled. No No 43 Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default. 43 In Linux and versions of Windows earlier than 10, this flag must be enabled. No No See bug 1100993. 56 No 43 No 6.0 availabilitychanged_event 56 79 No No 43 No No 56 No 43 No 6.0 getAvailability 56 79 No No 43 No No 56 No 43 No 6.0 getDevices 85 85 No No 71 No No 85 No No No No referringDevice 56 79 No No 43 No No 56 No 43 No 6.0 requestDevice 56 79 No No 43 No No 56 No 43 No 6.0 Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Feb 16, 2022, by MDN contributors
wp_check_comment_disallowed_list( string $author, string $email, string $url, string $comment, string $user_ip, string $user_agent ): bool Checks if a comment contains disallowed characters or words. Parameters $author string Required The author of the comment $email string Required The email of the comment $url string Required The url used in the comment $comment string Required The comment content $user_ip string Required The comment author's IP address $user_agent string Required The author's browser user agent Return bool True if comment contains disallowed content, false if comment does not Source File: wp-includes/comment.php. View all references function wp_check_comment_disallowed_list( $author, $email, $url, $comment, $user_ip, $user_agent ) { /** * Fires before the comment is tested for disallowed characters or words. * * @since 1.5.0 * @deprecated 5.5.0 Use {@see 'wp_check_comment_disallowed_list'} instead. * * @param string $author Comment author. * @param string $email Comment author's email. * @param string $url Comment author's URL. * @param string $comment Comment content. * @param string $user_ip Comment author's IP address. * @param string $user_agent Comment author's browser user agent. */ do_action_deprecated( 'wp_blacklist_check', array( $author, $email, $url, $comment, $user_ip, $user_agent ), '5.5.0', 'wp_check_comment_disallowed_list', __( 'Please consider writing more inclusive code.' ) ); /** * Fires before the comment is tested for disallowed characters or words. * * @since 5.5.0 * * @param string $author Comment author. * @param string $email Comment author's email. * @param string $url Comment author's URL. * @param string $comment Comment content. * @param string $user_ip Comment author's IP address. * @param string $user_agent Comment author's browser user agent. */ do_action( 'wp_check_comment_disallowed_list', $author, $email, $url, $comment, $user_ip, $user_agent ); $mod_keys = trim( get_option( 'disallowed_keys' ) ); if ( '' === $mod_keys ) { return false; // If moderation keys are empty. } // Ensure HTML tags are not being used to bypass the list of disallowed characters and words. $comment_without_html = wp_strip_all_tags( $comment ); $words = explode( "\n", $mod_keys ); foreach ( (array) $words as $word ) { $word = trim( $word ); // Skip empty lines. if ( empty( $word ) ) { continue; } // Do some escaping magic so that '#' chars // in the spam words don't break things: $word = preg_quote( $word, '#' ); $pattern = "#$word#i"; if ( preg_match( $pattern, $author ) || preg_match( $pattern, $email ) || preg_match( $pattern, $url ) || preg_match( $pattern, $comment ) || preg_match( $pattern, $comment_without_html ) || preg_match( $pattern, $user_ip ) || preg_match( $pattern, $user_agent ) ) { return true; } } return false; } Hooks do_action_deprecated( 'wp_blacklist_check', string $author, string $email, string $url, string $comment, string $user_ip, string $user_agent ) Fires before the comment is tested for disallowed characters or words. do_action( 'wp_check_comment_disallowed_list', string $author, string $email, string $url, string $comment, string $user_ip, string $user_agent ) Fires before the comment is tested for disallowed characters or words. Related Uses Uses Description do_action_deprecated() wp-includes/plugin.php Fires functions attached to a deprecated action hook. wp_strip_all_tags() wp-includes/formatting.php Properly strips all HTML tags including script and style __() wp-includes/l10n.php Retrieves the translation of $text. do_action() wp-includes/plugin.php Calls the callback functions that have been added to an action hook. get_option() wp-includes/option.php Retrieves an option value based on an option name. Used By Used By Description wp_blacklist_check() wp-includes/deprecated.php Does comment contain disallowed characters or words. wp_allow_comment() wp-includes/comment.php Validates whether this comment is allowed to be made. Changelog Version Description 5.5.0 Introduced.
tf.compat.v1.flags.mark_flags_as_required Ensures that flags are not None during program execution. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.app.flags.mark_flags_as_required tf.compat.v1.flags.mark_flags_as_required( flag_names, flag_values=_flagvalues.FLAGS ) Recommended usage: if name == 'main': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run() Args flag_names Sequence[str], names of the flags. flag_values flags.FlagValues, optional FlagValues instance where the flags are defined. Raises AttributeError If any of flag name has not already been defined as a flag.
fortinet.fortios.fortios_vpn_ssl_web_realm – Realm in Fortinet’s FortiOS and FortiGate. Note This plugin is part of the fortinet.fortios collection (version 1.1.8). To install it use: ansible-galaxy collection install fortinet.fortios. To use it in a playbook, specify: fortinet.fortios.fortios_vpn_ssl_web_realm. New in version 2.9: of fortinet.fortios Synopsis Requirements Parameters Notes Examples Return Values Synopsis This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify vpn_ssl_web feature and realm category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.0 Requirements The below requirements are needed on the host that executes this module. ansible>=2.9.0 Parameters Parameter Choices/Defaults Comments access_token string Token-based authentication. Generated from GUI of Fortigate. state string / required Choices: present absent Indicates whether to create or remove the object. vdom string Default:"root" Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. vpn_ssl_web_realm dictionary Realm. login_page string Replacement HTML for SSL-VPN login page. max_concurrent_user integer Maximum concurrent users (0 - 65535, 0 means unlimited). url_path string URL path to access SSL-VPN login page. virtual_host string Virtual host name for realm. Notes Note Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks Examples - hosts: fortigates collections: - fortinet.fortios connection: httpapi vars: vdom: "root" ansible_httpapi_use_ssl: yes ansible_httpapi_validate_certs: no ansible_httpapi_port: 443 tasks: - name: Realm. fortios_vpn_ssl_web_realm: vdom: "{{ vdom }}" state: "present" access_token: "<your_own_value>" vpn_ssl_web_realm: login_page: "<your_own_value>" max_concurrent_user: "4" url_path: "<your_own_value>" virtual_host: "<your_own_value>" Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description build string always Build number of the fortigate image Sample: 1547 http_method string always Last method used to provision the content into FortiGate Sample: PUT http_status string always Last result given by FortiGate on last operation applied Sample: 200 mkey string success Master key (id) used in the last call to FortiGate Sample: id name string always Name of the table used to fulfill the request Sample: urlfilter path string always Path of the table used to fulfill the request Sample: webfilter revision string always Internal revision number Sample: 30.894-54-18048 serial string always Serial number of the unit Sample: FGVMEVYYQT3AB5352 status string always Indication of the operation's result Sample: success vdom string always Virtual domain used Sample: root version string always Version of the FortiGate Sample: v5.6.3 Authors Link Zheng (@chillancezen) Jie Xue (@JieX19) Hongbin Lu (@fgtdev-hblu) Frank Shen (@frankshen01) Miguel Angel Munoz (@mamunozgonzalez) Nicolas Thomas (@thomnico) © 2012–2018 Michael DeHaan
Class ProgressShellHelper Create a progress bar using a supplied callback. BaseShellHelper ProgressShellHelper Copyright: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) License: MIT License Location: Cake/Console/Helper/ProgressShellHelper.php Properties summary $_progress protected integer The current progress. $_total protected integer The total number of 'items' to progress through. $_width protected integer The width of the bar. Inherited Properties _config, _configInitialized, _consoleOutput, _defaultConfig Method Summary draw() public Render the progress bar based on the current state. increment() public Increment the progress bar. init() public Initialize the progress bar for use. output() public Output a progress bar. Method Detail draw()source public draw( ) Render the progress bar based on the current state. increment()source public increment( integer $num 1 ) Increment the progress bar. Parameters integer $num optional 1 The amount of progress to advance by. init()source public init( array $args array() ) Initialize the progress bar for use. total The total number of items in the progress bar. Defaults to 100. width The width of the progress bar. Defaults to 80. Parameters array $args optional array() The initialization data. output()source public output( array $args ) Output a progress bar. Takes a number of options to customize the behavior: total The total number of items in the progress bar. Defaults to 100. width The width of the progress bar. Defaults to 80. callback The callback that will be called in a loop to advance the progress bar. Parameters array $args The arguments/options to use when outputing the progress bar. Throws RuntimeException Methods inherited from BaseShellHelper __construct()source public __construct( ConsoleOutput $consoleOutput , array $config array() ) Constructor. Parameters ConsoleOutput $consoleOutput The ConsoleOutput instance to use. array $config optional array() The settings for this helper. config()source public config( null $config null ) Initialize config & store config values Parameters null $config optional null Config values to set Returns array| Properties detail $_progresssource protected integer The current progress. $_totalsource protected integer The total number of 'items' to progress through. $_widthsource protected integer The width of the bar.
Packet Provider The Packet provider is used to interact with the resources supported by Packet. The provider needs to be configured with the proper credentials before it can be used. Use the navigation to the left to read about the available resources. Example Usage # Configure the Packet Provider provider "packet" { auth_token = "${var.auth_token}" } # Create a project resource "packet_project" "cool_project" { name = "My First Terraform Project" payment_method = "PAYMENT_METHOD_ID" # Only required for a non-default payment method } # Create a device and add it to tf_project_1 resource "packet_device" "web1" { hostname = "tf.coreos2" plan = "baremetal_1" facility = "ewr1" operating_system = "coreos_stable" billing_cycle = "hourly" project_id = "${packet_project.cool_project.id}" } Argument Reference The following arguments are supported: auth_token - (Required) This is your Packet API Auth token. This can also be specified with the PACKET_AUTH_TOKEN shell environment variable.
pandas.Series.T Series.T return the transpose, which is by definition self
tf.keras.layers.serialize View source on GitHub Serializes a Layer object into a JSON-compatible representation. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.layers.serialize tf.keras.layers.serialize( layer ) Args layer The Layer object to serialize. Returns A JSON-serializable dict representing the object's config. Example: from pprint import pprint model = tf.keras.models.Sequential() model.add(tf.keras.Input(shape=(16,))) model.add(tf.keras.layers.Dense(32, activation='relu')) pprint(tf.keras.layers.serialize(model)) # prints the configuration of the model, as a dict.
jQuery.mobile.path.get() jQuery.mobile.path.get( url )Returns: Boolean Description: Utility method for determining the directory portion of an URL. jQuery.mobile.path.get( url ) url Type: String Utility method for determining the directory portion of an URL. If the URL has no trailing slash, the last component of the URL is considered to be a file. This function returns the directory portion of a given URL. Example: Various uses of jQuery.mobile.path.get <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery.mobile.path.get demo</title> <link rel="stylesheet" href="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script src="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <style> #myResult{ border: 1px solid; border-color: #108040; padding: 10px; } </style> </head> <body> <div role="main" class="ui-content"> <input type="button" value="http://foo.com/a/file.html" id="button1" class="myButton" data-inline="true"> <input type="button" value="http://foo.com/a/" id="button2" class="myButton" data-inline="true"> <input type="button" value="http://foo.com/a" id="button3" class="myButton" data-inline="true"> <input type="button" value="//foo.com/a/file.html" id="button4" class="myButton" data-inline="true"> <input type="button" value="/a/file.html" id="button5" class="myButton" data-inline="true"> <input type="button" value="file.html" id="button6" class="myButton" data-inline="true"> <input type="button" value="/file.html" id="button7" class="myButton" data-inline="true"> <input type="button" value="?a=1&b=2" id="button8" class="myButton" data-inline="true"> <input type="button" value="#foo" id="button9" class="myButton" data-inline="true"> <div id="myResult">The result will be displayed here</div> </div> <script> $(document).ready(function() { $( ".myButton" ).on( "click", function() { var dirName = $.mobile.path.get( $( this ).attr( "value" ) ); $( "#myResult" ).html( String( dirName ) ); }) }); </script> </body> </html> Demo:
item-list.html.twig Default theme implementation for an item list. Available variables: items: A list of items. Each item contains: attributes: HTML attributes to be applied to each list item. value: The content of the list element. title: The title of the list. list_type: The tag for list element ("ul" or "ol"). wrapper_attributes: HTML attributes to be applied to the list wrapper. attributes: HTML attributes to be applied to the list. empty: A message to display when there are no items. Allowed value is a string or render array. context: A list of contextual data associated with the list. May contain: list_style: The custom list style. See also template_preprocess_item_list() File core/modules/system/templates/item-list.html.twig Related topics Theme system overview Functions and templates for the user interface that themes can override.
QQuickFramebufferObject Class The QQuickFramebufferObject class is a convenience class for integrating OpenGL rendering using a framebuffer object (FBO) with Qt Quick. More... Header: #include <QQuickFramebufferObject> qmake: QT += quick Since: Qt 5.2 Inherits: QQuickItem List of all members, including inherited members Public Types class Renderer Properties mirrorVertically : bool textureFollowsItemSize : bool 23 properties inherited from QQuickItem 1 property inherited from QObject Public Functions QQuickFramebufferObject(QQuickItem *parent = Q_NULLPTR) virtual Renderer * createRenderer() const = 0 bool mirrorVertically() const void setMirrorVertically(bool enable) void setTextureFollowsItemSize(bool follows) bool textureFollowsItemSize() const Reimplemented Public Functions virtual bool isTextureProvider() const virtual void releaseResources() virtual QSGTextureProvider * textureProvider() const 95 public functions inherited from QQuickItem 32 public functions inherited from QObject 2 public functions inherited from QQmlParserStatus Signals void mirrorVerticallyChanged(bool) void textureFollowsItemSizeChanged(bool) 1 signal inherited from QQuickItem 2 signals inherited from QObject Additional Inherited Members 1 public slot inherited from QQuickItem 1 public slot inherited from QObject 11 static public members inherited from QObject 33 protected functions inherited from QQuickItem 9 protected functions inherited from QObject Detailed Description The QQuickFramebufferObject class is a convenience class for integrating OpenGL rendering using a framebuffer object (FBO) with Qt Quick. On most platforms, the rendering will occur on a dedicated thread. For this reason, the QQuickFramebufferObject class enforces a strict separation between the item implementation and the FBO rendering. All item logic, such as properties and UI-related helper functions needed by QML should be located in a QQuickFramebufferObject class subclass. Everything that relates to rendering must be located in the QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069Renderer class. To avoid race conditions and read/write issues from two threads it is important that the renderer and the item never read or write shared variables. Communication between the item and the renderer should primarily happen via the QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069Renderer8b7c:f320:99b9:690f:4595:cd17:293a:c069synchronize() function. This function will be called on the render thread while the GUI thread is blocked. Using queued connections or events for communication between item and renderer is also possible. Both the Renderer and the FBO are memory managed internally. To render into the FBO, the user should subclass the Renderer class and reimplement its Renderer8b7c:f320:99b9:690f:4595:cd17:293a:c069render() function. The Renderer subclass is returned from createRenderer(). The size of the FBO will by default adapt to the size of the item. If a fixed size is preferred, set textureFollowsItemSize to false and return a texture of your choosing from QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069Renderer8b7c:f320:99b9:690f:4595:cd17:293a:c069reateFramebufferObject(). Starting Qt 5.4, the QQuickFramebufferObject class is a texture provider and can be used directly in ShaderEffects and other classes that consume texture providers. See also Scene Graph - Rendering FBOs and Scene Graph and Rendering. Property Documentation mirrorVertically : bool This property controls if the size of the FBO's contents should be mirrored vertically when drawing. This allows easy integration of third-party rendering code that does not follow the standard expectations. The default value is false. This property was introduced in Qt 5.6. Access functions: bool mirrorVertically() const void setMirrorVertically(bool enable) Notifier signal: void mirrorVerticallyChanged(bool) textureFollowsItemSize : bool This property controls if the size of the FBO's texture should follow the dimensions of the QQuickFramebufferObject item. When this property is false, the FBO will be created once the first time it is displayed. If it is set to true, the FBO will be recreated every time the dimensions of the item change. The default value is true. Access functions: bool textureFollowsItemSize() const void setTextureFollowsItemSize(bool follows) Notifier signal: void textureFollowsItemSizeChanged(bool) Member Function Documentation QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069QQuickFramebufferObject(QQuickItem *parent = Q_NULLPTR) Constructs a new QQuickFramebufferObject with parent parent. [pure virtual] Renderer *QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069reateRenderer() const Reimplement this function to create a renderer used to render into the FBO. This function will be called on the rendering thread while the GUI thread is blocked. [virtual] bool QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069isTextureProvider() const Reimplemented from QQuickItem8b7c:f320:99b9:690f:4595:cd17:293a:c069isTextureProvider(). [virtual] void QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069releaseResources() Reimplemented from QQuickItem8b7c:f320:99b9:690f:4595:cd17:293a:c069releaseResources(). [virtual] QSGTextureProvider *QQuickFramebufferObject8b7c:f320:99b9:690f:4595:cd17:293a:c069textureProvider() const Reimplemented from QQuickItem8b7c:f320:99b9:690f:4595:cd17:293a:c069textureProvider().
ctest_sleep sleeps for some amount of time ctest_sleep(<seconds>) Sleep for given number of seconds. ctest_sleep(<time1> <duration> <time2>) Sleep for t=(time1 + duration - time2) seconds if t > 0.
QHideEvent Class The QHideEvent class provides an event which is sent after a widget is hidden. More... Header: #include <QHideEvent> qmake: QT += gui Inherits: QEvent List of all members, including inherited members Public Functions QHideEvent() 6 public functions inherited from QEvent Additional Inherited Members 1 property inherited from QEvent 1 static public member inherited from QEvent Detailed Description The QHideEvent class provides an event which is sent after a widget is hidden. This event is sent just before QWidget8b7c:f320:99b9:690f:4595:cd17:293a:c069hide() returns, and also when a top-level window has been hidden (iconified) by the user. If spontaneous() is true, the event originated outside the application. In this case, the user hid the window using the window manager controls, either by iconifying the window or by switching to another virtual desktop where the window is not visible. The window will become hidden but not withdrawn. If the window was iconified, QWidget8b7c:f320:99b9:690f:4595:cd17:293a:c069isMinimized() returns true. See also QShowEvent. Member Function Documentation QHideEvent8b7c:f320:99b9:690f:4595:cd17:293a:c069QHideEvent() Constructs a QHideEvent.
Interface KeySpec All Known Implementing Classes: DESedeKeySpec, DESKeySpec, DHPrivateKeySpec, DHPublicKeySpec, DSAPrivateKeySpec, DSAPublicKeySpec, ECPrivateKeySpec, ECPublicKeySpec, EdECPrivateKeySpec, EdECPublicKeySpec, EncodedKeySpec, PBEKeySpec, PKCS8EncodedKeySpec, RSAMultiPrimePrivateCrtKeySpec, RSAPrivateCrtKeySpec, RSAPrivateKeySpec, RSAPublicKeySpec, SecretKeySpec, X509EncodedKeySpec, XECPrivateKeySpec, XECPublicKeySpec public interface KeySpec A (transparent) specification of the key material that constitutes a cryptographic key. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device. A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec). This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all key specifications. All key specifications must implement this interface. Since: 1.2 See Also: Key KeyFactory EncodedKeySpec X509EncodedKeySpec PKCS8EncodedKeySpec DSAPrivateKeySpec DSAPublicKeySpec
At-rules At-rules are CSS statements that instruct CSS how to behave. They begin with an at sign, '@' (U+0040 COMMERCIAL AT), followed by an identifier and includes everything up to the next semicolon, ';' (U+003B SEMICOLON), or the next CSS block, whichever comes first. Syntax Regular /* General structure */ @IDENTIFIER (RULE); /* Example: tells browser to use UTF-8 character set */ @charset "utf-8"; There are several regular at-rules, designated by their identifiers, each with a different syntax: @charset — Defines the character set used by the style sheet. @import — Tells the CSS engine to include an external style sheet. @namespace — Tells the CSS engine that all its content must be considered prefixed with an XML namespace. Nested @IDENTIFIER (RULE) { } A subset of nested statements, which can be used as a statement of a style sheet as well as inside of conditional group rules. @media — A conditional group rule that will apply its content if the device meets the criteria of the condition defined using a media query. @supports — A conditional group rule that will apply its content if the browser meets the criteria of the given condition. @document Deprecated — A conditional group rule that will apply its content if the document in which the style sheet is applied meets the criteria of the given condition. (deferred to Level 4 of CSS Spec) @page — Describes the aspect of layout changes that will be applied when printing the document. @font-face — Describes the aspect of an external font to be downloaded. @keyframes — Describes the aspect of intermediate steps in a CSS animation sequence. @viewport Deprecated — Describes the aspects of the viewport for small screen devices. (currently at the Working Draft stage) @counter-style — Defines specific counter styles that are not part of the predefined set of styles. (at the Candidate Recommendation stage, but only implemented in Gecko as of writing) @font-feature-values (plus @swash, @ornaments, @annotation, @stylistic, @styleset and @character-variant) — Define common names in font-variant-alternates for feature activated differently in OpenType. (at the Candidate Recommendation stage, but only implemented in Gecko as of writing) @property Experimental — Describes the aspect of custom properties and variables. (currently at the Working Draft stage) @layer – Declares a cascade layer and defines the order of precedence in case of multiple cascade layers. Conditional group rules Much like the values of properties, each at-rule has a different syntax. Nevertheless, several of them can be grouped into a special category named conditional group rules. These statements share a common syntax and each of them can include nested statements—either rulesets or nested at-rules. Furthermore, they all convey a common semantic meaning—they all link some type of condition, which at any time evaluates to either true or false. If the condition evaluates to true, then all of the statements within the group will be applied. Conditional group rules are defined in CSS Conditionals Level 3 and are: @media, @supports, @document. (deferred to Level 4 of CSS Spec) Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting. Index @charset @counter-style @document Deprecated @font-face @font-feature-values @import @keyframes @layer @media @namespace @page @property Experimental @supports @viewport Deprecated Specifications Specification CSS Conditional Rules Module Level 3 Compatibility Standard # css-at-rules See also CSS key concepts: CSS syntax Comments Specificity Inheritance Box model Layout modes Visual formatting models Margin collapsing Values Initial values Computed values Used values Actual values Value definition syntax Shorthand properties Replaced elements Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Aug 18, 2022, by MDN contributors
Class X509Certificate java.lang.Object java.security.cert.Certificate java.security.cert.X509Certificate All Implemented Interfaces: Serializable, X509Extension public abstract class X509Certificate extends Certificate implements X509Extension Abstract class for X.509 certificates. This provides a standard way to access all the attributes of an X.509 certificate. In June of 1996, the basic X.509 v3 format was completed by ISO/IEC and ANSI X9, which is described below in ASN.1: Certificate 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { tbsCertificate TBSCertificate, signatureAlgorithm AlgorithmIdentifier, signature BIT STRING } These certificates are widely used to support authentication and other functionality in Internet security systems. Common applications include Privacy Enhanced Mail (PEM), Transport Layer Security (SSL), code signing for trusted software distribution, and Secure Electronic Transactions (SET). These certificates are managed and vouched for by Certificate Authorities (CAs). CAs are services which create certificates by placing data in the X.509 standard format and then digitally signing that data. CAs act as trusted third parties, making introductions between principals who have no direct knowledge of each other. CA certificates are either signed by themselves, or by some other CA such as a "root" CA. More information can be found in RFC 5280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile. The ASN.1 definition of tbsCertificate is: TBSCertificate 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { version [0] EXPLICIT Version DEFAULT v1, serialNumber CertificateSerialNumber, signature AlgorithmIdentifier, issuer Name, validity Validity, subject Name, subjectPublicKeyInfo SubjectPublicKeyInfo, issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version must be v2 or v3 subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version must be v2 or v3 extensions [3] EXPLICIT Extensions OPTIONAL -- If present, version must be v3 } Certificates are instantiated using a certificate factory. The following is an example of how to instantiate an X.509 certificate: try (InputStream inStream = new FileInputStream("fileName-of-cert")) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream); } Since: 1.2 See Also: Certificate CertificateFactory X509Extension Serialized Form Nested Class Summary Nested classes/interfaces declared in class java.security.cert.Certificate Certificate.CertificateRep Constructor Summary X509Certificate() Modifier Constructor Description protected Constructor for X.509 certificates. Method Summary Modifier and Type Method Description abstract void checkValidity() Checks that the certificate is currently valid. abstract void checkValidity(Date date) Checks that the given date is within the certificate's validity period. abstract int getBasicConstraints() Gets the certificate constraints path length from the critical BasicConstraints extension, (OID = 352-889-1594). List<String> getExtendedKeyUsage() Gets an unmodifiable list of Strings representing the OBJECT IDENTIFIERs of the ExtKeyUsageSyntax field of the extended key usage extension, (OID = 352-889-1594). Collection<List<?>> getIssuerAlternativeNames() Gets an immutable collection of issuer alternative names from the IssuerAltName extension, (OID = 352-889-1594). abstract Principal getIssuerDN() Deprecated. Use getIssuerX500Principal() instead. abstract boolean[] getIssuerUniqueID() Gets the issuerUniqueID value from the certificate. X500Principal getIssuerX500Principal() Returns the issuer (issuer distinguished name) value from the certificate as an X500Principal. abstract boolean[] getKeyUsage() Gets a boolean array representing bits of the KeyUsage extension, (OID = 352-889-1594). abstract Date getNotAfter() Gets the notAfter date from the validity period of the certificate. abstract Date getNotBefore() Gets the notBefore date from the validity period of the certificate. abstract BigInteger getSerialNumber() Gets the serialNumber value from the certificate. abstract String getSigAlgName() Gets the signature algorithm name for the certificate signature algorithm. abstract String getSigAlgOID() Gets the signature algorithm OID string from the certificate. abstract byte[] getSigAlgParams() Gets the DER-encoded signature algorithm parameters from this certificate's signature algorithm. abstract byte[] getSignature() Gets the signature value (the raw signature bits) from the certificate. Collection<List<?>> getSubjectAlternativeNames() Gets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 352-889-1594). abstract Principal getSubjectDN() Deprecated. Use getSubjectX500Principal() instead. abstract boolean[] getSubjectUniqueID() Gets the subjectUniqueID value from the certificate. X500Principal getSubjectX500Principal() Returns the subject (subject distinguished name) value from the certificate as an X500Principal. abstract byte[] getTBSCertificate() Gets the DER-encoded certificate information, the tbsCertificate from this certificate. abstract int getVersion() Gets the version (version number) value from the certificate. void verify(PublicKey key, Provider sigProvider) Verifies that this certificate was signed using the private key that corresponds to the specified public key. Methods declared in class java.security.cert.Certificate equals, getEncoded, getPublicKey, getType, hashCode, toString, verify, verify, writeReplace Methods declared in class java.lang.Object clone, finalize, getClass, notify, notifyAll, wait, wait, wait Methods declared in interface java.security.cert.X509Extension getCriticalExtensionOIDs, getExtensionValue, getNonCriticalExtensionOIDs, hasUnsupportedCriticalExtension Constructor Details X509Certificate protected X509Certificate() Constructor for X.509 certificates. Method Details checkValidity public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException Checks that the certificate is currently valid. It is if the current date and time are within the validity period given in the certificate. The validity period consists of two date/time values: the first and last dates (and times) on which the certificate is valid. It is defined in ASN.1 as: validity Validity Validity 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { notBefore CertificateValidityDate, notAfter CertificateValidityDate } CertificateValidityDate 8b7c:f320:99b9:690f:4595:cd17:293a:c069= CHOICE { utcTime UTCTime, generalTime GeneralizedTime } Throws: CertificateExpiredException - if the certificate has expired. CertificateNotYetValidException - if the certificate is not yet valid. checkValidity public abstract void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException Checks that the given date is within the certificate's validity period. In other words, this determines whether the certificate would be valid at the given date/time. Parameters: date - the Date to check against to see if this certificate is valid at that date/time. Throws: CertificateExpiredException - if the certificate has expired with respect to the date supplied. CertificateNotYetValidException - if the certificate is not yet valid with respect to the date supplied. See Also: checkValidity() getVersion public abstract int getVersion() Gets the version (version number) value from the certificate. The ASN.1 definition for this is: version [0] EXPLICIT Version DEFAULT v1 Version 8b7c:f320:99b9:690f:4595:cd17:293a:c069= INTEGER { v1(0), v2(1), v3(2) } Returns: the version number, i.e. 1, 2 or 3. getSerialNumber public abstract BigInteger getSerialNumber() Gets the serialNumber value from the certificate. The serial number is an integer assigned by the certification authority to each certificate. It must be unique for each certificate issued by a given CA (i.e., the issuer name and serial number identify a unique certificate). The ASN.1 definition for this is: serialNumber CertificateSerialNumber CertificateSerialNumber 8b7c:f320:99b9:690f:4595:cd17:293a:c069= INTEGER Returns: the serial number. getIssuerDN @Deprecated(since="16") public abstract Principal getIssuerDN() Deprecated. Use getIssuerX500Principal() instead. This method returns the issuer as an implementation specific Principal object, which should not be relied upon by portable code. Gets the issuer (issuer distinguished name) value from the certificate. The issuer name identifies the entity that signed (and issued) the certificate. The issuer name field contains an X.500 distinguished name (DN). The ASN.1 definition for this is: issuer Name Name 8b7c:f320:99b9:690f:4595:cd17:293a:c069= CHOICE { RDNSequence } RDNSequence 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE OF RelativeDistinguishedName RelativeDistinguishedName 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SET OF AttributeValueAssertion AttributeValueAssertion 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { AttributeType, AttributeValue } AttributeType 8b7c:f320:99b9:690f:4595:cd17:293a:c069= OBJECT IDENTIFIER AttributeValue 8b7c:f320:99b9:690f:4595:cd17:293a:c069= ANY The Name describes a hierarchical name composed of attributes, such as country name, and corresponding values, such as US. The type of the AttributeValue component is determined by the AttributeType; in general it will be a directoryString. A directoryString is usually one of PrintableString, TeletexString or UniversalString. Returns: a Principal whose name is the issuer distinguished name. getIssuerX500Principal public X500Principal getIssuerX500Principal() Returns the issuer (issuer distinguished name) value from the certificate as an X500Principal. It is recommended that subclasses override this method. Returns: an X500Principal representing the issuer distinguished name Since: 1.4 getSubjectDN @Deprecated(since="16") public abstract Principal getSubjectDN() Deprecated. Use getSubjectX500Principal() instead. This method returns the subject as an implementation specific Principal object, which should not be relied upon by portable code. Gets the subject (subject distinguished name) value from the certificate. If the subject value is empty, then the getName() method of the returned Principal object returns an empty string (""). The ASN.1 definition for this is: subject Name See getIssuerDN for Name and other relevant definitions. Returns: a Principal whose name is the subject name. getSubjectX500Principal public X500Principal getSubjectX500Principal() Returns the subject (subject distinguished name) value from the certificate as an X500Principal. If the subject value is empty, then the getName() method of the returned X500Principal object returns an empty string (""). It is recommended that subclasses override this method. Returns: an X500Principal representing the subject distinguished name Since: 1.4 getNotBefore public abstract Date getNotBefore() Gets the notBefore date from the validity period of the certificate. The relevant ASN.1 definitions are: validity Validity Validity 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { notBefore CertificateValidityDate, notAfter CertificateValidityDate } CertificateValidityDate 8b7c:f320:99b9:690f:4595:cd17:293a:c069= CHOICE { utcTime UTCTime, generalTime GeneralizedTime } Returns: the start date of the validity period. See Also: checkValidity() getNotAfter public abstract Date getNotAfter() Gets the notAfter date from the validity period of the certificate. See getNotBefore for relevant ASN.1 definitions. Returns: the end date of the validity period. See Also: checkValidity() getTBSCertificate public abstract byte[] getTBSCertificate() throws CertificateEncodingException Gets the DER-encoded certificate information, the tbsCertificate from this certificate. This can be used to verify the signature independently. Returns: the DER-encoded certificate information. Throws: CertificateEncodingException - if an encoding error occurs. getSignature public abstract byte[] getSignature() Gets the signature value (the raw signature bits) from the certificate. The ASN.1 definition for this is: signature BIT STRING Returns: the signature. getSigAlgName public abstract String getSigAlgName() Gets the signature algorithm name for the certificate signature algorithm. An example is the string "SHA256withRSA". The ASN.1 definition for this is: signatureAlgorithm AlgorithmIdentifier AlgorithmIdentifier 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } -- contains a value of the type -- registered for use with the -- algorithm object identifier value The algorithm name is determined from the algorithm OID string. Returns: the signature algorithm name. getSigAlgOID public abstract String getSigAlgOID() Gets the signature algorithm OID string from the certificate. An OID is represented by a set of nonnegative whole numbers separated by periods. For example, the string "1.2.840.10040.4.3" identifies the SHA-1 with DSA signature algorithm defined in RFC 3279: Algorithms and Identifiers for the Internet X.509 Public Key Infrastructure Certificate and CRL Profile. See getSigAlgName for relevant ASN.1 definitions. Returns: the signature algorithm OID string. getSigAlgParams public abstract byte[] getSigAlgParams() Gets the DER-encoded signature algorithm parameters from this certificate's signature algorithm. In most cases, the signature algorithm parameters are null; the parameters are usually supplied with the certificate's public key. If access to individual parameter values is needed then use AlgorithmParameters and instantiate with the name returned by getSigAlgName. See getSigAlgName for relevant ASN.1 definitions. Returns: the DER-encoded signature algorithm parameters, or null if no parameters are present. getIssuerUniqueID public abstract boolean[] getIssuerUniqueID() Gets the issuerUniqueID value from the certificate. The issuer unique identifier is present in the certificate to handle the possibility of reuse of issuer names over time. RFC 5280 recommends that names not be reused and that conforming certificates not make use of unique identifiers. Applications conforming to that profile should be capable of parsing unique identifiers and making comparisons. The ASN.1 definition for this is: issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL UniqueIdentifier 8b7c:f320:99b9:690f:4595:cd17:293a:c069= BIT STRING Returns: the issuer unique identifier or null if it is not present in the certificate. getSubjectUniqueID public abstract boolean[] getSubjectUniqueID() Gets the subjectUniqueID value from the certificate. The ASN.1 definition for this is: subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL UniqueIdentifier 8b7c:f320:99b9:690f:4595:cd17:293a:c069= BIT STRING Returns: the subject unique identifier or null if it is not present in the certificate. getKeyUsage public abstract boolean[] getKeyUsage() Gets a boolean array representing bits of the KeyUsage extension, (OID = 352-889-1594). The key usage extension defines the purpose (e.g., encipherment, signature, certificate signing) of the key contained in the certificate. The ASN.1 definition for this is: KeyUsage 8b7c:f320:99b9:690f:4595:cd17:293a:c069= BIT STRING { digitalSignature (0), nonRepudiation (1), keyEncipherment (2), dataEncipherment (3), keyAgreement (4), keyCertSign (5), cRLSign (6), encipherOnly (7), decipherOnly (8) } RFC 5280 recommends that when used, this be marked as a critical extension. Returns: the KeyUsage extension of this certificate, represented as an array of booleans. The order of KeyUsage values in the array is the same as in the above ASN.1 definition. The array will contain a value for each KeyUsage defined above. If the KeyUsage list encoded in the certificate is longer than the above list, it will not be truncated. Returns null if this certificate does not contain a KeyUsage extension. getExtendedKeyUsage public List<String> getExtendedKeyUsage() throws CertificateParsingException Gets an unmodifiable list of Strings representing the OBJECT IDENTIFIERs of the ExtKeyUsageSyntax field of the extended key usage extension, (OID = 352-889-1594). It indicates one or more purposes for which the certified public key may be used, in addition to or in place of the basic purposes indicated in the key usage extension field. The ASN.1 definition for this is: ExtKeyUsageSyntax 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE SIZE (1..MAX) OF KeyPurposeId KeyPurposeId 8b7c:f320:99b9:690f:4595:cd17:293a:c069= OBJECT IDENTIFIER Key purposes may be defined by any organization with a need. Object identifiers used to identify key purposes shall be assigned in accordance with IANA or ITU-T Rec. X.660 | ISO/IEC/ITU 9834-1. This method was added to version 1.4 of the Java 2 Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Subclasses should override this method with a correct implementation. Returns: the ExtendedKeyUsage extension of this certificate, as an unmodifiable list of object identifiers represented as Strings. Returns null if this certificate does not contain an ExtendedKeyUsage extension. Throws: CertificateParsingException - if the extension cannot be decoded Since: 1.4 getBasicConstraints public abstract int getBasicConstraints() Gets the certificate constraints path length from the critical BasicConstraints extension, (OID = 352-889-1594). The basic constraints extension identifies whether the subject of the certificate is a Certificate Authority (CA) and how deep a certification path may exist through that CA. The pathLenConstraint field (see below) is meaningful only if cA is set to TRUE. In this case, it gives the maximum number of CA certificates that may follow this certificate in a certification path. A value of zero indicates that only an end-entity certificate may follow in the path. The ASN.1 definition for this is: BasicConstraints 8b7c:f320:99b9:690f:4595:cd17:293a:c069= SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER (0..MAX) OPTIONAL } Returns: the value of pathLenConstraint if the BasicConstraints extension is present in the certificate and the subject of the certificate is a CA, otherwise -1. If the subject of the certificate is a CA and pathLenConstraint does not appear, Integer.MAX_VALUE is returned to indicate that there is no limit to the allowed length of the certification path. getSubjectAlternativeNames public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException Gets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 352-889-1594). The ASN.1 definition of the SubjectAltName extension is: SubjectAltName 8b7c:f320:99b9:690f:4595:cd17:293a:c069= GeneralNames GeneralNames 8b7c:f320:99b9:690f:4595:cd17:293a:c069 = SEQUENCE SIZE (1..MAX) OF GeneralName GeneralName 8b7c:f320:99b9:690f:4595:cd17:293a:c069= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2] IA5String, x400Address [3] ORAddress, directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER} If this certificate does not contain a SubjectAltName extension, null is returned. Otherwise, a Collection is returned with an entry representing each GeneralName included in the extension. Each entry is a List whose first entry is an Integer (the name type, 0-8) and whose second entry is a String or a byte array (the name, in string or ASN.1 DER encoded form, respectively). RFC 822, DNS, and URI names are returned as Strings, using the well-established string formats for those types (subject to the restrictions included in RFC 5280). IPv4 address names are returned using dotted quad notation. IPv6 address names are returned in the form "a1:a2:...:a8", where a1-a8 are hexadecimal values representing the eight 16-bit pieces of the address. OID names are returned as Strings represented as a series of nonnegative integers separated by periods. And directory names (distinguished names) are returned in RFC 2253 string format. No standard string format is defined for otherNames, X.400 names, EDI party names, or any other type of names. They are returned as byte arrays containing the ASN.1 DER encoded form of the name. Note that the Collection returned may contain more than one name of the same type. Also, note that the returned Collection is immutable and any entries containing byte arrays are cloned to protect against subsequent modifications. This method was added to version 1.4 of the Java 2 Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Subclasses should override this method with a correct implementation. Returns: an immutable Collection of subject alternative names (or null) Throws: CertificateParsingException - if the extension cannot be decoded Since: 1.4 getIssuerAlternativeNames public Collection<List<?>> getIssuerAlternativeNames() throws CertificateParsingException Gets an immutable collection of issuer alternative names from the IssuerAltName extension, (OID = 352-889-1594). The ASN.1 definition of the IssuerAltName extension is: IssuerAltName 8b7c:f320:99b9:690f:4595:cd17:293a:c069= GeneralNames The ASN.1 definition of GeneralNames is defined in getSubjectAlternativeNames. If this certificate does not contain an IssuerAltName extension, null is returned. Otherwise, a Collection is returned with an entry representing each GeneralName included in the extension. Each entry is a List whose first entry is an Integer (the name type, 0-8) and whose second entry is a String or a byte array (the name, in string or ASN.1 DER encoded form, respectively). For more details about the formats used for each name type, see the getSubjectAlternativeNames method. Note that the Collection returned may contain more than one name of the same type. Also, note that the returned Collection is immutable and any entries containing byte arrays are cloned to protect against subsequent modifications. This method was added to version 1.4 of the Java 2 Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Subclasses should override this method with a correct implementation. Returns: an immutable Collection of issuer alternative names (or null) Throws: CertificateParsingException - if the extension cannot be decoded Since: 1.4 verify public void verify(PublicKey key, Provider sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException Verifies that this certificate was signed using the private key that corresponds to the specified public key. This method uses the signature verification engine supplied by the specified provider. Note that the specified Provider object does not have to be registered in the provider list. This method was added to version 1.8 of the Java Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Overrides: verify in class Certificate Parameters: key - the PublicKey used to carry out the verification. sigProvider - the signature provider. Throws: NoSuchAlgorithmException - on unsupported signature algorithms. InvalidKeyException - on incorrect key. SignatureException - on signature errors. CertificateException - on encoding errors. UnsupportedOperationException - if the method is not supported Since: 1.8
function dblog_filter_form dblog_filter_form($form) Form constructor for the database logging filter form. See also dblog_filter_form_validate() dblog_filter_form_submit() dblog_overview() Related topics Form builder functions Functions that build an abstract representation of a HTML form. File modules/dblog/dblog.admin.inc, line 315 Administrative page callbacks for the Database Logging module. Code function dblog_filter_form($form) { $filters = dblog_filters(); $form['filters'] = array( '#type' => 'fieldset', '#title' => t('Filter log messages'), '#collapsible' => TRUE, '#collapsed' => empty($_SESSION['dblog_overview_filter']), ); foreach ($filters as $key => $filter) { $form['filters']['status'][$key] = array( '#title' => $filter['title'], '#type' => 'select', '#multiple' => TRUE, '#size' => 8, '#options' => $filter['options'], ); if (!empty($_SESSION['dblog_overview_filter'][$key])) { $form['filters']['status'][$key]['#default_value'] = $_SESSION['dblog_overview_filter'][$key]; } } $form['filters']['actions'] = array( '#type' => 'actions', '#attributes' => array('class' => array('container-inline')), ); $form['filters']['actions']['submit'] = array( '#type' => 'submit', '#value' => t('Filter'), ); if (!empty($_SESSION['dblog_overview_filter'])) { $form['filters']['actions']['reset'] = array( '#type' => 'submit', '#value' => t('Reset') ); } return $form; }
PhpProcess class PhpProcess extends Process PhpProcess runs a PHP script in an independent process. $p = new PhpProcess(''); $p->run(); print $p->getOutput()."\n"; Constants ERR OUT STATUS_READY STATUS_STARTED STATUS_TERMINATED STDIN STDOUT STDERR TIMEOUT_PRECISION Properties static array $exitCodes Exit codes translation table. from Process Methods __construct(string $script, string|null $cwd = null, array $env = null, int|float|null $timeout = 60, array $options = array()) Constructor. __destruct() from Process __clone() from Process int run(callable|null $callback = null) Runs the process. from Process Process mustRun(callable $callback = null) Runs the process. from Process start(callable $callback = null) Starts the process and returns after writing the input to STDIN. Process restart(callable $callback = null) Restarts the process. from Process int wait(callable $callback = null) Waits for the process to terminate. from Process int|null getPid() Returns the Pid (process identifier), if applicable. from Process Process signal(int $signal) Sends a POSIX signal to the process. from Process Process disableOutput() Disables fetching output and error output from the underlying process. from Process Process enableOutput() Enables fetching output and error output from the underlying process. from Process bool isOutputDisabled() Returns true in case the output is disabled, false otherwise. from Process string getOutput() Returns the current output of the process (STDOUT). from Process string getIncrementalOutput() Returns the output incrementally. from Process Process clearOutput() Clears the process output. from Process string getErrorOutput() Returns the current error output of the process (STDERR). from Process string getIncrementalErrorOutput() Returns the errorOutput incrementally. from Process Process clearErrorOutput() Clears the process output. from Process null|int getExitCode() Returns the exit code returned by the process. from Process null|string getExitCodeText() Returns a string representation for the exit code returned by the process. from Process bool isSuccessful() Checks if the process ended successfully. from Process bool hasBeenSignaled() Returns true if the child process has been terminated by an uncaught signal. from Process int getTermSignal() Returns the number of the signal that caused the child process to terminate its execution. from Process bool hasBeenStopped() Returns true if the child process has been stopped by a signal. from Process int getStopSignal() Returns the number of the signal that caused the child process to stop its execution. from Process bool isRunning() Checks if the process is currently running. from Process bool isStarted() Checks if the process has been started with no regard to the current state. from Process bool isTerminated() Checks if the process is terminated. from Process string getStatus() Gets the process status. from Process int stop(int|float $timeout = 10, int $signal = null) Stops the process. from Process addOutput(string $line) Adds a line to the STDOUT stream. from Process addErrorOutput(string $line) Adds a line to the STDERR stream. from Process string getCommandLine() Gets the command line to be executed. from Process Process setCommandLine(string $commandline) Sets the command line to be executed. from Process float|null getTimeout() Gets the process timeout (max. runtime). from Process float|null getIdleTimeout() Gets the process idle timeout (max. time since last output). from Process Process setTimeout(int|float|null $timeout) Sets the process timeout (max. runtime). from Process Process setIdleTimeout(int|float|null $timeout) Sets the process idle timeout (max. time since last output). from Process Process setTty(bool $tty) Enables or disables the TTY mode. from Process bool isTty() Checks if the TTY mode is enabled. from Process Process setPty(bool $bool) Sets PTY mode. from Process bool isPty() Returns PTY state. from Process string|null getWorkingDirectory() Gets the working directory. from Process Process setWorkingDirectory(string $cwd) Sets the current working directory. from Process array getEnv() Gets the environment variables. from Process Process setEnv(array $env) Sets the environment variables. from Process null|string getInput() Gets the Process input. from Process Process setInput(mixed $input) Sets the input. from Process array getOptions() Gets the options for proc_open. from Process Process setOptions(array $options) Sets the options for proc_open. from Process bool getEnhanceWindowsCompatibility() Gets whether or not Windows compatibility is enabled. from Process Process setEnhanceWindowsCompatibility(bool $enhance) Sets whether or not Windows compatibility is enabled. from Process bool getEnhanceSigchildCompatibility() Returns whether sigchild compatibility mode is activated or not. from Process Process setEnhanceSigchildCompatibility(bool $enhance) Activates sigchild compatibility mode. from Process checkTimeout() Performs a check between the timeout definition and the time the process started. from Process static bool isPtySupported() Returns whether PTY is supported on the current operating system. from Process setPhpBinary($php) Sets the path to the PHP binary to use. Details __construct(string $script, string|null $cwd = null, array $env = null, int|float|null $timeout = 60, array $options = array()) Constructor. Parameters string $script The PHP script to run (as a string) string|null $cwd The working directory or null to use the working dir of the current PHP process array $env The environment variables or null to use the same environment as the current PHP process int|float|null $timeout The timeout in seconds or null to disable array $options An array of options for proc_open __destruct() __clone() int run(callable|null $callback = null) Runs the process. The callback receives the type of output (out or err) and some bytes from the output in real-time. It allows to have feedback from the independent process during execution. The STDOUT and STDERR are also available after the process is finished via the getOutput() and getErrorOutput() methods. Parameters callable|null $callback A PHP callback to run whenever there is some output available on STDOUT or STDERR Return Value int The exit status code Exceptions RuntimeException When process can't be launched RuntimeException When process stopped after receiving signal LogicException In case a callback is provided and output has been disabled Process mustRun(callable $callback = null) Runs the process. This is identical to run() except that an exception is thrown if the process exits with a non-zero exit code. Parameters callable $callback Return Value Process Exceptions RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled ProcessFailedException if the process didn't terminate successfully start(callable $callback = null) Starts the process and returns after writing the input to STDIN. This method blocks until all STDIN data is sent to the process then it returns while the process runs in the background. The termination of the process can be awaited with wait(). The callback receives the type of output (out or err) and some bytes from the output in real-time while writing the standard input to the process. It allows to have feedback from the independent process during execution. If there is no callback passed, the wait() method can be called with true as a second parameter then the callback will get all data occurred in (and since) the start call. Parameters callable $callback A PHP callback to run whenever there is some output available on STDOUT or STDERR Exceptions RuntimeException When process can't be launched RuntimeException When process is already running LogicException In case a callback is provided and output has been disabled Process restart(callable $callback = null) Restarts the process. Be warned that the process is cloned before being started. Parameters callable $callback A PHP callback to run whenever there is some output available on STDOUT or STDERR Return Value Process The new process Exceptions RuntimeException When process can't be launched RuntimeException When process is already running See also start() int wait(callable $callback = null) Waits for the process to terminate. The callback receives the type of output (out or err) and some bytes from the output in real-time while writing the standard input to the process. It allows to have feedback from the independent process during execution. Parameters callable $callback A valid PHP callback Return Value int The exitcode of the process Exceptions RuntimeException When process timed out RuntimeException When process stopped after receiving signal LogicException When process is not yet started int|null getPid() Returns the Pid (process identifier), if applicable. Return Value int|null The process id if running, null otherwise Process signal(int $signal) Sends a POSIX signal to the process. Parameters int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php) Return Value Process Exceptions LogicException In case the process is not running RuntimeException In case --enable-sigchild is activated and the process can't be killed RuntimeException In case of failure Process disableOutput() Disables fetching output and error output from the underlying process. Return Value Process Exceptions RuntimeException In case the process is already running LogicException if an idle timeout is set Process enableOutput() Enables fetching output and error output from the underlying process. Return Value Process Exceptions RuntimeException In case the process is already running bool isOutputDisabled() Returns true in case the output is disabled, false otherwise. Return Value bool string getOutput() Returns the current output of the process (STDOUT). Return Value string The process output Exceptions LogicException in case the output has been disabled LogicException In case the process is not started string getIncrementalOutput() Returns the output incrementally. In comparison with the getOutput method which always return the whole output, this one returns the new output since the last call. Return Value string The process output since the last call Exceptions LogicException in case the output has been disabled LogicException In case the process is not started Process clearOutput() Clears the process output. Return Value Process string getErrorOutput() Returns the current error output of the process (STDERR). Return Value string The process error output Exceptions LogicException in case the output has been disabled LogicException In case the process is not started string getIncrementalErrorOutput() Returns the errorOutput incrementally. In comparison with the getErrorOutput method which always return the whole error output, this one returns the new error output since the last call. Return Value string The process error output since the last call Exceptions LogicException in case the output has been disabled LogicException In case the process is not started Process clearErrorOutput() Clears the process output. Return Value Process null|int getExitCode() Returns the exit code returned by the process. Return Value null|int The exit status code, null if the Process is not terminated Exceptions RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled null|string getExitCodeText() Returns a string representation for the exit code returned by the process. This method relies on the Unix exit code status standardization and might not be relevant for other operating systems. Return Value null|string A string representation for the exit status code, null if the Process is not terminated. See also http://tldp.org/LDP/abs/html/exitcodes.html http://en.wikipedia.org/wiki/Unix_signal bool isSuccessful() Checks if the process ended successfully. Return Value bool true if the process ended successfully, false otherwise bool hasBeenSignaled() Returns true if the child process has been terminated by an uncaught signal. It always returns false on Windows. Return Value bool Exceptions RuntimeException In case --enable-sigchild is activated LogicException In case the process is not terminated int getTermSignal() Returns the number of the signal that caused the child process to terminate its execution. It is only meaningful if hasBeenSignaled() returns true. Return Value int Exceptions RuntimeException In case --enable-sigchild is activated LogicException In case the process is not terminated bool hasBeenStopped() Returns true if the child process has been stopped by a signal. It always returns false on Windows. Return Value bool Exceptions LogicException In case the process is not terminated int getStopSignal() Returns the number of the signal that caused the child process to stop its execution. It is only meaningful if hasBeenStopped() returns true. Return Value int Exceptions LogicException In case the process is not terminated bool isRunning() Checks if the process is currently running. Return Value bool true if the process is currently running, false otherwise bool isStarted() Checks if the process has been started with no regard to the current state. Return Value bool true if status is ready, false otherwise bool isTerminated() Checks if the process is terminated. Return Value bool true if process is terminated, false otherwise string getStatus() Gets the process status. The status is one of: ready, started, terminated. Return Value string The current process status int stop(int|float $timeout = 10, int $signal = null) Stops the process. Parameters int|float $timeout The timeout in seconds int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9) Return Value int The exit-code of the process addOutput(string $line) Adds a line to the STDOUT stream. Parameters string $line The line to append addErrorOutput(string $line) Adds a line to the STDERR stream. Parameters string $line The line to append string getCommandLine() Gets the command line to be executed. Return Value string The command to execute Process setCommandLine(string $commandline) Sets the command line to be executed. Parameters string $commandline The command to execute Return Value Process The current Process instance float|null getTimeout() Gets the process timeout (max. runtime). Return Value float|null The timeout in seconds or null if it's disabled float|null getIdleTimeout() Gets the process idle timeout (max. time since last output). Return Value float|null The timeout in seconds or null if it's disabled Process setTimeout(int|float|null $timeout) Sets the process timeout (max. runtime). To disable the timeout, set this value to null. Parameters int|float|null $timeout The timeout in seconds Return Value Process The current Process instance Exceptions InvalidArgumentException if the timeout is negative Process setIdleTimeout(int|float|null $timeout) Sets the process idle timeout (max. time since last output). To disable the timeout, set this value to null. Parameters int|float|null $timeout The timeout in seconds Return Value Process The current Process instance. Exceptions LogicException if the output is disabled InvalidArgumentException if the timeout is negative Process setTty(bool $tty) Enables or disables the TTY mode. Parameters bool $tty True to enabled and false to disable Return Value Process The current Process instance Exceptions RuntimeException In case the TTY mode is not supported bool isTty() Checks if the TTY mode is enabled. Return Value bool true if the TTY mode is enabled, false otherwise Process setPty(bool $bool) Sets PTY mode. Parameters bool $bool Return Value Process bool isPty() Returns PTY state. Return Value bool string|null getWorkingDirectory() Gets the working directory. Return Value string|null The current working directory or null on failure Process setWorkingDirectory(string $cwd) Sets the current working directory. Parameters string $cwd The new working directory Return Value Process The current Process instance array getEnv() Gets the environment variables. Return Value array The current environment variables Process setEnv(array $env) Sets the environment variables. An environment variable value should be a string. If it is an array, the variable is ignored. That happens in PHP when 'argv' is registered into the $_ENV array for instance. Parameters array $env The new environment variables Return Value Process The current Process instance null|string getInput() Gets the Process input. Return Value null|string The Process input Process setInput(mixed $input) Sets the input. This content will be passed to the underlying process standard input. Parameters mixed $input The content Return Value Process The current Process instance Exceptions LogicException In case the process is running array getOptions() Gets the options for proc_open. Return Value array The current options Process setOptions(array $options) Sets the options for proc_open. Parameters array $options The new options Return Value Process The current Process instance bool getEnhanceWindowsCompatibility() Gets whether or not Windows compatibility is enabled. This is true by default. Return Value bool Process setEnhanceWindowsCompatibility(bool $enhance) Sets whether or not Windows compatibility is enabled. Parameters bool $enhance Return Value Process The current Process instance bool getEnhanceSigchildCompatibility() Returns whether sigchild compatibility mode is activated or not. Return Value bool Process setEnhanceSigchildCompatibility(bool $enhance) Activates sigchild compatibility mode. Sigchild compatibility mode is required to get the exit code and determine the success of a process when PHP has been compiled with the --enable-sigchild option Parameters bool $enhance Return Value Process The current Process instance checkTimeout() Performs a check between the timeout definition and the time the process started. In case you run a background process (with the start method), you should trigger this method regularly to ensure the process timeout Exceptions ProcessTimedOutException In case the timeout was reached static bool isPtySupported() Returns whether PTY is supported on the current operating system. Return Value bool setPhpBinary($php) Sets the path to the PHP binary to use. Parameters $php
ctest(1) Synopsis Description Options Label and Subproject Summary Build and Test Mode Dashboard Client Dashboard Client Steps Dashboard Client Modes Dashboard Client via CTest Command-Line Dashboard Client via CTest Script Dashboard Client Configuration CTest Start Step CTest Update Step CTest Configure Step CTest Build Step CTest Test Step CTest Coverage Step CTest MemCheck Step CTest Submit Step Show as JSON Object Model Resource Allocation Resource Specification File RESOURCE_GROUPS Property Environment Variables See Also Synopsis ctest [<options>] ctest --build-and-test <path-to-source> <path-to-build> --build-generator <generator> [<options>...] [--build-options <opts>...] [--test-command <command> [<args>...]] ctest {-D <dashboard> | -M <model> -T <action> | -S <script> | -SP <script>} [-- <dashboard-options>...] Description The ctest executable is the CMake test driver program. CMake-generated build trees created for projects that use the enable_testing() and add_test() commands have testing support. This program will run the tests and report results. Options -C <cfg>, --build-config <cfg> Choose configuration to test. Some CMake-generated build trees can have multiple build configurations in the same tree. This option can be used to specify which one should be tested. Example configurations are Debug and Release. --progress Enable short progress output from tests. When the output of ctest is being sent directly to a terminal, the progress through the set of tests is reported by updating the same line rather than printing start and end messages for each test on new lines. This can significantly reduce the verbosity of the test output. Test completion messages are still output on their own line for failed tests and the final test summary will also still be logged. This option can also be enabled by setting the environment variable CTEST_PROGRESS_OUTPUT. -V,--verbose Enable verbose output from tests. Test output is normally suppressed and only summary information is displayed. This option will show all test output. -VV,--extra-verbose Enable more verbose output from tests. Test output is normally suppressed and only summary information is displayed. This option will show even more test output. --debug Displaying more verbose internals of CTest. This feature will result in a large number of output that is mostly useful for debugging dashboard problems. --output-on-failure Output anything outputted by the test program if the test should fail. This option can also be enabled by setting the CTEST_OUTPUT_ON_FAILURE environment variable -F Enable failover. This option allows CTest to resume a test set execution that was previously interrupted. If no interruption occurred, the -F option will have no effect. -j <jobs>, --parallel <jobs> Run the tests in parallel using the given number of jobs. This option tells CTest to run the tests in parallel using given number of jobs. This option can also be set by setting the CTEST_PARALLEL_LEVEL environment variable. This option can be used with the PROCESSORS test property. See Label and Subproject Summary. --resource-spec-file <file> Run CTest with resource allocation enabled, using the resource specification file specified in <file>. When ctest is run as a Dashboard Client this sets the ResourceSpecFile option of the CTest Test Step. --test-load <level> While running tests in parallel (e.g. with -j), try not to start tests when they may cause the CPU load to pass above a given threshold. When ctest is run as a Dashboard Client this sets the TestLoad option of the CTest Test Step. -Q,--quiet Make CTest quiet. This option will suppress all the output. The output log file will still be generated if the --output-log is specified. Options such as --verbose, --extra-verbose, and --debug are ignored if --quiet is specified. -O <file>, --output-log <file> Output to log file. This option tells CTest to write all its output to a <file> log file. -N,--show-only[=<format>] Disable actual execution of tests. This option tells CTest to list the tests that would be run but not actually run them. Useful in conjunction with the -R and -E options. <format> can be one of the following values. human Human-friendly output. This is not guaranteed to be stable. This is the default. json-v1 Dump the test information in JSON format. See Show as JSON Object Model. -L <regex>, --label-regex <regex> Run tests with labels matching regular expression. This option tells CTest to run only the tests whose labels match the given regular expression. -R <regex>, --tests-regex <regex> Run tests matching regular expression. This option tells CTest to run only the tests whose names match the given regular expression. -E <regex>, --exclude-regex <regex> Exclude tests matching regular expression. This option tells CTest to NOT run the tests whose names match the given regular expression. -LE <regex>, --label-exclude <regex> Exclude tests with labels matching regular expression. This option tells CTest to NOT run the tests whose labels match the given regular expression. -FA <regex>, --fixture-exclude-any <regex> Exclude fixtures matching <regex> from automatically adding any tests to the test set. If a test in the set of tests to be executed requires a particular fixture, that fixture’s setup and cleanup tests would normally be added to the test set automatically. This option prevents adding setup or cleanup tests for fixtures matching the <regex>. Note that all other fixture behavior is retained, including test dependencies and skipping tests that have fixture setup tests that fail. -FS <regex>, --fixture-exclude-setup <regex> Same as -FA except only matching setup tests are excluded. -FC <regex>, --fixture-exclude-cleanup <regex> Same as -FA except only matching cleanup tests are excluded. -D <dashboard>, --dashboard <dashboard> Execute dashboard test. This option tells CTest to act as a CDash client and perform a dashboard test. All tests are <Mode><Test>, where <Mode> can be Experimental, Nightly, and Continuous, and <Test> can be Start, Update, Configure, Build, Test, Coverage, and Submit. See Dashboard Client. -D <var>:<type>=<value> Define a variable for script mode. Pass in variable values on the command line. Use in conjunction with -S to pass variable values to a dashboard script. Parsing -D arguments as variable values is only attempted if the value following -D does not match any of the known dashboard types. -M <model>, --test-model <model> Sets the model for a dashboard. This option tells CTest to act as a CDash client where the <model> can be Experimental, Nightly, and Continuous. Combining -M and -T is similar to -D. See Dashboard Client. -T <action>, --test-action <action> Sets the dashboard action to perform. This option tells CTest to act as a CDash client and perform some action such as start, build, test etc. See Dashboard Client Steps for the full list of actions. Combining -M and -T is similar to -D. See Dashboard Client. -S <script>, --script <script> Execute a dashboard for a configuration. This option tells CTest to load in a configuration script which sets a number of parameters such as the binary and source directories. Then CTest will do what is required to create and run a dashboard. This option basically sets up a dashboard and then runs ctest -D with the appropriate options. See Dashboard Client. -SP <script>, --script-new-process <script> Execute a dashboard for a configuration. This option does the same operations as -S but it will do them in a separate process. This is primarily useful in cases where the script may modify the environment and you do not want the modified environment to impact other -S scripts. See Dashboard Client. -I [Start,End,Stride,test#,test#|Test file], --tests-information Run a specific number of tests by number. This option causes CTest to run tests starting at number Start, ending at number End, and incrementing by Stride. Any additional numbers after Stride are considered individual test numbers. Start, End, or Stride can be empty. Optionally a file can be given that contains the same syntax as the command line. -U, --union Take the Union of -I and -R. When both -R and -I are specified by default the intersection of tests are run. By specifying -U the union of tests is run instead. --rerun-failed Run only the tests that failed previously. This option tells CTest to perform only the tests that failed during its previous run. When this option is specified, CTest ignores all other options intended to modify the list of tests to run (-L, -R, -E, -LE, -I, etc). In the event that CTest runs and no tests fail, subsequent calls to CTest with the --rerun-failed option will run the set of tests that most recently failed (if any). --repeat <mode>:<n> Run tests repeatedly based on the given <mode> up to <n> times. The modes are: until-fail Require each test to run <n> times without failing in order to pass. This is useful in finding sporadic failures in test cases. until-pass Allow each test to run up to <n> times in order to pass. Repeats tests if they fail for any reason. This is useful in tolerating sporadic failures in test cases. after-timeout Allow each test to run up to <n> times in order to pass. Repeats tests only if they timeout. This is useful in tolerating sporadic timeouts in test cases on busy machines. --repeat-until-fail <n> Equivalent to --repeat until-fail:<n>. --max-width <width> Set the max width for a test name to output. Set the maximum width for each test name to show in the output. This allows the user to widen the output to avoid clipping the test name which can be very annoying. --interactive-debug-mode [0|1] Set the interactive mode to 0 or 1. This option causes CTest to run tests in either an interactive mode or a non-interactive mode. On Windows this means that in non-interactive mode, all system debug pop up windows are blocked. In dashboard mode (Experimental, Nightly, Continuous), the default is non-interactive. When just running tests not for a dashboard the default is to allow popups and interactive debugging. --no-label-summary Disable timing summary information for labels. This option tells CTest not to print summary information for each label associated with the tests run. If there are no labels on the tests, nothing extra is printed. See Label and Subproject Summary. --no-subproject-summary Disable timing summary information for subprojects. This option tells CTest not to print summary information for each subproject associated with the tests run. If there are no subprojects on the tests, nothing extra is printed. See Label and Subproject Summary. --build-and-test See Build and Test Mode. --test-output-size-passed <size> Limit the output for passed tests to <size> bytes. --test-output-size-failed <size> Limit the output for failed tests to <size> bytes. --overwrite Overwrite CTest configuration option. By default CTest uses configuration options from configuration file. This option will overwrite the configuration option. --force-new-ctest-process Run child CTest instances as new processes. By default CTest will run child CTest instances within the same process. If this behavior is not desired, this argument will enforce new processes for child CTest processes. --schedule-random Use a random order for scheduling tests. This option will run the tests in a random order. It is commonly used to detect implicit dependencies in a test suite. --submit-index Legacy option for old Dart2 dashboard server feature. Do not use. --timeout <seconds> Set the default test timeout. This option effectively sets a timeout on all tests that do not already have a timeout set on them via the TIMEOUT property. --stop-time <time> Set a time at which all tests should stop running. Set a real time of day at which all tests should timeout. Example: 7:00:00 -0400. Any time format understood by the curl date parser is accepted. Local time is assumed if no timezone is specified. --print-labels Print all available test labels. This option will not run any tests, it will simply print the list of all labels associated with the test set. --no-tests=<[error|ignore]> Regard no tests found either as error or ignore it. If no tests were found, the default behavior of CTest is to always log an error message but to return an error code in script mode only. This option unifies the behavior of CTest by either returning an error code if no tests were found or by ignoring it. --help,-help,-usage,-h,-H,/? Print usage information and exit. Usage describes the basic command line interface and its options. --version,-version,/V [<f>] Show program name/version banner and exit. If a file is specified, the version is written into it. The help is printed to a named <f>ile if given. --help-full [<f>] Print all help manuals and exit. All manuals are printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-manual <man> [<f>] Print one help manual and exit. The specified manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-manual-list [<f>] List help manuals available and exit. The list contains all manuals for which help may be obtained by using the --help-manual option followed by a manual name. The help is printed to a named <f>ile if given. --help-command <cmd> [<f>] Print help for one command and exit. The cmake-commands(7) manual entry for <cmd> is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-command-list [<f>] List commands with help available and exit. The list contains all commands for which help may be obtained by using the --help-command option followed by a command name. The help is printed to a named <f>ile if given. --help-commands [<f>] Print cmake-commands manual and exit. The cmake-commands(7) manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-module <mod> [<f>] Print help for one module and exit. The cmake-modules(7) manual entry for <mod> is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-module-list [<f>] List modules with help available and exit. The list contains all modules for which help may be obtained by using the --help-module option followed by a module name. The help is printed to a named <f>ile if given. --help-modules [<f>] Print cmake-modules manual and exit. The cmake-modules(7) manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-policy <cmp> [<f>] Print help for one policy and exit. The cmake-policies(7) manual entry for <cmp> is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-policy-list [<f>] List policies with help available and exit. The list contains all policies for which help may be obtained by using the --help-policy option followed by a policy name. The help is printed to a named <f>ile if given. --help-policies [<f>] Print cmake-policies manual and exit. The cmake-policies(7) manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-property <prop> [<f>] Print help for one property and exit. The cmake-properties(7) manual entries for <prop> are printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-property-list [<f>] List properties with help available and exit. The list contains all properties for which help may be obtained by using the --help-property option followed by a property name. The help is printed to a named <f>ile if given. --help-properties [<f>] Print cmake-properties manual and exit. The cmake-properties(7) manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-variable <var> [<f>] Print help for one variable and exit. The cmake-variables(7) manual entry for <var> is printed in a human-readable text format. The help is printed to a named <f>ile if given. --help-variable-list [<f>] List variables with help available and exit. The list contains all variables for which help may be obtained by using the --help-variable option followed by a variable name. The help is printed to a named <f>ile if given. --help-variables [<f>] Print cmake-variables manual and exit. The cmake-variables(7) manual is printed in a human-readable text format. The help is printed to a named <f>ile if given. Label and Subproject Summary CTest prints timing summary information for each LABEL and subproject associated with the tests run. The label time summary will not include labels that are mapped to subprojects. When the PROCESSORS test property is set, CTest will display a weighted test timing result in label and subproject summaries. The time is reported with sec*proc instead of just sec. The weighted time summary reported for each label or subproject j is computed as: Weighted Time Summary for Label/Subproject j = sum(raw_test_time[j,i] * num_processors[j,i], i=1...num_tests[j]) for labels/subprojects j=1...total where: raw_test_time[j,i]: Wall-clock time for the i test for the j label or subproject num_processors[j,i]: Value of the CTest PROCESSORS property for the i test for the j label or subproject num_tests[j]: Number of tests associated with the j label or subproject total: Total number of labels or subprojects that have at least one test run Therefore, the weighted time summary for each label or subproject represents the amount of time that CTest gave to run the tests for each label or subproject and gives a good representation of the total expense of the tests for each label or subproject when compared to other labels or subprojects. For example, if SubprojectA showed 100 sec*proc and SubprojectB showed 10 sec*proc, then CTest allocated approximately 10 times the CPU/core time to run the tests for SubprojectA than for SubprojectB (e.g. so if effort is going to be expended to reduce the cost of the test suite for the whole project, then reducing the cost of the test suite for SubprojectA would likely have a larger impact than effort to reduce the cost of the test suite for SubprojectB). Build and Test Mode CTest provides a command-line signature to configure (i.e. run cmake on), build, and/or execute a test: ctest --build-and-test <path-to-source> <path-to-build> --build-generator <generator> [<options>...] [--build-options <opts>...] [--test-command <command> [<args>...]] The configure and test steps are optional. The arguments to this command line are the source and binary directories. The --build-generator option must be provided to use --build-and-test. If --test-command is specified then that will be run after the build is complete. Other options that affect this mode include: --build-target Specify a specific target to build. If left out the all target is built. --build-nocmake Run the build without running cmake first. Skip the cmake step. --build-run-dir Specify directory to run programs from. Directory where programs will be after it has been compiled. --build-two-config Run CMake twice. --build-exe-dir Specify the directory for the executable. --build-generator Specify the generator to use. See the cmake-generators(7) manual. --build-generator-platform Specify the generator-specific platform. --build-generator-toolset Specify the generator-specific toolset. --build-project Specify the name of the project to build. --build-makeprogram Specify the explicit make program to be used by CMake when configuring and building the project. Only applicable for Make and Ninja based generators. --build-noclean Skip the make clean step. --build-config-sample A sample executable to use to determine the configuration that should be used. e.g. Debug, Release etc. --build-options Additional options for configuring the build (i.e. for CMake, not for the build tool). Note that if this is specified, the --build-options keyword and its arguments must be the last option given on the command line, with the possible exception of --test-command. --test-command The command to run as the test step with the --build-and-test option. All arguments following this keyword will be assumed to be part of the test command line, so it must be the last option given. --test-timeout The time limit in seconds Dashboard Client CTest can operate as a client for the CDash software quality dashboard application. As a dashboard client, CTest performs a sequence of steps to configure, build, and test software, and then submits the results to a CDash server. The command-line signature used to submit to CDash is: ctest (-D <dashboard> | -M <model> -T <action> | -S <script> | -SP <script>) [-- <dashboard-options>...] Options for Dashboard Client include: --group <group> Specify what group you’d like to submit results to Submit dashboard to specified group instead of default one. By default, the dashboard is submitted to Nightly, Experimental, or Continuous group, but by specifying this option, the group can be arbitrary. This replaces the deprecated option --track. Despite the name change its behavior is unchanged. -A <file>, --add-notes <file> Add a notes file with submission. This option tells CTest to include a notes file when submitting dashboard. --tomorrow-tag Nightly or Experimental starts with next day tag. This is useful if the build will not finish in one day. --extra-submit <file>[;<file>] Submit extra files to the dashboard. This option will submit extra files to the dashboard. --http1.0 Submit using HTTP 1.0. This option will force CTest to use HTTP 1.0 to submit files to the dashboard, instead of HTTP 1.1. --no-compress-output Do not compress test output when submitting. This flag will turn off automatic compression of test output. Use this to maintain compatibility with an older version of CDash which doesn’t support compressed test output. Dashboard Client Steps CTest defines an ordered list of testing steps of which some or all may be run as a dashboard client: Start Start a new dashboard submission to be composed of results recorded by the following steps. See the CTest Start Step section below. Update Update the source tree from its version control repository. Record the old and new versions and the list of updated source files. See the CTest Update Step section below. Configure Configure the software by running a command in the build tree. Record the configuration output log. See the CTest Configure Step section below. Build Build the software by running a command in the build tree. Record the build output log and detect warnings and errors. See the CTest Build Step section below. Test Test the software by loading a CTestTestfile.cmake from the build tree and executing the defined tests. Record the output and result of each test. See the CTest Test Step section below. Coverage Compute coverage of the source code by running a coverage analysis tool and recording its output. See the CTest Coverage Step section below. MemCheck Run the software test suite through a memory check tool. Record the test output, results, and issues reported by the tool. See the CTest MemCheck Step section below. Submit Submit results recorded from other testing steps to the software quality dashboard server. See the CTest Submit Step section below. Dashboard Client Modes CTest defines three modes of operation as a dashboard client: Nightly This mode is intended to be invoked once per day, [email protected]. It enables the Start, Update, Configure, Build, Test, Coverage, and Submit steps by default. Selected steps run even if the Update step reports no changes to the source tree. Continuous This mode is intended to be invoked repeatedly throughout the day. It enables the Start, Update, Configure, Build, Test, Coverage, and Submit steps by default, but exits after the Update step if it reports no changes to the source tree. Experimental This mode is intended to be invoked by a developer to test local changes. It enables the Start, Configure, Build, Test, Coverage, and Submit steps by default. Dashboard Client via CTest Command-Line CTest can perform testing on an already-generated build tree. Run the ctest command with the current working directory set to the build tree and use one of these signatures: ctest -D <mode>[<step>] ctest -M <mode> [ -T <step> ]... The <mode> must be one of the above Dashboard Client Modes, and each <step> must be one of the above Dashboard Client Steps. CTest reads the Dashboard Client Configuration settings from a file in the build tree called either CTestConfiguration.ini or DartConfiguration.tcl (the names are historical). The format of the file is: # Lines starting in '#' are comments. # Other non-blank lines are key-value pairs. <setting>: <value> where <setting> is the setting name and <value> is the setting value. In build trees generated by CMake, this configuration file is generated by the CTest module if included by the project. The module uses variables to obtain a value for each setting as documented with the settings below. Dashboard Client via CTest Script CTest can perform testing driven by a cmake-language(7) script that creates and maintains the source and build tree as well as performing the testing steps. Run the ctest command with the current working directory set outside of any build tree and use one of these signatures: ctest -S <script> ctest -SP <script> The <script> file must call CTest Commands commands to run testing steps explicitly as documented below. The commands obtain Dashboard Client Configuration settings from their arguments or from variables set in the script. Dashboard Client Configuration The Dashboard Client Steps may be configured by named settings as documented in the following sections. CTest Start Step Start a new dashboard submission to be composed of results recorded by the following steps. In a CTest Script, the ctest_start() command runs this step. Arguments to the command may specify some of the step settings. The command first runs the command-line specified by the CTEST_CHECKOUT_COMMAND variable, if set, to initialize the source directory. Configuration settings include: BuildDirectory The full path to the project build tree. CTest Script variable: CTEST_BINARY_DIRECTORY CTest module variable: PROJECT_BINARY_DIR SourceDirectory The full path to the project source tree. CTest Script variable: CTEST_SOURCE_DIRECTORY CTest module variable: PROJECT_SOURCE_DIR CTest Update Step In a CTest Script, the ctest_update() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings to specify the version control tool include: BZRCommand bzr command-line tool to use if source tree is managed by Bazaar. CTest Script variable: CTEST_BZR_COMMAND CTest module variable: none BZRUpdateOptions Command-line options to the BZRCommand when updating the source. CTest Script variable: CTEST_BZR_UPDATE_OPTIONS CTest module variable: none CVSCommand cvs command-line tool to use if source tree is managed by CVS. CTest Script variable: CTEST_CVS_COMMAND CTest module variable: CVSCOMMAND CVSUpdateOptions Command-line options to the CVSCommand when updating the source. CTest Script variable: CTEST_CVS_UPDATE_OPTIONS CTest module variable: CVS_UPDATE_OPTIONS GITCommand git command-line tool to use if source tree is managed by Git. CTest Script variable: CTEST_GIT_COMMAND CTest module variable: GITCOMMAND The source tree is updated by git fetch followed by git reset --hard to the FETCH_HEAD. The result is the same as git pull except that any local modifications are overwritten. Use GITUpdateCustom to specify a different approach. GITInitSubmodules If set, CTest will update the repository’s submodules before updating. CTest Script variable: CTEST_GIT_INIT_SUBMODULES CTest module variable: CTEST_GIT_INIT_SUBMODULES GITUpdateCustom Specify a custom command line (as a semicolon-separated list) to run in the source tree (Git work tree) to update it instead of running the GITCommand. CTest Script variable: CTEST_GIT_UPDATE_CUSTOM CTest module variable: CTEST_GIT_UPDATE_CUSTOM GITUpdateOptions Command-line options to the GITCommand when updating the source. CTest Script variable: CTEST_GIT_UPDATE_OPTIONS CTest module variable: GIT_UPDATE_OPTIONS HGCommand hg command-line tool to use if source tree is managed by Mercurial. CTest Script variable: CTEST_HG_COMMAND CTest module variable: none HGUpdateOptions Command-line options to the HGCommand when updating the source. CTest Script variable: CTEST_HG_UPDATE_OPTIONS CTest module variable: none P4Client Value of the -c option to the P4Command. CTest Script variable: CTEST_P4_CLIENT CTest module variable: CTEST_P4_CLIENT P4Command p4 command-line tool to use if source tree is managed by Perforce. CTest Script variable: CTEST_P4_COMMAND CTest module variable: P4COMMAND P4Options Command-line options to the P4Command for all invocations. CTest Script variable: CTEST_P4_OPTIONS CTest module variable: CTEST_P4_OPTIONS P4UpdateCustom Specify a custom command line (as a semicolon-separated list) to run in the source tree (Perforce tree) to update it instead of running the P4Command. CTest Script variable: none CTest module variable: CTEST_P4_UPDATE_CUSTOM P4UpdateOptions Command-line options to the P4Command when updating the source. CTest Script variable: CTEST_P4_UPDATE_OPTIONS CTest module variable: CTEST_P4_UPDATE_OPTIONS SVNCommand svn command-line tool to use if source tree is managed by Subversion. CTest Script variable: CTEST_SVN_COMMAND CTest module variable: SVNCOMMAND SVNOptions Command-line options to the SVNCommand for all invocations. CTest Script variable: CTEST_SVN_OPTIONS CTest module variable: CTEST_SVN_OPTIONS SVNUpdateOptions Command-line options to the SVNCommand when updating the source. CTest Script variable: CTEST_SVN_UPDATE_OPTIONS CTest module variable: SVN_UPDATE_OPTIONS UpdateCommand Specify the version-control command-line tool to use without detecting the VCS that manages the source tree. CTest Script variable: CTEST_UPDATE_COMMAND CTest module variable: <VCS>COMMAND when UPDATE_TYPE is <vcs>, else UPDATE_COMMAND UpdateOptions Command-line options to the UpdateCommand. CTest Script variable: CTEST_UPDATE_OPTIONS CTest module variable: <VCS>_UPDATE_OPTIONS when UPDATE_TYPE is <vcs>, else UPDATE_OPTIONS UpdateType Specify the version-control system that manages the source tree if it cannot be detected automatically. The value may be bzr, cvs, git, hg, p4, or svn. CTest Script variable: none, detected from source tree CTest module variable: UPDATE_TYPE if set, else CTEST_UPDATE_TYPE UpdateVersionOnly Specify that you want the version control update command to only discover the current version that is checked out, and not to update to a different version. CTest Script variable: CTEST_UPDATE_VERSION_ONLY UpdateVersionOverride Specify the current version of your source tree. When this variable is set to a non-empty string, CTest will report the value you specified rather than using the update command to discover the current version that is checked out. Use of this variable supersedes UpdateVersionOnly. Like UpdateVersionOnly, using this variable tells CTest not to update the source tree to a different version. CTest Script variable: CTEST_UPDATE_VERSION_OVERRIDE Additional configuration settings include: NightlyStartTime In the Nightly dashboard mode, specify the “nightly start time”. With centralized version control systems (cvs and svn), the Update step checks out the version of the software as of this time so that multiple clients choose a common version to test. This is not well-defined in distributed version-control systems so the setting is ignored. CTest Script variable: CTEST_NIGHTLY_START_TIME CTest module variable: NIGHTLY_START_TIME if set, else CTEST_NIGHTLY_START_TIME CTest Configure Step In a CTest Script, the ctest_configure() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: ConfigureCommand Command-line to launch the software configuration process. It will be executed in the location specified by the BuildDirectory setting. CTest Script variable: CTEST_CONFIGURE_COMMAND CTest module variable: CMAKE_COMMAND followed by PROJECT_SOURCE_DIR LabelsForSubprojects Specify a semicolon-separated list of labels that will be treated as subprojects. This mapping will be passed on to CDash when configure, test or build results are submitted. CTest Script variable: CTEST_LABELS_FOR_SUBPROJECTS CTest module variable: CTEST_LABELS_FOR_SUBPROJECTS See Label and Subproject Summary. CTest Build Step In a CTest Script, the ctest_build() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: DefaultCTestConfigurationType When the build system to be launched allows build-time selection of the configuration (e.g. Debug, Release), this specifies the default configuration to be built when no -C option is given to the ctest command. The value will be substituted into the value of MakeCommand to replace the literal string ${CTEST_CONFIGURATION_TYPE} if it appears. CTest Script variable: CTEST_CONFIGURATION_TYPE CTest module variable: DEFAULT_CTEST_CONFIGURATION_TYPE, initialized by the CMAKE_CONFIG_TYPE environment variable LabelsForSubprojects Specify a semicolon-separated list of labels that will be treated as subprojects. This mapping will be passed on to CDash when configure, test or build results are submitted. CTest Script variable: CTEST_LABELS_FOR_SUBPROJECTS CTest module variable: CTEST_LABELS_FOR_SUBPROJECTS See Label and Subproject Summary. MakeCommand Command-line to launch the software build process. It will be executed in the location specified by the BuildDirectory setting. CTest Script variable: CTEST_BUILD_COMMAND CTest module variable: MAKECOMMAND, initialized by the build_command() command UseLaunchers For build trees generated by CMake using one of the Makefile Generators or the Ninja generator, specify whether the CTEST_USE_LAUNCHERS feature is enabled by the CTestUseLaunchers module (also included by the CTest module). When enabled, the generated build system wraps each invocation of the compiler, linker, or custom command line with a “launcher” that communicates with CTest via environment variables and files to report granular build warning and error information. Otherwise, CTest must “scrape” the build output log for diagnostics. CTest Script variable: CTEST_USE_LAUNCHERS CTest module variable: CTEST_USE_LAUNCHERS CTest Test Step In a CTest Script, the ctest_test() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: ResourceSpecFile Specify a resource specification file. See Resource Allocation for more information. LabelsForSubprojects Specify a semicolon-separated list of labels that will be treated as subprojects. This mapping will be passed on to CDash when configure, test or build results are submitted. CTest Script variable: CTEST_LABELS_FOR_SUBPROJECTS CTest module variable: CTEST_LABELS_FOR_SUBPROJECTS See Label and Subproject Summary. TestLoad While running tests in parallel (e.g. with -j), try not to start tests when they may cause the CPU load to pass above a given threshold. CTest Script variable: CTEST_TEST_LOAD CTest module variable: CTEST_TEST_LOAD TimeOut The default timeout for each test if not specified by the TIMEOUT test property. CTest Script variable: CTEST_TEST_TIMEOUT CTest module variable: DART_TESTING_TIMEOUT CTest Coverage Step In a CTest Script, the ctest_coverage() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: CoverageCommand Command-line tool to perform software coverage analysis. It will be executed in the location specified by the BuildDirectory setting. CTest Script variable: CTEST_COVERAGE_COMMAND CTest module variable: COVERAGE_COMMAND CoverageExtraFlags Specify command-line options to the CoverageCommand tool. CTest Script variable: CTEST_COVERAGE_EXTRA_FLAGS CTest module variable: COVERAGE_EXTRA_FLAGS These options are the first arguments passed to CoverageCommand. CTest MemCheck Step In a CTest Script, the ctest_memcheck() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: MemoryCheckCommand Command-line tool to perform dynamic analysis. Test command lines will be launched through this tool. CTest Script variable: CTEST_MEMORYCHECK_COMMAND CTest module variable: MEMORYCHECK_COMMAND MemoryCheckCommandOptions Specify command-line options to the MemoryCheckCommand tool. They will be placed prior to the test command line. CTest Script variable: CTEST_MEMORYCHECK_COMMAND_OPTIONS CTest module variable: MEMORYCHECK_COMMAND_OPTIONS MemoryCheckType Specify the type of memory checking to perform. CTest Script variable: CTEST_MEMORYCHECK_TYPE CTest module variable: MEMORYCHECK_TYPE MemoryCheckSanitizerOptions Specify options to sanitizers when running with a sanitize-enabled build. CTest Script variable: CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTest module variable: MEMORYCHECK_SANITIZER_OPTIONS MemoryCheckSuppressionFile Specify a file containing suppression rules for the MemoryCheckCommand tool. It will be passed with options appropriate to the tool. CTest Script variable: CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTest module variable: MEMORYCHECK_SUPPRESSIONS_FILE Additional configuration settings include: BoundsCheckerCommand Specify a MemoryCheckCommand that is known to be command-line compatible with Bounds Checker. CTest Script variable: none CTest module variable: none PurifyCommand Specify a MemoryCheckCommand that is known to be command-line compatible with Purify. CTest Script variable: none CTest module variable: PURIFYCOMMAND ValgrindCommand Specify a MemoryCheckCommand that is known to be command-line compatible with Valgrind. CTest Script variable: none CTest module variable: VALGRIND_COMMAND ValgrindCommandOptions Specify command-line options to the ValgrindCommand tool. They will be placed prior to the test command line. CTest Script variable: none CTest module variable: VALGRIND_COMMAND_OPTIONS DrMemoryCommand Specify a MemoryCheckCommand that is known to be a command-line compatible with DrMemory. CTest Script variable: none CTest module variable: DRMEMORY_COMMAND DrMemoryCommandOptions Specify command-line options to the DrMemoryCommand tool. They will be placed prior to the test command line. CTest Script variable: none CTest module variable: DRMEMORY_COMMAND_OPTIONS CTest Submit Step In a CTest Script, the ctest_submit() command runs this step. Arguments to the command may specify some of the step settings. Configuration settings include: BuildName Describe the dashboard client platform with a short string. (Operating system, compiler, etc.) CTest Script variable: CTEST_BUILD_NAME CTest module variable: BUILDNAME CDashVersion Legacy option. Not used. CTest Script variable: none, detected from server CTest module variable: CTEST_CDASH_VERSION CTestSubmitRetryCount Specify a number of attempts to retry submission on network failure. CTest Script variable: none, use the ctest_submit() RETRY_COUNT option. CTest module variable: CTEST_SUBMIT_RETRY_COUNT CTestSubmitRetryDelay Specify a delay before retrying submission on network failure. CTest Script variable: none, use the ctest_submit() RETRY_DELAY option. CTest module variable: CTEST_SUBMIT_RETRY_DELAY CurlOptions Specify a semicolon-separated list of options to control the Curl library that CTest uses internally to connect to the server. Possible options are CURLOPT_SSL_VERIFYPEER_OFF and CURLOPT_SSL_VERIFYHOST_OFF. CTest Script variable: CTEST_CURL_OPTIONS CTest module variable: CTEST_CURL_OPTIONS DropLocation Legacy option. When SubmitURL is not set, it is constructed from DropMethod, DropSiteUser, DropSitePassword, DropSite, and DropLocation. CTest Script variable: CTEST_DROP_LOCATION CTest module variable: DROP_LOCATION if set, else CTEST_DROP_LOCATION DropMethod Legacy option. When SubmitURL is not set, it is constructed from DropMethod, DropSiteUser, DropSitePassword, DropSite, and DropLocation. CTest Script variable: CTEST_DROP_METHOD CTest module variable: DROP_METHOD if set, else CTEST_DROP_METHOD DropSite Legacy option. When SubmitURL is not set, it is constructed from DropMethod, DropSiteUser, DropSitePassword, DropSite, and DropLocation. CTest Script variable: CTEST_DROP_SITE CTest module variable: DROP_SITE if set, else CTEST_DROP_SITE DropSitePassword Legacy option. When SubmitURL is not set, it is constructed from DropMethod, DropSiteUser, DropSitePassword, DropSite, and DropLocation. CTest Script variable: CTEST_DROP_SITE_PASSWORD CTest module variable: DROP_SITE_PASSWORD if set, else CTEST_DROP_SITE_PASWORD DropSiteUser Legacy option. When SubmitURL is not set, it is constructed from DropMethod, DropSiteUser, DropSitePassword, DropSite, and DropLocation. CTest Script variable: CTEST_DROP_SITE_USER CTest module variable: DROP_SITE_USER if set, else CTEST_DROP_SITE_USER IsCDash Legacy option. Not used. CTest Script variable: CTEST_DROP_SITE_CDASH CTest module variable: CTEST_DROP_SITE_CDASH ScpCommand Legacy option. Not used. CTest Script variable: CTEST_SCP_COMMAND CTest module variable: SCPCOMMAND Site Describe the dashboard client host site with a short string. (Hostname, domain, etc.) CTest Script variable: CTEST_SITE CTest module variable: SITE, initialized by the site_name() command SubmitURL The http or https URL of the dashboard server to send the submission to. CTest Script variable: CTEST_SUBMIT_URL CTest module variable: SUBMIT_URL if set, else CTEST_SUBMIT_URL TriggerSite Legacy option. Not used. CTest Script variable: CTEST_TRIGGER_SITE CTest module variable: TRIGGER_SITE if set, else CTEST_TRIGGER_SITE Show as JSON Object Model When the --show-only=json-v1 command line option is given, the test information is output in JSON format. Version 1.0 of the JSON object model is defined as follows: kind The string “ctestInfo”. version A JSON object specifying the version components. Its members are major A non-negative integer specifying the major version component. minor A non-negative integer specifying the minor version component. backtraceGraph JSON object representing backtrace information with the following members: commands List of command names. files List of file names. nodes List of node JSON objects with members: command Index into the commands member of the backtraceGraph. file Index into the files member of the backtraceGraph. line Line number in the file where the backtrace was added. parent Index into the nodes member of the backtraceGraph representing the parent in the graph. tests A JSON array listing information about each test. Each entry is a JSON object with members: name Test name. config Configuration that the test can run on. Empty string means any config. command List where the first element is the test command and the remaining elements are the command arguments. backtrace Index into the nodes member of the backtraceGraph. properties Test properties. Can contain keys for each of the supported test properties. Resource Allocation CTest provides a mechanism for tests to specify the resources that they need in a fine-grained way, and for users to specify the resources availiable on the running machine. This allows CTest to internally keep track of which resources are in use and which are free, scheduling tests in a way that prevents them from trying to claim resources that are not available. When the resource allocation feature is used, CTest will not oversubscribe resources. For example, if a resource has 8 slots, CTest will not run tests that collectively use more than 8 slots at a time. This has the effect of limiting how many tests can run at any given time, even if a high -j argument is used, if those tests all use some slots from the same resource. In addition, it means that a single test that uses more of a resource than is available on a machine will not run at all (and will be reported as Not Run). A common use case for this feature is for tests that require the use of a GPU. Multiple tests can simultaneously allocate memory from a GPU, but if too many tests try to do this at once, some of them will fail to allocate, resulting in a failed test, even though the test would have succeeded if it had the memory it needed. By using the resource allocation feature, each test can specify how much memory it requires from a GPU, allowing CTest to schedule tests in a way that running several of these tests at once does not exhaust the GPU’s memory pool. Please note that CTest has no concept of what a GPU is or how much memory it has, nor does it have any way of communicating with a GPU to retrieve this information or perform any memory management. CTest simply keeps track of a list of abstract resource types, each of which has a certain number of slots available for tests to use. Each test specifies the number of slots that it requires from a certain resource, and CTest then schedules them in a way that prevents the total number of slots in use from exceeding the listed capacity. When a test is executed, and slots from a resource are allocated to that test, tests may assume that they have exclusive use of those slots for the duration of the test’s process. The CTest resource allocation feature consists of two inputs: The resource specification file, described below, which describes the resources available on the system. The RESOURCE_GROUPS property of tests, which describes the resources required by the test. When CTest runs a test, the resources allocated to that test are passed in the form of a set of environment variables as described below. Using this information to decide which resource to connect to is left to the test writer. The RESOURCE_GROUPS property tells CTest what resources a test expects to use grouped in a way meaningful to the test. The test itself must read the environment variables to determine which resources have been allocated to each group. For example, each group may correspond to a process the test will spawn when executed. Note that even if a test specifies a RESOURCE_GROUPS property, it is still possible for that to test to run without any resource allocation (and without the corresponding environment variables) if the user does not pass a resource specification file. Passing this file, either through the --resource-spec-file command-line argument or the RESOURCE_SPEC_FILE argument to ctest_test(), is what activates the resource allocation feature. Tests should check the CTEST_RESOURCE_GROUP_COUNT environment variable to find out whether or not resource allocation is activated. This variable will always (and only) be defined if resource allocation is activated. If resource allocation is not activated, then the CTEST_RESOURCE_GROUP_COUNT variable will not exist, even if it exists for the parent ctest process. If a test absolutely must have resource allocation, then it can return a failing exit code or use the SKIP_RETURN_CODE or SKIP_REGULAR_EXPRESSION properties to indicate a skipped test. Resource Specification File The resource specification file is a JSON file which is passed to CTest, either on the ctest(1) command line as --resource-spec-file, or as the RESOURCE_SPEC_FILE argument of ctest_test(). The resource specification file must be a JSON object. All examples in this document assume the following resource specification file: { "version": { "major": 1, "minor": 0 }, "local": [ { "gpus": [ { "id": "0", "slots": 2 }, { "id": "1", "slots": 4 }, { "id": "2", "slots": 2 }, { "id": "3" } ], "crypto_chips": [ { "id": "card0", "slots": 4 } ] } ] } The members are: version An object containing a major integer field and a minor integer field. Currently, the only supported version is major 1, minor 0. Any other value is an error. local A JSON array of resource sets present on the system. Currently, this array is restricted to being of size 1. Each array element is a JSON object with members whose names are equal to the desired resource types, such as gpus. These names must start with a lowercase letter or an underscore, and subsequent characters can be a lowercase letter, a digit, or an underscore. Uppercase letters are not allowed, because certain platforms have case-insensitive environment variables. See the Environment Variables section below for more information. It is recommended that the resource type name be the plural of a noun, such as gpus or crypto_chips (and not gpu or crypto_chip.) Please note that the names gpus and crypto_chips are just examples, and CTest does not interpret them in any way. You are free to make up any resource type you want to meet your own requirements. The value for each resource type is a JSON array consisting of JSON objects, each of which describe a specific instance of the specified resource. These objects have the following members: id A string consisting of an identifier for the resource. Each character in the identifier can be a lowercase letter, a digit, or an underscore. Uppercase letters are not allowed. Identifiers must be unique within a resource type. However, they do not have to be unique across resource types. For example, it is valid to have a gpus resource named 0 and a crypto_chips resource named 0, but not two gpus resources both named 0. Please note that the IDs 0, 1, 2, 3, and card0 are just examples, and CTest does not interpret them in any way. You are free to make up any IDs you want to meet your own requirements. slots An optional unsigned number specifying the number of slots available on the resource. For example, this could be megabytes of RAM on a GPU, or cryptography units available on a cryptography chip. If slots is not specified, a default value of 1 is assumed. In the example file above, there are four GPUs with ID’s 0 through 3. GPU 0 has 2 slots, GPU 1 has 4, GPU 2 has 2, and GPU 3 has a default of 1 slot. There is also one cryptography chip with 4 slots. RESOURCE_GROUPS Property See RESOURCE_GROUPS for a description of this property. Environment Variables Once CTest has decided which resources to allocate to a test, it passes this information to the test executable as a series of environment variables. For each example below, we will assume that the test in question has a RESOURCE_GROUPS property of 2,gpus:2;gpus:4,gpus:1,crypto_chips:2. The following variables are passed to the test process: CTEST_RESOURCE_GROUP_COUNT The total number of groups specified by the RESOURCE_GROUPS property. For example: CTEST_RESOURCE_GROUP_COUNT=3 This variable will only be defined if ctest(1) has been given a --resource-spec-file, or if ctest_test() has been given a RESOURCE_SPEC_FILE. If no resource specification file has been given, this variable will not be defined. CTEST_RESOURCE_GROUP_<num> The list of resource types allocated to each group, with each item separated by a comma. <num> is a number from zero to CTEST_RESOURCE_GROUP_COUNT minus one. CTEST_RESOURCE_GROUP_<num> is defined for each <num> in this range. For example: CTEST_RESOURCE_GROUP_0=gpus CTEST_RESOURCE_GROUP_1=gpus CTEST_RESOURCE_GROUP_2=crypto_chips,gpus CTEST_RESOURCE_GROUP_<num>_<resource-type> The list of resource IDs and number of slots from each ID allocated to each group for a given resource type. This variable consists of a series of pairs, each pair separated by a semicolon, and with the two items in the pair separated by a comma. The first item in each pair is id: followed by the ID of a resource of type <resource-type>, and the second item is slots: followed by the number of slots from that resource allocated to the given group. For example: CTEST_RESOURCE_GROUP_0_GPUS=id:0,slots:2 CTEST_RESOURCE_GROUP_1_GPUS=id:2,slots:2 CTEST_RESOURCE_GROUP_2_GPUS=id:1,slots:4;id:3,slots:1 CTEST_RESOURCE_GROUP_2_CRYPTO_CHIPS=id:card0,slots:2 In this example, group 0 gets 2 slots from GPU 0, group 1 gets 2 slots from GPU 2, and group 2 gets 4 slots from GPU 1, 1 slot from GPU 3, and 2 slots from cryptography chip card0. <num> is a number from zero to CTEST_RESOURCE_GROUP_COUNT minus one. <resource-type> is the name of a resource type, converted to uppercase. CTEST_RESOURCE_GROUP_<num>_<resource-type> is defined for the product of each <num> in the range listed above and each resource type listed in CTEST_RESOURCE_GROUP_<num>. Because some platforms have case-insensitive names for environment variables, the names of resource types may not clash in a case-insensitive environment. Because of this, for the sake of simplicity, all resource types must be listed in all lowercase in the resource specification file and in the RESOURCE_GROUPS property, and they are converted to all uppercase in the CTEST_RESOURCE_GROUP_<num>_<resource-type> environment variable. See Also The following resources are available to get help using CMake: Home Page https://cmake.org The primary starting point for learning about CMake. Online Documentation and Community Resources https://cmake.org/documentation Links to available documentation and community resources may be found on this web page. Discourse Forum https://discourse.cmake.org The Discourse Forum hosts discussion and questions about CMake.
InvalidOptionsException class InvalidOptionsException extends ValidatorException Methods __construct($message, array $options) getOptions() Details __construct($message, array $options) Parameters $message array $options getOptions()
AbstractExtension class AbstractExtension implements FormExtensionInterface Methods FormTypeInterface getType(string $name) Returns a type by name. bool hasType(string $name) Returns whether the given type is supported. FormTypeExtensionInterface[] getTypeExtensions(string $name) Returns the extensions for the given type. bool hasTypeExtensions(string $name) Returns whether this extension provides type extensions for the given type. FormTypeGuesserInterface|null getTypeGuesser() Returns the type guesser provided by this extension. Details FormTypeInterface getType(string $name) Returns a type by name. Parameters string $name The name of the type Return Value FormTypeInterface The type Exceptions InvalidArgumentException if the given type is not supported by this extension bool hasType(string $name) Returns whether the given type is supported. Parameters string $name The name of the type Return Value bool Whether the type is supported by this extension FormTypeExtensionInterface[] getTypeExtensions(string $name) Returns the extensions for the given type. Parameters string $name The name of the type Return Value FormTypeExtensionInterface[] An array of extensions as FormTypeExtensionInterface instances bool hasTypeExtensions(string $name) Returns whether this extension provides type extensions for the given type. Parameters string $name The name of the type Return Value bool Whether the given type has extensions FormTypeGuesserInterface|null getTypeGuesser() Returns the type guesser provided by this extension. Return Value FormTypeGuesserInterface|null The type guesser
onyx_lldp_interface - Manage LLDP interfaces configuration on Mellanox ONYX network devices New in version 2.5. Synopsis Parameters Examples Return Values Status Author Synopsis This module provides declarative management of LLDP interfaces configuration on Mellanox ONYX network devices. Parameters Parameter Choices/Defaults Comments aggregate List of interfaces LLDP should be configured on. name Name of the interface LLDP should be configured on. purge Choices: no ← yes Purge interfaces not defined in the aggregate parameter. state Choices: present ← absent enabled disabled State of the LLDP configuration. Examples - name: Configure LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: present - name: Disable LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: disabled - name: Enable LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: enabled - name: Delete LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: absent - name: Create aggregate of LLDP interface configurations onyx_lldp_interface: aggregate: - { name: Eth1/1 } - { name: Eth1/2 } state: present - name: Delete aggregate of LLDP interface configurations onyx_lldp_interface: aggregate: - { name: Eth1/1 } - { name: Eth1/2 } state: absent Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description commands list always. The list of configuration mode commands to send to the device Sample: ['interface ethernet 1/1 lldp transmit', 'interface ethernet 1/1 lldp receive'] Status This module is flagged as preview which means that it is not guaranteed to have a backwards compatible interface. Author Samer Deeb (@samerd) Hint If you notice any issues in this documentation you can edit this document to improve it. © 2012–2018 Michael DeHaan
HEADER_SET New in version 3.23. Semicolon-separated list of files in the target's default header set, (i.e. the file set with name and type HEADERS). If any of the paths are relative, they are computed relative to the target's source directory. The property supports generator expressions. This property is normally only set by target_sources(FILE_SET) rather than being manipulated directly. See HEADER_SET_<NAME> for the list of files in other header sets.
public function LanguageManagerInter8b7c:f320:99b9:690f:4595:cd17:293a:c069getDefaultLockedLanguages public LanguageManagerInter8b7c:f320:99b9:690f:4595:cd17:293a:c069getDefaultLockedLanguages($weight = 0) Returns a list of the default locked languages. Parameters int $weight: (optional) An integer value that is used as the start value for the weights of the locked languages. Return value \Drupal\Core\Language\LanguageInterface[] An array of language objects. File core/lib/Drupal/Core/Language/LanguageManagerInterface.php, line 128 Class LanguageManagerInterface Common interface for the language manager service. Namespace Drupal\Core\Language Code public function getDefaultLockedLanguages($weight = 0);
gen_event Module gen_event Module summary Generic event handling behavior. Description This behavior module provides event handling functionality. It consists of a generic event manager process with any number of event handlers that are added and deleted dynamically. An event manager implemented using this module has a standard set of interface functions and includes functionality for tracing and error reporting. It also fits into an OTP supervision tree. For more information, see OTP Design Principles. Each event handler is implemented as a callback module exporting a predefined set of functions. The relationship between the behavior functions and the callback functions is as follows: gen_event module Callback module ---------------- --------------- gen_event:start gen_event:start_link -----> - gen_event:add_handler gen_event:add_sup_handler -----> Module:init/1 gen_event:notify gen_event:sync_notify -----> Module:handle_event/2 gen_event:call -----> Module:handle_call/2 - -----> Module:handle_info/2 gen_event:delete_handler -----> Module:terminate/2 gen_event:swap_handler gen_event:swap_sup_handler -----> Module1:terminate/2 Module2:init/1 gen_event:which_handlers -----> - gen_event:stop -----> Module:terminate/2 - -----> Module:code_change/3 As each event handler is one callback module, an event manager has many callback modules that are added and deleted dynamically. gen_event is therefore more tolerant of callback module errors than the other behaviors. If a callback function for an installed event handler fails with Reason, or returns a bad value Term, the event manager does not fail. It deletes the event handler by calling callback function Module:terminate/2, giving as argument {error,{'EXIT',Reason}} or {error,Term}, respectively. No other event handler is affected. A gen_event process handles system messages as described in sys(3). The sys module can be used for debugging an event manager. Notice that an event manager does trap exit signals automatically. The gen_event process can go into hibernation (see erlang:hibernate/3) if a callback function in a handler module specifies hibernate in its return value. This can be useful if the server is expected to be idle for a long time. However, use this feature with care, as hibernation implies at least two garbage collections (when hibernating and shortly after waking up) and is not something you want to do between each event handled by a busy event manager. Notice that when multiple event handlers are invoked, it is sufficient that one single event handler returns a hibernate request for the whole event manager to go into hibernation. Unless otherwise stated, all functions in this module fail if the specified event manager does not exist or if bad arguments are specified. Data types handler() = atom() | {atom(), term()} handler_args() = term() add_handler_ret() = ok | term() | {'EXIT', term()} del_handler_ret() = ok | term() | {'EXIT', term()} Exports add_handler(EventMgrRef, Handler, Args) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler = Module | {Module,Id}  Module = atom()  Id = term() Args = term() Result = ok | {'EXIT',Reason} | term()  Reason = term() Adds a new event handler to event manager EventMgrRef. The event manager calls Module:init/1 to initiate the event handler and its internal state. EventMgrRef can be any of the following: The pid Name, if the event manager is locally registered {Name,Node}, if the event manager is locally registered at another node {global,GlobalName}, if the event manager is globally registered {via,Module,ViaName}, if the event manager is registered through an alternative process registry Handler is the name of the callback module Module or a tuple {Module,Id}, where Id is any term. The {Module,Id} representation makes it possible to identify a specific event handler when many event handlers use the same callback module. Args is any term that is passed as the argument to Module:init/1. If Module:init/1 returns a correct value indicating successful completion, the event manager adds the event handler and this function returns ok. If Module:init/1 fails with Reason or returns {error,Reason}, the event handler is ignored and this function returns {'EXIT',Reason} or {error,Reason}, respectively. add_sup_handler(EventMgrRef, Handler, Args) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler = Module | {Module,Id}  Module = atom()  Id = term() Args = term() Result = ok | {'EXIT',Reason} | term()  Reason = term() Adds a new event handler in the same way as add_handler/3, but also supervises the connection between the event handler and the calling process. If the calling process later terminates with Reason, the event manager deletes the event handler by calling Module:terminate/2 with {stop,Reason} as argument. If the event handler is deleted later, the event manager sends a message{gen_event_EXIT,Handler,Reason} to the calling process. Reason is one of the following: normal, if the event handler has been removed because of a call to delete_handler/3, or remove_handler has been returned by a callback function (see below). shutdown, if the event handler has been removed because the event manager is terminating. {swapped,NewHandler,Pid}, if the process Pid has replaced the event handler with another event handler NewHandler using a call to swap_handler/3 or swap_sup_handler/3. A term, if the event handler is removed because of an error. Which term depends on the error. For a description of the arguments and return values, see add_handler/3. call(EventMgrRef, Handler, Request) -> Resultcall(EventMgrRef, Handler, Request, Timeout) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler = Module | {Module,Id}  Module = atom()  Id = term() Request = term() Timeout = int()>0 | infinity Result = Reply | {error,Error}  Reply = term()  Error = bad_module | {'EXIT',Reason} | term()   Reason = term() Makes a synchronous call to event handler Handler installed in event manager EventMgrRef by sending a request and waiting until a reply arrives or a time-out occurs. The event manager calls Module:handle_call/2 to handle the request. For a description of EventMgrRef and Handler, see add_handler/3. Request is any term that is passed as one of the arguments to Module:handle_call/2. Timeout is an integer greater than zero that specifies how many milliseconds to wait for a reply, or the atom infinity to wait indefinitely. Defaults to 5000. If no reply is received within the specified time, the function call fails. The return value Reply is defined in the return value of Module:handle_call/2. If the specified event handler is not installed, the function returns {error,bad_module}. If the callback function fails with Reason or returns an unexpected value Term, this function returns {error,{'EXIT',Reason}} or {error,Term}, respectively. delete_handler(EventMgrRef, Handler, Args) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler = Module | {Module,Id}  Module = atom()  Id = term() Args = term() Result = term() | {error,module_not_found} | {'EXIT',Reason}  Reason = term() Deletes an event handler from event manager EventMgrRef. The event manager calls Module:terminate/2 to terminate the event handler. For a description of EventMgrRef and Handler, see add_handler/3. Args is any term that is passed as one of the arguments to Module:terminate/2. The return value is the return value of Module:terminate/2. If the specified event handler is not installed, the function returns {error,module_not_found}. If the callback function fails with Reason, the function returns {'EXIT',Reason}. notify(EventMgrRef, Event) -> oksync_notify(EventMgrRef, Event) -> ok Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Event = term() Sends an event notification to event manager EventMgrRef. The event manager calls Module:handle_event/2 for each installed event handler to handle the event. notify/2 is asynchronous and returns immediately after the event notification has been sent. sync_notify/2 is synchronous in the sense that it returns ok after the event has been handled by all event handlers. For a description of EventMgrRef, see add_handler/3. Event is any term that is passed as one of the arguments to Module:handle_event/2. notify/1 does not fail even if the specified event manager does not exist, unless it is specified as Name. start() -> Resultstart(EventMgrName) -> Result Types: EventMgrName = {local,Name} | {global,GlobalName} | {via,Module,ViaName}  Name = atom()  GlobalName = ViaName = term() Result = {ok,Pid} | {error,{already_started,Pid}}  Pid = pid() Creates a stand-alone event manager process, that is, an event manager that is not part of a supervision tree and thus has no supervisor. For a description of the arguments and return values, see start_link/0,1. start_link() -> Resultstart_link(EventMgrName) -> Result Types: EventMgrName = {local,Name} | {global,GlobalName} | {via,Module,ViaName}  Name = atom()  GlobalName = ViaName = term() Result = {ok,Pid} | {error,{already_started,Pid}}  Pid = pid() Creates an event manager process as part of a supervision tree. The function is to be called, directly or indirectly, by the supervisor. For example, it ensures that the event manager is linked to the supervisor. If EventMgrName={local,Name}, the event manager is registered locally as Name using register/2. If EventMgrName={global,GlobalName}, the event manager is registered globally as GlobalName using global:register_name/2. If no name is provided, the event manager is not registered. If EventMgrName={via,Module,ViaName}, the event manager registers with the registry represented by Module. The Module callback is to export the functions register_name/2, unregister_name/1, whereis_name/1, and send/2, which are to behave as the corresponding functions in global. Thus, {via,global,GlobalName} is a valid reference. If the event manager is successfully created, the function returns {ok,Pid}, where Pid is the pid of the event manager. If a process with the specified EventMgrName exists already, the function returns {error,{already_started,Pid}}, where Pid is the pid of that process. stop(EventMgrRef) -> okstop(EventMgrRef, Reason, Timeout) -> ok Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid() Name = Node = atom() GlobalName = ViaName = term() Reason = term() Timeout = int()>0 | infinity Orders event manager EventMgrRef to exit with the specifies Reason and waits for it to terminate. Before terminating, gen_event calls Module:terminate(stop,...) for each installed event handler. The function returns ok if the event manager terminates with the expected reason. Any other reason than normal, shutdown, or {shutdown,Term} causes an error report to be issued using error_logger:format/2. The default Reason is normal. Timeout is an integer greater than zero that specifies how many milliseconds to wait for the event manager to terminate, or the atom infinity to wait indefinitely. Defaults to infinity. If the event manager has not terminated within the specified time, a timeout exception is raised. If the process does not exist, a noproc exception is raised. For a description of EventMgrRef, see add_handler/3. swap_handler(EventMgrRef, {Handler1,Args1}, {Handler2,Args2}) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler1 = Handler2 = Module | {Module,Id}  Module = atom()  Id = term() Args1 = Args2 = term() Result = ok | {error,Error}  Error = {'EXIT',Reason} | term()   Reason = term() Replaces an old event handler with a new event handler in event manager EventMgrRef. For a description of the arguments, see add_handler/3. First the old event handler Handler1 is deleted. The event manager calls Module1:terminate(Args1, ...), where Module1 is the callback module of Handler1, and collects the return value. Then the new event handler Handler2 is added and initiated by calling Module2:init({Args2,Term}), where Module2 is the callback module of Handler2 and Term is the return value of Module1:terminate/2. This makes it possible to transfer information from Handler1 to Handler2. The new handler is added even if the the specified old event handler is not installed, in which case Term=error, or if Module1:terminate/2 fails with Reason, in which case Term={'EXIT',Reason}. The old handler is deleted even if Module2:init/1 fails. If there was a supervised connection between Handler1 and a process Pid, there is a supervised connection between Handler2 and Pid instead. If Module2:init/1 returns a correct value, this function returns ok. If Module2:init/1 fails with Reason or returns an unexpected value Term, this function returns {error,{'EXIT',Reason}} or {error,Term}, respectively. swap_sup_handler(EventMgrRef, {Handler1,Args1}, {Handler2,Args2}) -> Result Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler1 = Handler 2 = Module | {Module,Id}  Module = atom()  Id = term() Args1 = Args2 = term() Result = ok | {error,Error}  Error = {'EXIT',Reason} | term()   Reason = term() Replaces an event handler in event manager EventMgrRef in the same way as swap_handler/3, but also supervises the connection between Handler2 and the calling process. For a description of the arguments and return values, see swap_handler/3. which_handlers(EventMgrRef) -> [Handler] Types: EventMgrRef = Name | {Name,Node} | {global,GlobalName} | {via,Module,ViaName} | pid()  Name = Node = atom()  GlobalName = ViaName = term() Handler = Module | {Module,Id}  Module = atom()  Id = term() Returns a list of all event handlers installed in event manager EventMgrRef. For a description of EventMgrRef and Handler, see add_handler/3. Callback Functions The following functions are to be exported from a gen_event callback module. Exports Module:code_change(OldVsn, State, Extra) -> {ok, NewState} Types: OldVsn = Vsn | {down, Vsn}   Vsn = term() State = NewState = term() Extra = term() This function is called for an installed event handler that is to update its internal state during a release upgrade/downgrade, that is, when the instruction {update,Module,Change,...}, where Change={advanced,Extra}, is specified in the .appup file. For more information, see OTP Design Principles. For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old version of the callback module Module. If no such attribute is defined, the version is the checksum of the Beam file. State is the internal state of the event handler. Extra is passed "as is" from the {advanced,Extra} part of the update instruction. The function is to return the updated internal state. Module:format_status(Opt, [PDict, State]) -> Status Types: Opt = normal | terminate PDict = [{Key, Value}] State = term() Status = term() Note This callback is optional, so event handler modules need not export it. If a handler does not export this function, the gen_event module uses the handler state directly for the purposes described below. This function is called by a gen_event process in the following situations: One of sys:get_status/1,2 is invoked to get the gen_event status. Opt is set to the atom normal for this case. The event handler terminates abnormally and gen_event logs an error. Opt is set to the atom terminate for this case. This function is useful for changing the form and appearance of the event handler state for these cases. An event handler callback module wishing to change the the sys:get_status/1,2 return value as well as how its state appears in termination error logs, exports an instance of format_status/2 that returns a term describing the current state of the event handler. PDict is the current value of the process dictionary of gen_event. State is the internal state of the event handler. The function is to return Status, a term that change the details of the current state of the event handler. Any term is allowed for Status. The gen_event module uses Status as follows: When sys:get_status/1,2 is called, gen_event ensures that its return value contains Status in place of the state term of the event handler. When an event handler terminates abnormally, gen_event logs Status in place of the state term of the event handler. One use for this function is to return compact alternative state representations to avoid that large state terms are printed in log files. Module:handle_call(Request, State) -> Result Types: Request = term() State = term() Result = {ok,Reply,NewState} | {ok,Reply,NewState,hibernate}  | {swap_handler,Reply,Args1,NewState,Handler2,Args2}  | {remove_handler, Reply}  Reply = term()  NewState = term()  Args1 = Args2 = term()  Handler2 = Module2 | {Module2,Id}   Module2 = atom()   Id = term() Whenever an event manager receives a request sent using call/3,4, this function is called for the specified event handler to handle the request. Request is the Request argument of call/3,4. State is the internal state of the event handler. The return values are the same as for Module:handle_event/2 except that they also contain a term Reply, which is the reply to the client as the return value of call/3,4. Module:handle_event(Event, State) -> Result Types: Event = term() State = term() Result = {ok,NewState} | {ok,NewState,hibernate}   | {swap_handler,Args1,NewState,Handler2,Args2} | remove_handler  NewState = term()  Args1 = Args2 = term()  Handler2 = Module2 | {Module2,Id}   Module2 = atom()   Id = term() Whenever an event manager receives an event sent using notify/2 or sync_notify/2, this function is called for each installed event handler to handle the event. Event is the Event argument of notify/2/sync_notify/2. State is the internal state of the event handler. If {ok,NewState} or {ok,NewState,hibernate} is returned, the event handler remains in the event manager with the possible updated internal state NewState. If {ok,NewState,hibernate} is returned, the event manager also goes into hibernation (by calling proc_lib:hibernate/3), waiting for the next event to occur. It is sufficient that one of the event handlers return {ok,NewState,hibernate} for the whole event manager process to hibernate. If {swap_handler,Args1,NewState,Handler2,Args2} is returned, the event handler is replaced by Handler2 by first calling Module:terminate(Args1,NewState) and then Module2:init({Args2,Term}), where Term is the return value of Module:terminate/2. For more information, see swap_handler/3. If remove_handler is returned, the event handler is deleted by calling Module:terminate(remove_handler,State). Module:handle_info(Info, State) -> Result Types: Info = term() State = term() Result = {ok,NewState} | {ok,NewState,hibernate}  | {swap_handler,Args1,NewState,Handler2,Args2} | remove_handler  NewState = term()  Args1 = Args2 = term()  Handler2 = Module2 | {Module2,Id}   Module2 = atom()   Id = term() This function is called for each installed event handler when an event manager receives any other message than an event or a synchronous request (or a system message). Info is the received message. For a description of State and possible return values, see Module:handle_event/2. Module:init(InitArgs) -> {ok,State} | {ok,State,hibernate} | {error,Reason} Types: InitArgs = Args | {Args,Term}  Args = Term = term() State = term() Reason = term() Whenever a new event handler is added to an event manager, this function is called to initialize the event handler. If the event handler is added because of a call to add_handler/3 or add_sup_handler/3, InitArgs is the Args argument of these functions. If the event handler replaces another event handler because of a call to swap_handler/3 or swap_sup_handler/3, or because of a swap return tuple from one of the other callback functions, InitArgs is a tuple {Args,Term}, where Args is the argument provided in the function call/return tuple and Term is the result of terminating the old event handler, see swap_handler/3. If successful, the function returns {ok,State} or {ok,State,hibernate}, where State is the initial internal state of the event handler. If {ok,State,hibernate} is returned, the event manager goes into hibernation (by calling proc_lib:hibernate/3), waiting for the next event to occur. Module:terminate(Arg, State) -> term() Types: Arg = Args | {stop,Reason} | stop | remove_handler  | {error,{'EXIT',Reason}} | {error,Term}  Args = Reason = Term = term() Whenever an event handler is deleted from an event manager, this function is called. It is to be the opposite of Module:init/1 and do any necessary cleaning up. If the event handler is deleted because of a call to delete_handler/3, swap_handler/3, or swap_sup_handler/3, Arg is the Args argument of this function call. Arg={stop,Reason} if the event handler has a supervised connection to a process that has terminated with reason Reason. Arg=stop if the event handler is deleted because the event manager is terminating. The event manager terminates if it is part of a supervision tree and it is ordered by its supervisor to terminate. Even if it is not part of a supervision tree, it terminates if it receives an 'EXIT' message from its parent. Arg=remove_handler if the event handler is deleted because another callback function has returned remove_handler or {remove_handler,Reply}. Arg={error,Term} if the event handler is deleted because a callback function returned an unexpected value Term, or Arg={error,{'EXIT',Reason}} if a callback function failed. State is the internal state of the event handler. The function can return any term. If the event handler is deleted because of a call to gen_event:delete_handler/3, the return value of that function becomes the return value of this function. If the event handler is to be replaced with another event handler because of a swap, the return value is passed to the init function of the new event handler. Otherwise the return value is ignored. See Also supervisor(3), sys(3)
tf.compat.v1.flags.mark_bool_flags_as_mutual_exclusive Ensures that only one flag among flag_names is True. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.app.flags.mark_bool_flags_as_mutual_exclusive tf.compat.v1.flags.mark_bool_flags_as_mutual_exclusive( flag_names, required=False, flag_values=_flagvalues.FLAGS ) Args flag_names [str], names of the flags. required bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False. flag_values flags.FlagValues, optional FlagValues instance where the flags are defined.
sklearn.base.TransformerMixin classsklearn.base.TransformerMixin[source] Mixin class for all transformers in scikit-learn. Methods fit_transform(X[, y]) Fit to data, then transform it. fit_transform(X, y=None, **fit_params)[source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters: Xarray-like of shape (n_samples, n_features) Input samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None Target values (None for unsupervised transformations). **fit_paramsdict Additional fit parameters. Returns: X_newndarray array of shape (n_samples, n_features_new) Transformed array. Examples using sklearn.base.TransformerMixin Approximate nearest neighbors in TSNE
dart:core tryParse method DateTime? tryParse( String formattedString ) Constructs a new DateTime instance based on formattedString. Works like parse except that this function returns null where parse would throw a FormatException. Implementation static DateTime? tryParse(String formattedString) { // TODO: Optimize to avoid throwing. try { return parse(formattedString); } on FormatException { return null; } }
dart:html client property Point client Source @DomName('Touch.clientX') @DomName('Touch.clientY') Point get client => new Point/*<num>*/(__clientX, __clientY);
Selection.rangeCount The Selection.rangeCount read-only property returns the number of ranges in the selection. Before the user has clicked a freshly loaded page, the rangeCount is 0. After the user clicks on the page, rangeCount is 1, even if no selection is visible. A user can normally only select one range at a time, so the rangeCount will usually be 1. Scripting can be used to make the selection contain more than one range. Gecko browsers allow multiple selections across table cells. Firefox allows to select multiple ranges in the document by using Ctrl+click (unless the click occurs within an element that has the display: table-cell CSS property assigned). Value A number. Examples The following example will show the rangeCount every second. Select text in the browser to see it change. HTML <table> <tr><td>a.1<td>a.2 <tr><td>b.1<td>b.2 <tr><td>c.1<td>c.2 JavaScript window.setInterval(function () { console.log(window.getSelection().rangeCount); }, 1000); Result Open your console to see how many ranges are in the selection. In Gecko browsers, you can select multiple ranges across table cells by holding down Ctrl while dragging with the mouse. Specifications Specification Selection API # dom-selection-rangecount Browser compatibility Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet rangeCount 1 12 1 9 ≤12.1 3 1 18 4 ≤12.1 1 1.0 See also Selection, the interface it belongs to. Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Apr 5, 2022, by MDN contributors
Open A BLOB For Incremental I/O int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); This interfaces opens a handle to the BLOB located in row iRow, column zColumn, table zTable in database zDb; in other words, the same BLOB that would be selected by: SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; Parameter zDb is not the filename that contains the database, but rather the symbolic name of the database. For attached databases, this is the name that appears after the AS keyword in the ATTACH statement. For the main database file, the database name is "main". For TEMP tables, the database name is "temp". If the flags parameter is non-zero, then the BLOB is opened for read and write access. If the flags parameter is zero, the BLOB is opened for read-only access. On success, SQLITE_OK is returned and the new BLOB handle is stored in *ppBlob. Otherwise an error code is returned and, unless the error code is SQLITE_MISUSE, *ppBlob is set to NULL. This means that, provided the API is not misused, it is always safe to call sqlite3_blob_close() on *ppBlob after this function it returns. This function fails with SQLITE_ERROR if any of the following are true: Database zDb does not exist, Table zTable does not exist within database zDb, Table zTable is a WITHOUT ROWID table, Column zColumn does not exist, Row iRow is not present in the table, The specified column of row iRow contains a value that is not a TEXT or BLOB value, Column zColumn is part of an index, PRIMARY KEY or UNIQUE constraint and the blob is being opened for read/write access, Foreign key constraints are enabled, column zColumn is part of a child key definition and the blob is being opened for read/write access. Unless it returns SQLITE_MISUSE, this function sets the database connection error code and message accessible via sqlite3_errcode() and sqlite3_errmsg() and related functions. A BLOB referenced by sqlite3_blob_open() may be read using the sqlite3_blob_read() interface and modified by using sqlite3_blob_write(). The BLOB handle can be moved to a different row of the same table using the sqlite3_blob_reopen() interface. However, the column, table, or database of a BLOB handle cannot be changed after the BLOB handle is opened. If the row that a BLOB handle points to is modified by an UPDATE, DELETE, or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". This is true if any column of the row is changed, even a column other than the one the BLOB handle is open on. Calls to sqlite3_blob_read() and sqlite3_blob_write() for an expired BLOB handle fail with a return code of SQLITE_ABORT. Changes written into a BLOB prior to the BLOB expiring are not rolled back by the expiration of the BLOB. Such changes will eventually commit if the transaction continues to completion. Use the sqlite3_blob_bytes() interface to determine the size of the opened blob. The size of a blob may not be changed by this interface. Use the UPDATE SQL command to change the size of a blob. The sqlite3_bind_zeroblob() and sqlite3_result_zeroblob() interfaces and the built-in zeroblob SQL function may be used to create a zero-filled blob to read or write using the incremental-blob interface. To avoid a resource leak, every open BLOB handle should eventually be released by a call to sqlite3_blob_close(). See also: sqlite3_blob_close(), sqlite3_blob_reopen(), sqlite3_blob_read(), sqlite3_blob_bytes(), sqlite3_blob_write(). See also lists of Objects, Constants, and Functions. SQLite is in the Public Domain. https://sqlite.org/c3ref/blob_open.html
git Resource Edit this page in the Chef repository This page is generated from the Chef Infra Client source code. To suggest a change, edit the git.rb file and submit a pull request to the Chef Infra Client repository. All Infra resources page Use the git resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource. Syntax A git resource block manages source control resources that exist in a git repository: git "#{Ch8b7c:f320:99b9:690f:4595:cd17:293a:c069Config[:file_cache_path]}/app_name" do repository node[:app_name][:git_repository] revision node[:app_name][:git_revision] action :sync end The full syntax for all of the properties that are available to the git resource is: git 'name' do additional_remotes Hash # default value: {} checkout_branch String depth Integer destination String # default value: 'name' unless specified enable_checkout true, false # default value: true enable_submodules true, false # default value: false environment Hash group String, Integer remote String # default value: "origin" repository String revision String # default value: "HEAD" ssh_wrapper String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end where: git is the resource. name is the name given to the resource block. action identifies which steps Chef Infra Client will take to bring the node into the desired state. additional_remotes, checkout_branch, depth, destination, enable_checkout, enable_submodules, environment, group, remote, repository, revision, ssh_wrapper, timeout, and user are the properties available to this resource. Actions The git resource has the following actions: :checkout Clone or check out the source. When a checkout is available, this provider does nothing. :export Export the source, excluding or removing any version control artifacts. :nothing This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. :sync Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. Properties The git resource has the following properties: additional_remotes Ruby Type: Hash | Default Value: {} A Hash of additional remotes that are added to the git repository configuration. checkout_branch Ruby Type: String Do a one-time checkout from git or use when a branch in the upstream repository is named deploy. To prevent the git resource from attempting to check out master from master, set enable_checkout to false when using the checkout_branch property. See revision. depth Ruby Type: Integer The number of past revisions to be included in the git shallow clone. Unless specified the default behavior will do a full clone. destination Ruby Type: String | Default Value: The resource block's name The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. enable_checkout Ruby Type: true, false | Default Value: true Check out a repo from master. Set to false when using the checkout_branch attribute to prevent the git resource from attempting to check out master from master. enable_submodules Ruby Type: true, false | Default Value: false Perform a sub-module initialization and update. environment Ruby Type: Hash A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.) Note The git provider automatically sets the ENV['HOME'] and ENV['GIT_SSH'] environment variables. To override this behavior and provide different values, add ENV['HOME'] and/or ENV['GIT_SSH'] to the environment Hash. group Ruby Type: String, Integer The system group that will own the checked-out code. remote Ruby Type: String | Default Value: origin The remote repository to use when synchronizing an existing clone. repository Ruby Type: String The URI of the code repository. revision Ruby Type: String | Default Value: HEAD A branch, tag, or commit to be synchronized with git. This can be symbolic, like HEAD or it can be a source control management-specific revision identifier. See checkout_branch. The value of the revision attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The revision attribute may even be changed in a way where history gets rewritten. Instead of tracking a specific branch or doing a headless checkout, Chef Infra Client maintains its own branch (via the git resource) that does not exist in the upstream repository. Chef Infra Client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch. For example, to explicitly track an upstream repository’s master branch: revision 'master' Use the git rev-parse and git ls-remote commands to verify that Chef Infra Client is synchronizing commits correctly. (Chef Infra Client always runs git ls-remote on the upstream repository to verify the commit is made to the correct repository.) ssh_wrapper Ruby Type: String The path to the wrapper script used when running SSH with git. The GIT_SSH environment variable is set to this. timeout Ruby Type: Integer The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the deploy resource, the value of the timeout property is passed from the deploy resource to the git resource. user Ruby Type: String, Integer | Default Value: `HOME` environment variable of the user running chef-client The system user that will own the checked-out code. Common Resource Functionality Chef resources include common properties, notifications, and resource guards. Common Properties The following properties are common to every resource: compile_time Ruby Type: true, false | Default Value: false Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase). ignore_failure Ruby Type: true, false, :quiet | Default Value: false Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails. retries Ruby Type: Integer | Default Value: 0 The number of attempts to catch exceptions and retry the resource. retry_delay Ruby Type: Integer | Default Value: 2 The delay in seconds between retry attempts. sensitive Ruby Type: true, false | Default Value: false Ensure that sensitive resource data is not logged by Chef Infra Client. Notifications notifies Ruby Type: Symbol, 'Ch8b7c:f320:99b9:690f:4595:cd17:293a:c069Resource[String]' A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for notifies is: notifies :action, 'resource[name]', :timer subscribes Ruby Type: Symbol, 'Ch8b7c:f320:99b9:690f:4595:cd17:293a:c069Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action. Note that subscribes does not apply the specified action to the resource that it listens to - for example: file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for subscribes is: subscribes :action, 'resource[name]', :timer Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0. A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. Properties The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: not_if Prevent a resource from executing when the condition returns true. only_if Allow a resource to execute only if the condition returns true. Examples The following examples demonstrate various approaches for using the git resource in recipes: Use the git mirror git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' action :sync end Use different branches To use different branches, depending on the environment of the node: branch_name = if node.chef_environment == 'QA' 'staging' else 'master' end git '/home/user/deployment' do repository '[email protected]:git_site/deployment.git' revision branch_name action :sync user 'user' group 'test' end Where the branch_name variable is set to staging or master, depending on the environment of the node. Once this is determined, the branch_name variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as deploy, as this is the default value. Run Chef Infra Client in debug mode to verify that the correct branches are being checked out: sudo chef-client -l debug Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command. git "/Users/tsmith/.chef/cache/ruby-build" do repository 'git://github.com/rbenv/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "/Users/tsmith/.chef/cache/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end Notify a resource post-checkout git "/Users/tsmith/.chef/cache/my_app" do repository node['my_app']['git_repository'] revision node['my_app']['git_revision'] action :sync notifies :run, 'bash[compile_my_app]', :immediately end Pass in environment variables git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' environment 'VAR' => 'whatever' action :sync end
jsffi This Module implements types and macros to facilitate the wrapping of, and interaction with JavaScript libraries. Using the provided types JsObject and JsAssoc together with the provided macros allows for smoother interfacing with JavaScript, allowing for example quick and easy imports of JavaScript variables: # Here, we are using jQuery for just a few calls and do not want to wrap the # whole library: # import the document object and the console var document {.importc, nodecl.}: JsObject var console {.importc, nodecl.}: JsObject # import the "$" function proc jq(selector: JsObject): JsObject {.importcpp: "$$(#)".} # Use jQuery to make the following code run, after the document is ready. # This uses an experimental ``.()`` operator for ``JsObject``, to emit # JavaScript calls, when no corresponding proc exists for ``JsObject``. proc main = jq(document).ready(proc() = console.log("Hello JavaScript!") ) Imports macros, tables Types JsKey = concept atypeof(T) cstring.toJsKey(T) is T Source Edit JsObject = ref object of JsRoot Dynamically typed wrapper around a JavaScript object. Source Edit JsAssoc[K; V] = ref object of JsRoot Statically typed wrapper around a JavaScript object. Source Edit js = JsObject Source Edit JsError {...}{.importc: "Error".} = object of JsRoot message*: cstring Source Edit JsEvalError {...}{.importc: "EvalError".} = object of JsError Source Edit JsRangeError {...}{.importc: "RangeError".} = object of JsError Source Edit JsReferenceError {...}{.importc: "ReferenceError".} = object of JsError Source Edit JsSyntaxError {...}{.importc: "SyntaxError".} = object of JsError Source Edit JsTypeError {...}{.importc: "TypeError".} = object of JsError Source Edit JsURIError {...}{.importc: "URIError".} = object of JsError Source Edit Vars jsArguments: JsObject JavaScript's arguments pseudo-variable Source Edit jsNull: JsObject JavaScript's null literal Source Edit jsUndefined: JsObject JavaScript's undefined literal Source Edit jsDirname: cstring JavaScript's __dirname pseudo-variable Source Edit jsFilename: cstring JavaScript's __filename pseudo-variable Source Edit Procs proc toJsKey[T: SomeInteger](text: cstring; t: type T): T {...}{. importcpp: "parseInt(#)".} Source Edit proc toJsKey[T: enum](text: cstring; t: type T): T Source Edit proc toJsKey(text: cstring; t: type cstring): cstring Source Edit proc toJsKey[T: SomeFloat](text: cstring; t: type T): T {...}{. importcpp: "parseFloat(#)".} Source Edit proc isNull[T](x: T): bool {...}{.noSideEffect, importcpp: "(# === null)".} check if a value is exactly null Source Edit proc isUndefined[T](x: T): bool {...}{.noSideEffect, importcpp: "(# === undefined)".} check if a value is exactly undefined Source Edit proc newJsObject(): JsObject {...}{.importcpp: "{@}".} Creates a new empty JsObject Source Edit proc newJsAssoc[K: JsKey; V](): JsAssoc[K, V] {...}{.importcpp: "{@}".} Creates a new empty JsAssoc with key type K and value type V. Source Edit proc hasOwnProperty(x: JsObject; prop: cstring): bool {...}{. importcpp: "#.hasOwnProperty(#)".} Checks, whether x has a property of name prop. Source Edit proc jsTypeOf(x: JsObject): cstring {...}{.importcpp: "typeof(#)".} Returns the name of the JsObject's JavaScript type as a cstring. Source Edit proc jsNew(x: auto): JsObject {...}{.importcpp: "(new #)".} Turns a regular function call into an invocation of the JavaScript's new operator Source Edit proc jsDelete(x: auto): JsObject {...}{.importcpp: "(delete #)".} JavaScript's delete operator Source Edit proc require(module: cstring): JsObject {...}{.importc.} JavaScript's require function Source Edit proc to(x: JsObject; T: typedesc): T:type {...}{.importcpp: "(#)".} Converts a JsObject x to type T. Source Edit proc toJs[T](val: T): JsObject {...}{.importcpp: "(#)".} Converts a value of any type to type JsObject Source Edit proc `&`(a, b: cstring): cstring {...}{.importcpp: "(# + #)".} Concatenation operator for JavaScript strings Source Edit proc `+`(x, y: JsObject): JsObject {...}{.importcpp: "(# + #)".} Source Edit proc `-`(x, y: JsObject): JsObject {...}{.importcpp: "(# - #)".} Source Edit proc `*`(x, y: JsObject): JsObject {...}{.importcpp: "(# * #)".} Source Edit proc `/`(x, y: JsObject): JsObject {...}{.importcpp: "(# / #)".} Source Edit proc `%`(x, y: JsObject): JsObject {...}{.importcpp: "(# % #)".} Source Edit proc `+=`(x, y: JsObject): JsObject {...}{.importcpp: "(# += #)", discardable.} Source Edit proc `-=`(x, y: JsObject): JsObject {...}{.importcpp: "(# -= #)", discardable.} Source Edit proc `*=`(x, y: JsObject): JsObject {...}{.importcpp: "(# *= #)", discardable.} Source Edit proc `/=`(x, y: JsObject): JsObject {...}{.importcpp: "(# /= #)", discardable.} Source Edit proc `%=`(x, y: JsObject): JsObject {...}{.importcpp: "(# %= #)", discardable.} Source Edit proc `++`(x: JsObject): JsObject {...}{.importcpp: "(++#)".} Source Edit proc `--`(x: JsObject): JsObject {...}{.importcpp: "(--#)".} Source Edit proc `>`(x, y: JsObject): JsObject {...}{.importcpp: "(# > #)".} Source Edit proc `<`(x, y: JsObject): JsObject {...}{.importcpp: "(# < #)".} Source Edit proc `>=`(x, y: JsObject): JsObject {...}{.importcpp: "(# >= #)".} Source Edit proc `<=`(x, y: JsObject): JsObject {...}{.importcpp: "(# <= #)".} Source Edit proc `and`(x, y: JsObject): JsObject {...}{.importcpp: "(# && #)".} Source Edit proc `or`(x, y: JsObject): JsObject {...}{.importcpp: "(# || #)".} Source Edit proc `not`(x: JsObject): JsObject {...}{.importcpp: "(!#)".} Source Edit proc `in`(x, y: JsObject): JsObject {...}{.importcpp: "(# in #)".} Source Edit proc `[]`(obj: JsObject; field: cstring): JsObject {...}{.importcpp: "#[#]".} Return the value of a property of name field from a JsObject obj. Source Edit proc `[]`(obj: JsObject; field: int): JsObject {...}{.importcpp: "#[#]".} Return the value of a property of name field from a JsObject obj. Source Edit proc `[]=`[T](obj: JsObject; field: cstring; val: T) {...}{.importcpp: "#[#] = #".} Set the value of a property of name field in a JsObject obj to v. Source Edit proc `[]=`[T](obj: JsObject; field: int; val: T) {...}{.importcpp: "#[#] = #".} Set the value of a property of name field in a JsObject obj to v. Source Edit proc `[]`[K: JsKey; V](obj: JsAssoc[K, V]; field: K): V {...}{.importcpp: "#[#]".} Return the value of a property of name field from a JsAssoc obj. Source Edit proc `[]=`[K: JsKey; V](obj: JsAssoc[K, V]; field: K; val: V) {...}{. importcpp: "#[#] = #".} Set the value of a property of name field in a JsAssoc obj to v. Source Edit proc `[]`[V](obj: JsAssoc[cstring, V]; field: string): V Source Edit proc `[]=`[V](obj: JsAssoc[cstring, V]; field: string; val: V) Source Edit proc `==`(x, y: JsRoot): bool {...}{.importcpp: "(# === #)".} Compare two JsObjects or JsAssocs. Be careful though, as this is comparison like in JavaScript, so if your JsObjects are in fact JavaScript Objects, and not strings or numbers, this is a comparison of references. Source Edit Iterators iterator pairs(obj: JsObject): (cstring, JsObject) {...}{.raises: [], tags: [].} Yields tuples of type (cstring, JsObject), with the first entry being the name of a fields in the JsObject and the second being its value wrapped into a JsObject. Source Edit iterator items(obj: JsObject): JsObject {...}{.raises: [], tags: [].} Yields the values of each field in a JsObject, wrapped into a JsObject. Source Edit iterator keys(obj: JsObject): cstring {...}{.raises: [], tags: [].} Yields the names of each field in a JsObject. Source Edit iterator pairs[K: JsKey; V](assoc: JsAssoc[K, V]): (K, V) Yields tuples of type (K, V), with the first entry being a key in the JsAssoc and the second being its corresponding value. Source Edit iterator items[K, V](assoc: JsAssoc[K, V]): V Yields the values in a JsAssoc. Source Edit iterator keys[K: JsKey; V](assoc: JsAssoc[K, V]): K Yields the keys in a JsAssoc. Source Edit Macros macro jsFromAst(n: untyped): untyped Source Edit macro `.`(obj: JsObject; field: untyped): JsObject Experimental dot accessor (get) for type JsObject. Returns the value of a property of name field from a JsObject x. Example: let obj = newJsObject() obj.a = 20 console.log(obj.a) # puts 20 onto the console. Source Edit macro `.=`(obj: JsObject; field, value: untyped): untyped Experimental dot accessor (set) for type JsObject. Sets the value of a property of name field in a JsObject x to value. Source Edit macro `.()`(obj: JsObject; field: untyped; args: varargs[JsObject, jsFromAst]): JsObject Experimental "method call" operator for type JsObject. Takes the name of a method of the JavaScript object (field) and calls it with args as arguments, returning a JsObject (which may be discarded, and may be undefined, if the method does not return anything, so be careful when using this.) Example: # Let's get back to the console example: var console {.importc, nodecl.}: JsObject let res = console.log("I return undefined!") console.log(res) # This prints undefined, as console.log always returns # undefined. Thus one has to be careful, when using # JsObject calls. Source Edit macro `.`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped): V Experimental dot accessor (get) for type JsAssoc. Returns the value of a property of name field from a JsObject x. Source Edit macro `.=`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped; value: V): untyped Experimental dot accessor (set) for type JsAssoc. Sets the value of a property of name field in a JsObject x to value. Source Edit macro `.()`[K: cstring; V: proc](obj: JsAssoc[K, V]; field: untyped; args: varargs[untyped]): auto Experimental "method call" operator for type JsAssoc. Takes the name of a method of the JavaScript object (field) and calls it with args as arguments. Here, everything is typechecked, so you do not have to worry about undefined return values. Source Edit macro `{}`(typ: typedesc; xs: varargs[untyped]): auto Takes a typedesc as its first argument, and a series of expressions of type key: value, and returns a value of the specified type with each field key set to value, as specified in the arguments of {}. Example: # Let's say we have a type with a ton of fields, where some fields do not # need to be set, and we do not want those fields to be set to ``nil``: type ExtremelyHugeType = ref object a, b, c, d, e, f, g: int h, i, j, k, l: cstring # And even more fields ... let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 } # This generates roughly the same JavaScript as: {.emit: "var obj = {a: 1, k: "foo", d: 42};".} Source Edit macro bindMethod(procedure: typed): auto Takes the name of a procedure and wraps it into a lambda missing the first argument, which passes the JavaScript builtin this as the first argument to the procedure. Returns the resulting lambda. Example: We want to generate roughly this JavaScript: var obj = {a: 10}; obj.someMethod = function() { return this.a + 42; }; We can achieve this using the bindMethod macro: let obj = JsObject{ a: 10 } proc someMethodImpl(that: JsObject): int = that.a.to(int) + 42 obj.someMethod = bindMethod someMethodImpl # Alternatively: obj.someMethod = bindMethod proc(that: JsObject): int = that.a.to(int) + 42 Source Edit Templates template toJs(s: string): JsObject Source Edit
dart:core operator <= method bool operator <=(Duration other) Returns true if the value of this Duration is less than or equal to the value of other. Source bool operator <=(Duration other) => this._duration <= other._duration;
Curses Programming with Python Author A.M. Kuchling, Eric S. Raymond Release 2.04 Abstract This document describes how to use the curses extension module to control text-mode displays. What is curses? The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs. Display terminals support various control codes to perform common operations such as moving the cursor, scrolling the screen, and erasing areas. Different terminals use widely differing codes, and often have their own minor quirks. In a world of graphical displays, one might ask “why bother”? It’s true that character-cell display terminals are an obsolete technology, but there are niches in which being able to do fancy things with them are still valuable. One niche is on small-footprint or embedded Unixes that don’t run an X server. Another is tools such as OS installers and kernel configurators that may have to run before any graphical support is available. The curses library provides fairly basic functionality, providing the programmer with an abstraction of a display containing multiple non-overlapping windows of text. The contents of a window can be changed in various ways—adding text, erasing it, changing its appearance—and the curses library will figure out what control codes need to be sent to the terminal to produce the right output. curses doesn’t provide many user-interface concepts such as buttons, checkboxes, or dialogs; if you need such features, consider a user interface library such as Urwid. The curses library was originally written for BSD Unix; the later System V versions of Unix from AT&T added many enhancements and new functions. BSD curses is no longer maintained, having been replaced by ncurses, which is an open-source implementation of the AT&T interface. If you’re using an open-source Unix such as Linux or FreeBSD, your system almost certainly uses ncurses. Since most current commercial Unix versions are based on System V code, all the functions described here will probably be available. The older versions of curses carried by some proprietary Unixes may not support everything, though. The Windows version of Python doesn’t include the curses module. A ported version called UniCurses is available. You could also try the Console module written by Fredrik Lundh, which doesn’t use the same API as curses but provides cursor-addressable text output and full support for mouse and keyboard input. The Python curses module The Python module is a fairly simple wrapper over the C functions provided by curses; if you’re already familiar with curses programming in C, it’s really easy to transfer that knowledge to Python. The biggest difference is that the Python interface makes things simpler by merging different C functions such as addstr(), mvaddstr(), and mvwaddstr() into a single addstr() method. You’ll see this covered in more detail later. This HOWTO is an introduction to writing text-mode programs with curses and Python. It doesn’t attempt to be a complete guide to the curses API; for that, see the Python library guide’s section on ncurses, and the C manual pages for ncurses. It will, however, give you the basic ideas. Starting and ending a curses application Before doing anything, curses must be initialized. This is done by calling the initscr() function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, initscr() returns a window object representing the entire screen; this is usually called stdscr after the name of the corresponding C variable. import curses stdscr = curses.initscr() Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read keys and only display them under certain circumstances. This requires calling the noecho() function. curses.noecho() Applications will also commonly need to react to keys instantly, without requiring the Enter key to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode. curses.cbreak() Terminals usually return special keys, such as the cursor keys or navigation keys such as Page Up and Home, as a multibyte escape sequence. While you could write your application to expect such sequences and process them accordingly, curses can do it for you, returning a special value such as curses.KEY_LEFT. To get curses to do the job, you’ll have to enable keypad mode. stdscr.keypad(True) Terminating a curses application is much easier than starting one. You’ll need to call: curses.nocbreak() stdscr.keypad(False) curses.echo() to reverse the curses-friendly terminal settings. Then call the endwin() function to restore the terminal to its original operating mode. curses.endwin() A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer echoed to the screen when you type them, for example, which makes using the shell difficult. In Python you can avoid these complications and make debugging much easier by importing the curses.wrapper() function and using it like this: from curses import wrapper def main(stdscr): # Clear screen stdscr.clear() # This raises ZeroDivisionError when i == 10. for i in range(0, 11): v = i-10 stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v)) stdscr.refresh() stdscr.getkey() wrapper(main) The wrapper() function takes a callable object and does the initializations described above, also initializing colors if color support is present. wrapper() then runs your provided callable. Once the callable returns, wrapper() will restore the original state of the terminal. The callable is called inside a try…except that catches exceptions, restores the state of the terminal, and then re-raises the exception. Therefore your terminal won’t be left in a funny state on exception and you’ll be able to read the exception’s message and traceback. Windows and Pads Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports methods to display text, erase it, allow the user to input strings, and so forth. The stdscr object returned by the initscr() function is a window object that covers the entire screen. Many programs may need only this single window, but you might wish to divide the screen into smaller windows, in order to redraw or clear them separately. The newwin() function creates a new window of a given size, returning the new window object. begin_x = 20; begin_y = 7 height = 5; width = 40 win = curses.newwin(height, width, begin_y, begin_x) Note that the coordinate system used in curses is unusual. Coordinates are always passed in the order y,x, and the top-left corner of a window is coordinate (0,0). This breaks the normal convention for handling coordinates where the x coordinate comes first. This is an unfortunate difference from most other computer applications, but it’s been part of curses since it was first written, and it’s too late to change things now. Your application can determine the size of the screen by using the curses.LINES and curses.COLS variables to obtain the y and x sizes. Legal coordinates will then extend from (0,0) to (curses.LINES - 1, curses.COLS - 1). When you call a method to display or erase text, the effect doesn’t immediately show up on the display. Instead you must call the refresh() method of window objects to update the screen. This is because curses was originally written with slow 300-baud terminal connections in mind; with these terminals, minimizing the time required to redraw the screen was very important. Instead curses accumulates changes to the screen and displays them in the most efficient manner when you call refresh(). For example, if your program displays some text in a window and then clears the window, there’s no need to send the original text because they’re never visible. In practice, explicitly telling curses to redraw a window doesn’t really complicate programming with curses much. Most programs go into a flurry of activity, and then pause waiting for a keypress or some other action on the part of the user. All you have to do is to be sure that the screen has been redrawn before pausing to wait for user input, by first calling stdscr.refresh() or the refresh() method of some other relevant window. A pad is a special case of a window; it can be larger than the actual display screen, and only a portion of the pad displayed at a time. Creating a pad requires the pad’s height and width, while refreshing a pad requires giving the coordinates of the on-screen area where a subsection of the pad will be displayed. pad = curses.newpad(100, 100) # These loops fill the pad with letters; addch() is # explained in the next section for y in range(0, 99): for x in range(0, 99): pad.addch(y,x, ord('a') + (x*x+y*y) % 26) # Displays a section of the pad in the middle of the screen. # (0,0) : coordinate of upper-left corner of pad area to display. # (5,5) : coordinate of upper-left corner of window area to be filled # with pad content. # (20, 75) : coordinate of lower-right corner of window area to be # : filled with pad content. pad.refresh( 0,0, 5,5, 20,75) The refresh() call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods. If you have multiple windows and pads on screen there is a more efficient way to update the screen and prevent annoying screen flicker as each part of the screen gets updated. refresh() actually does two things: Calls the noutrefresh() method of each window to update an underlying data structure representing the desired state of the screen. Calls the function doupdate() function to change the physical screen to match the desired state recorded in the data structure. Instead you can call noutrefresh() on a number of windows to update the data structure, and then call doupdate() to update the screen. Displaying Text From a C programmer’s point of view, curses may sometimes look like a twisty maze of functions, all subtly different. For example, addstr() displays a string at the current cursor location in the stdscr window, while mvaddstr() moves to a given y,x coordinate first before displaying the string. waddstr() is just like addstr(), but allows specifying a window to use instead of using stdscr by default. mvwaddstr() allows specifying both a window and a coordinate. Fortunately the Python interface hides all these details. stdscr is a window object like any other, and methods such as addstr() accept multiple argument forms. Usually there are four different forms. Form Description str or ch Display the string str or character ch at the current position str or ch, attr Display the string str or character ch, using attribute attr at the current position y, x, str or ch Move to position y,x within the window, and display str or ch y, x, str or ch, attr Move to position y,x within the window, and display str or ch, using attribute attr Attributes allow displaying text in highlighted forms such as boldface, underline, reverse code, or in color. They’ll be explained in more detail in the next subsection. The addstr() method takes a Python string or bytestring as the value to be displayed. The contents of bytestrings are sent to the terminal as-is. Strings are encoded to bytes using the value of the window’s encoding attribute; this defaults to the default system encoding as returned by locale.getpreferredencoding(). The addch() methods take a character, which can be either a string of length 1, a bytestring of length 1, or an integer. Constants are provided for extension characters; these constants are integers greater than 255. For example, ACS_PLMINUS is a +/- symbol, and ACS_ULCORNER is the upper left corner of a box (handy for drawing borders). You can also use the appropriate Unicode character. Windows remember where the cursor was left after the last operation, so if you leave out the y,x coordinates, the string or character will be displayed wherever the last operation left off. You can also move the cursor with the move(y,x) method. Because some terminals always display a flashing cursor, you may want to ensure that the cursor is positioned in some location where it won’t be distracting; it can be confusing to have the cursor blinking at some apparently random location. If your application doesn’t need a blinking cursor at all, you can call curs_set(False) to make it invisible. For compatibility with older curses versions, there’s a leaveok(bool) function that’s a synonym for curs_set(). When bool is true, the curses library will attempt to suppress the flashing cursor, and you won’t need to worry about leaving it in odd locations. Attributes and Color Characters can be displayed in different ways. Status lines in a text-based application are commonly shown in reverse video, or a text viewer may need to highlight certain words. curses supports this by allowing you to specify an attribute for each cell on the screen. An attribute is an integer, each bit representing a different attribute. You can try to display text with multiple attribute bits set, but curses doesn’t guarantee that all the possible combinations are available, or that they’re all visually distinct. That depends on the ability of the terminal being used, so it’s safest to stick to the most commonly available attributes, listed here. Attribute Description A_BLINK Blinking text A_BOLD Extra bright or bold text A_DIM Half bright text A_REVERSE Reverse-video text A_STANDOUT The best highlighting mode available A_UNDERLINE Underlined text So, to display a reverse-video status line on the top line of the screen, you could code: stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE) stdscr.refresh() The curses library also supports color on those terminals that provide it. The most common such terminal is probably the Linux console, followed by color xterms. To use color, you must call the start_color() function soon after calling initscr(), to initialize the default color set (the curses.wrapper() function does this automatically). Once that’s done, the has_colors() function returns TRUE if the terminal in use can actually display color. (Note: curses uses the American spelling ‘color’, instead of the Canadian/British spelling ‘colour’. If you’re used to the British spelling, you’ll have to resign yourself to misspelling it for the sake of these functions.) The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You can get the attribute value corresponding to a color pair with the color_pair() function; this can be bitwise-OR’ed with other attributes such as A_REVERSE, but again, such combinations are not guaranteed to work on all terminals. An example, which displays a line of text using color pair 1: stdscr.addstr("Pretty text", curses.color_pair(1)) stdscr.refresh() As I said before, a color pair consists of a foreground and background color. The init_pair(n, f, b) function changes the definition of color pair n, to foreground color f and background color b. Color pair 0 is hard-wired to white on black, and cannot be changed. Colors are numbered, and start_color() initializes 8 basic colors when it activates color mode. They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The curses module defines named constants for each of these colors: curses.COLOR_BLACK, curses.COLOR_RED, and so forth. Let’s put all this together. To change color 1 to red text on a white background, you would call: curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) When you change a color pair, any text already displayed using that color pair will change to the new colors. You can also display new text in this color with: stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1)) Very fancy terminals can change the definitions of the actual colors to a given RGB value. This lets you change color 1, which is usually red, to purple or blue or any other color you like. Unfortunately, the Linux console doesn’t support this, so I’m unable to try it out, and can’t provide any examples. You can check if your terminal can do this by calling can_change_color(), which returns True if the capability is there. If you’re lucky enough to have such a talented terminal, consult your system’s man pages for more information. User Input The C curses library offers only very simple input mechanisms. Python’s curses module adds a basic text-input widget. (Other libraries such as Urwid have more extensive collections of widgets.) There are two methods for getting input from a window: getch() refreshes the screen and then waits for the user to hit a key, displaying the key if echo() has been called earlier. You can optionally specify a coordinate to which the cursor should be moved before pausing. getkey() does the same thing but converts the integer to a string. Individual characters are returned as 1-character strings, and special keys such as function keys return longer strings containing a key name such as KEY_UP or ^G. It’s possible to not wait for the user using the nodelay() window method. After nodelay(True), getch() and getkey() for the window become non-blocking. To signal that no input is ready, getch() returns curses.ERR (a value of -1) and getkey() raises an exception. There’s also a halfdelay() function, which can be used to (in effect) set a timer on each getch(); if no input becomes available within a specified delay (measured in tenths of a second), curses raises an exception. The getch() method returns an integer; if it’s between 0 and 255, it represents the ASCII code of the key pressed. Values greater than 255 are special keys such as Page Up, Home, or the cursor keys. You can compare the value returned to constants such as curses.KEY_PPAGE, curses.KEY_HOME, or curses.KEY_LEFT. The main loop of your program may look something like this: while True: c = stdscr.getch() if c == ord('p'): PrintDocument() elif c == ord('q'): break # Exit the while loop elif c == curses.KEY_HOME: x = y = 0 The curses.ascii module supplies ASCII class membership functions that take either integer or 1-character string arguments; these may be useful in writing more readable tests for such loops. It also supplies conversion functions that take either integer or 1-character-string arguments and return the same type. For example, curses.ascii.ctrl() returns the control character corresponding to its argument. There’s also a method to retrieve an entire string, getstr(). It isn’t used very often, because its functionality is quite limited; the only editing keys available are the backspace key and the Enter key, which terminates the string. It can optionally be limited to a fixed number of characters. curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15) The curses.textpad module supplies a text box that supports an Emacs-like set of keybindings. Various methods of the Textbox class support editing with input validation and gathering the edit results either with or without trailing spaces. Here’s an example: import curses from curses.textpad import Textbox, rectangle def main(stdscr): stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)") editwin = curses.newwin(5,30, 2,1) rectangle(stdscr, 1,0, 1+5+1, 1+30+1) stdscr.refresh() box = Textbox(editwin) # Let the user edit until Ctrl-G is struck. box.edit() # Get resulting contents message = box.gather() See the library documentation on curses.textpad for more details. For More Information This HOWTO doesn’t cover some advanced topics, such as reading the contents of the screen or capturing mouse events from an xterm instance, but the Python library page for the curses module is now reasonably complete. You should browse it next. If you’re in doubt about the detailed behavior of the curses functions, consult the manual pages for your curses implementation, whether it’s ncurses or a proprietary Unix vendor’s. The manual pages will document any quirks, and provide complete lists of all the functions, attributes, and ACS_* characters available to you. Because the curses API is so large, some functions aren’t supported in the Python interface. Often this isn’t because they’re difficult to implement, but because no one has needed them yet. Also, Python doesn’t yet support the menu library associated with ncurses. Patches adding support for these would be welcome; see the Python Developer’s Guide to learn more about submitting patches to Python. Writing Programs with NCURSES: a lengthy tutorial for C programmers. The ncurses man page The ncurses FAQ “Use curses… don’t swear”: video of a PyCon 2013 talk on controlling terminals using curses or Urwid. “Console Applications with Urwid”: video of a PyCon CA 2012 talk demonstrating some applications written using Urwid.
public static function ConfigEntityBas8b7c:f320:99b9:690f:4595:cd17:293a:c069sort public static ConfigEntityBas8b7c:f320:99b9:690f:4595:cd17:293a:c069sort(ConfigEntityInterface $a, ConfigEntityInterface $b) Helper callback for uasort() to sort configuration entities by weight and label. File core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php, line 251 Class ConfigEntityBase Defines a base configuration entity class. Namespace Drupal\Core\Config\Entity Code public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) { $a_weight = isset($a->weight) ? $a->weight : 0; $b_weight = isset($b->weight) ? $b->weight : 0; if ($a_weight == $b_weight) { $a_label = $a->label(); $b_label = $b->label(); return strnatcasecmp($a_label, $b_label); } return ($a_weight < $b_weight) ? -1 : 1; }
numpy.isclose numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)[source] Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. Warning The default atol is not appropriate for comparing numbers that are much smaller than one (see Notes). Parameters a, barray_like Input arrays to compare. rtolfloat The relative tolerance parameter (see Notes). atolfloat The absolute tolerance parameter (see Notes). equal_nanbool Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array. Returns yarray_like Returns a boolean array of where a and b are equal within the given tolerance. If both a and b are scalars, returns a single boolean value. See also allclose math.isclose Notes New in version 1.7.0. For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(a - b) <= (atol + rtol * absolute(b)) Unlike the built-in math.isclose, the above equation is not symmetric in a and b – it assumes b is the reference value – so that isclose(a, b) might be different from isclose(b, a). Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. atol should be carefully selected for the use [email protected]. A zero value for atol will result in False if either a or b is zero. isclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose. Examples >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) array([False, True])
numpy.ma.where numpy.ma.where(condition, x=<no value>, y=<no value>) [source] Return a masked array with elements from x or y, depending on condition. Returns a masked array, shaped like condition, where the elements are from x when condition is True, and from y otherwise. If neither x nor y are given, the function returns a tuple of indices where condition is True (the result of condition.nonzero()). Parameters: condition : array_like, bool The condition to meet. For each True element, yield the corresponding element from x, otherwise from y. x, y : array_like, optional Values from which to choose. x, y and condition need to be broadcastable to some shape. Returns: out : MaskedArray or tuple of ndarrays The resulting masked array if x and y were given, otherwise the result of condition.nonzero(). See also numpy.where Equivalent function in the top-level NumPy module. Examples >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], ... [1, 0, 1], ... [0, 1, 0]]) >>> print(x) [[0.0 -- 2.0] [-- 4.0 --] [6.0 -- 8.0]] >>> np.ma.where(x > 5) # return the indices where x > 5 (array([2, 2]), array([0, 2])) >>> print(np.ma.where(x > 5, x, -3.1416)) [[-3.1416 -- -3.1416] [-- -3.1416 --] [6.0 -- 8.0]]
encodeString Encode Character Vector as for Printing Description encodeString escapes the strings in a character vector in the same way print.default does, and optionally fits the encoded strings within a field width. Usage encodeString(x, width = 0, quote = "", na.encode = TRUE, justify = c("left", "right", "centre", "none")) Arguments x A character vector, or an object that can be coerced to one by as.character. width integer: the minimum field width. If NULL or NA, this is taken to be the largest field width needed for any element of x. quote character: quoting character, if any. na.encode logical: should NA strings be encoded? justify character: partial matches are allowed. If padding to the minimum field width is needed, how should spaces be inserted? justify == "none" is equivalent to width = 0, for consistency with format.default. Details This escapes backslash and the control characters \a (bell), \b (backspace), \f (formfeed), \n (line feed), \r (carriage return), \t (tab) and \v (vertical tab) as well as any non-printable characters in a single-byte locale, which are printed in octal notation (\xyz with leading zeroes). Which characters are non-printable depends on the current locale. Windows' reporting of printable characters is unreliable, so there all other control characters are regarded as non-printable, and all characters with codes 32–255 as printable in a single-byte locale. See print.default for how non-printable characters are handled in multi-byte locales. If quote is a single or double quote any embedded quote of the same type is escaped. Note that justification is of the quoted string, hence spaces are added outside the quotes. Value A character vector of the same length as x, with the same attributes (including names and dimensions) but with no class set. Marked UTF-8 encodings are preserved. Note The default for width is different from format.default, which does similar things for character vectors but without encoding using escapes. See Also print.default Examples x <- "ab\bc\ndef" print(x) cat(x) # interprets escapes cat(encodeString(x), "\n", sep = "") # similar to print() factor(x) # makes use of this to print the levels x <- c("a", "ab", "abcde") encodeString(x) # width = 0: use as little as possible encodeString(x, 2) # use two or more (left justified) encodeString(x, width = NA) # left justification encodeString(x, width = NA, justify = "c") encodeString(x, width = NA, justify = "r") encodeString(x, width = NA, quote = "'", justify = "r") Copyright (
backends matplotlib.backend_bases matplotlib.backend_managers matplotlib.backend_tools matplotlib.backends.backend_gtkagg matplotlib.backends.backend_qt4agg matplotlib.backends.backend_wxagg matplotlib.backends.backend_pdf
module ActionView8b7c:f320:99b9:690f:4595:cd17:293a:c069Helpers8b7c:f320:99b9:690f:4595:cd17:293a:c069ssetUrlHelper This module provides methods for generating asset paths and urls. image_path("rails.png") # => "/assets/rails.png" image_url("rails.png") # => "http://www.example.com/assets/rails.png" Using asset hosts By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated asset server by setting ActionController8b7c:f320:99b9:690f:4595:cd17:293a:c069se.asset_host in the application configuration, typically in config/environments/production.rb. For example, you'd define assets.example.com to be your asset host this way, inside the configure block of your environment-specific configuration files or config/application.rb: config.action_controller.asset_host = "assets.example.com" Helpers take that into account: image_tag("rails.png") # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" /> stylesheet_link_tag("application") # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" /> Browsers open a limited number of simultaneous connections to a single host. The exact number varies by browser and version. This limit may cause some asset downloads to wait for previous assets to finish before they can begin. You can use the %d wildcard in the asset_host to distribute the requests over four hosts. For example, <tt>assets%d.example.com<tt> will spread the asset requests over “assets0.example.com”, …, “assets3.example.com”. image_tag("rails.png") # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" /> stylesheet_link_tag("application") # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" /> This may improve the asset loading performance of your application. It is also possible the combination of additional connection overhead (DNS, SSL) and the overall browser connection limits may result in this solution being slower. You should be sure to measure your actual performance across targeted browsers both before and after this change. To implement the corresponding hosts you can either setup four actual hosts or use wildcard DNS to CNAME the wildcard to a single asset host. You can read more about setting up your DNS CNAME records from your ISP. Note: This is purely a browser performance optimization and is not meant for server load balancing. See www.die.net/musings/page_load_time/ for background and www.browserscope.org/?category=network for connection limit data. Alternatively, you can exert more control over the asset host by setting asset_host to a proc like this: ActionController8b7c:f320:99b9:690f:4595:cd17:293a:c069se.asset_host = Proc.new { |source| "http://assets#{Digest8b7c:f320:99b9:690f:4595:cd17:293a:c069MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com" } image_tag("rails.png") # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" /> stylesheet_link_tag("application") # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" /> The example above generates “assets1.example.com” and “assets2.example.com”. This option is useful for example if you need fewer/more than four hosts, custom host names, etc. As you see the proc takes a source parameter. That's a string with the absolute path of the asset, for example “/assets/rails.png”. ActionController8b7c:f320:99b9:690f:4595:cd17:293a:c069se.asset_host = Proc.new { |source| if source.ends_with?('.css') "http://stylesheets.example.com" else "http://assets.example.com" end } image_tag("rails.png") # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" /> stylesheet_link_tag("application") # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" /> Alternatively you may ask for a second parameter request. That one is particularly useful for serving assets from an SSL-protected page. The example proc below disables asset hosting for HTTPS connections, while still sending assets for plain HTTP requests from asset hosts. If you don't have SSL certificates for each of the asset hosts this technique allows you to avoid warnings in the client about mixed media. Note that the request parameter might not be supplied, e.g. when the assets are precompiled via a Rake task. Make sure to use a Proc instead of a lambda, since a Proc allows missing parameters and sets them to nil. config.action_controller.asset_host = Proc.new { |source, request| if request && request.ssl? "#{request.protocol}#{request.host_with_port}" else "#{request.protocol}assets.example.com" end } You can also implement a custom asset host object that responds to call and takes either one or two parameters just like the proc. config.action_controller.asset_host = AssetHostingWithMinimumSsl.new( "http://asset%d.example.com", "https://asset1.example.com" ) Constants ASSET_EXTENSIONS ASSET_PUBLIC_DIRECTORIES Maps asset types to public directory. URI_REGEXP Public Instance Methods asset_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 130 def asset_path(source, options = {}) raise ArgumentError, "nil is not a valid asset source" if source.nil? source = source.to_s return "" unless source.present? return source if source =~ URI_REGEXP tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, ''.freeze) if extname = compute_asset_extname(source, options) source = "#{source}#{extname}" end if source[0] != ?/ source = compute_asset_path(source, options) end relative_url_root = defined?(config.relative_url_root) && config.relative_url_root if relative_url_root source = File.join(relative_url_root, source) unless source.starts_with?("#{relative_url_root}/") end if host = compute_asset_host(source, options) source = File.join(host, source) end "#{source}#{tail}" end Computes the path to asset in public directory. If :type options is set, a file extension will be appended and scoped to the corresponding public directory. All other asset *_path helpers delegate through this method. asset_path "application.js" # => /assets/application.js asset_path "application", type: :javascript # => /assets/application.js asset_path "application", type: :stylesheet # => /assets/application.css asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js Also aliased as: path_to_asset asset_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 170 def asset_url(source, options = {}) path_to_asset(source, options.merge(:protocol => :request)) end Computes the full URL to an asset in the public directory. This will use asset_path internally, so most of their behaviors will be the same. If :host options is set, it overwrites global config.action_controller.asset_host setting. All other options provided are forwarded to asset_path call. asset_url "application.js" # => http://example.com/assets/application.js asset_url "application.js", host: "http://cdn.example.com" # => http://cdn.example.com/assets/application.js Also aliased as: url_to_asset audio_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 362 def audio_path(source, options = {}) path_to_asset(source, {type: :audio}.merge!(options)) end Computes the path to an audio asset in the public audios directory. Full paths from the document root will be passed through. Used internally by audio_tag to build the audio path. audio_path("horse") # => /audios/horse audio_path("horse.wav") # => /audios/horse.wav audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav audio_path("/sounds/horse.wav") # => /sounds/horse.wav audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav Also aliased as: path_to_audio audio_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 374 def audio_url(source, options = {}) url_to_asset(source, {type: :audio}.merge!(options)) end Computes the full URL to an audio asset in the public audios directory. This will use audio_path internally, so most of their behaviors will be the same. Since audio_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. audio_url "horse.wav", host: "http://stage.example.com" # => http://stage.example.com/horse.wav Also aliased as: url_to_audio compute_asset_extname(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 182 def compute_asset_extname(source, options = {}) return if options[:extname] == false extname = options[:extname] || ASSET_EXTENSIONS[options[:type]] extname if extname && File.extname(source) != extname end Compute extname to append to asset path. Returns nil if nothing should be added. compute_asset_host(source = "", options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 211 def compute_asset_host(source = "", options = {}) request = self.request if respond_to?(:request) host = options[:host] host ||= config.asset_host if defined? config.asset_host if host.respond_to?(:call) arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity args = [source] args << request if request && (arity > 1 || arity < 0) host = host.call(*args) elsif host =~ /%d/ host = host % (Zlib.crc32(source) % 4) end host ||= request.base_url if request && options[:protocol] == :request return unless host if host =~ URI_REGEXP host else protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative) case protocol when :relative "//#{host}" when :request "#{request.protocol}#{host}" else "#{protocol}://#{host}" end end end Pick an asset host for this source. Returns nil if no host is set, the host if no wildcard is set, the host interpolated with the numbers 0-3 if it contains %d (the number is the source hash mod 4), or the value returned from invoking call on an object responding to call (proc or otherwise). compute_asset_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 201 def compute_asset_path(source, options = {}) dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || "" File.join(dir, source) end Computes asset path to public directory. Plugins and extensions can override this method to point to custom assets or generate digested paths or query strings. font_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 387 def font_path(source, options = {}) path_to_asset(source, {type: :font}.merge!(options)) end Computes the path to a font asset. Full paths from the document root will be passed through. font_path("font") # => /fonts/font font_path("font.ttf") # => /fonts/font.ttf font_path("dir/font.ttf") # => /fonts/dir/font.ttf font_path("/dir/font.ttf") # => /dir/font.ttf font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf Also aliased as: path_to_font font_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 399 def font_url(source, options = {}) url_to_asset(source, {type: :font}.merge!(options)) end Computes the full URL to a font asset. This will use font_path internally, so most of their behaviors will be the same. Since font_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. font_url "font.ttf", host: "http://stage.example.com" # => http://stage.example.com/font.ttf Also aliased as: url_to_font image_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 310 def image_path(source, options = {}) path_to_asset(source, {type: :image}.merge!(options)) end Computes the path to an image asset. Full paths from the document root will be passed through. Used internally by image_tag to build the image path: image_path("edit") # => "/assets/edit" image_path("edit.png") # => "/assets/edit.png" image_path("icons/edit.png") # => "/assets/icons/edit.png" image_path("/icons/edit.png") # => "/icons/edit.png" image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png" If you have images as application resources this method may conflict with their named routes. The alias path_to_image is provided to avoid that. Rails uses the alias internally, and plugin authors are encouraged to do so. Also aliased as: path_to_image image_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 322 def image_url(source, options = {}) url_to_asset(source, {type: :image}.merge!(options)) end Computes the full URL to an image asset. This will use image_path internally, so most of their behaviors will be the same. Since image_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. image_url "edit.png", host: "http://stage.example.com" # => http://stage.example.com/edit.png Also aliased as: url_to_image javascript_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 253 def javascript_path(source, options = {}) path_to_asset(source, {type: :javascript}.merge!(options)) end Computes the path to a JavaScript asset in the public javascripts directory. If the source filename has no extension, .js will be appended (except for explicit URIs) Full paths from the document root will be passed through. Used internally by javascript_include_tag to build the script path. javascript_path "xmlhr" # => /assets/xmlhr.js javascript_path "dir/xmlhr.js" # => /assets/dir/xmlhr.js javascript_path "/dir/xmlhr" # => /dir/xmlhr.js javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js Also aliased as: path_to_javascript javascript_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 265 def javascript_url(source, options = {}) url_to_asset(source, {type: :javascript}.merge!(options)) end Computes the full URL to a JavaScript asset in the public javascripts directory. This will use javascript_path internally, so most of their behaviors will be the same. Since javascript_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. javascript_url "js/xmlhr.js", host: "http://stage.example.com" # => http://stage.example.com/assets/dir/xmlhr.js Also aliased as: url_to_javascript path_to_asset(source, options = {}) Alias for: asset_path path_to_audio(source, options = {}) Alias for: audio_path path_to_font(source, options = {}) Alias for: font_path path_to_image(source, options = {}) Alias for: image_path path_to_javascript(source, options = {}) Alias for: javascript_path path_to_stylesheet(source, options = {}) Alias for: stylesheet_path path_to_video(source, options = {}) Alias for: video_path stylesheet_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 280 def stylesheet_path(source, options = {}) path_to_asset(source, {type: :stylesheet}.merge!(options)) end Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended (except for explicit URIs). Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path. stylesheet_path "style" # => /assets/style.css stylesheet_path "dir/style.css" # => /assets/dir/style.css stylesheet_path "/dir/style.css" # => /dir/style.css stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css Also aliased as: path_to_stylesheet stylesheet_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 292 def stylesheet_url(source, options = {}) url_to_asset(source, {type: :stylesheet}.merge!(options)) end Computes the full URL to a stylesheet asset in the public stylesheets directory. This will use stylesheet_path internally, so most of their behaviors will be the same. Since stylesheet_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. stylesheet_url "css/style.css", host: "http://stage.example.com" # => http://stage.example.com/css/style.css Also aliased as: url_to_stylesheet url_to_asset(source, options = {}) Alias for: asset_url url_to_audio(source, options = {}) Alias for: audio_url url_to_font(source, options = {}) Alias for: font_url url_to_image(source, options = {}) Alias for: image_url url_to_javascript(source, options = {}) Alias for: javascript_url url_to_stylesheet(source, options = {}) Alias for: stylesheet_url url_to_video(source, options = {}) Alias for: video_url video_path(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 336 def video_path(source, options = {}) path_to_asset(source, {type: :video}.merge!(options)) end Computes the path to a video asset in the public videos directory. Full paths from the document root will be passed through. Used internally by video_tag to build the video path. video_path("hd") # => /videos/hd video_path("hd.avi") # => /videos/hd.avi video_path("trailers/hd.avi") # => /videos/trailers/hd.avi video_path("/trailers/hd.avi") # => /trailers/hd.avi video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi Also aliased as: path_to_video video_url(source, options = {}) Show source # File actionview/lib/action_view/helpers/asset_url_helper.rb, line 348 def video_url(source, options = {}) url_to_asset(source, {type: :video}.merge!(options)) end Computes the full URL to a video asset in the public videos directory. This will use video_path internally, so most of their behaviors will be the same. Since video_url is based on asset_url method you can set :host options. If :host options is set, it overwrites global config.action_controller.asset_host setting. video_url "hd.avi", host: "http://stage.example.com" # => http://stage.example.com/hd.avi Also aliased as: url_to_video
matplotlib.pyplot.cla matplotlib.pyplot.cla()[source] Clear the current axes. Examples using matplotlib.pyplot.cla
salt.modules.eix Support for Eix salt.modules.eix.sync() Sync portage/overlay trees and update the eix database CLI Example: salt '*' eix.sync salt.modules.eix.update() Update the eix database CLI Example: salt '*' eix.update
PEXPIRE PEXPIRE key milliseconds Available since 2.6.0. Time complexity: O(1) This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds. Return value Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist. Examples redis> SET mykey "Hello" "OK" redis> PEXPIRE mykey 1500 (integer) 1 redis> TTL mykey (integer) 1 redis> PTTL mykey (integer) 1459
dart:web_sql SqlTransactionErrorCallback typedef @DomName('SQLTransactionErrorCallback') @Experimental() void SqlTransactionErrorCallback(SqlError error) Source @DomName('SQLTransactionErrorCallback') // http://www.w3.org/TR/webdatabase/#sqltransactionerrorcallback @Experimental() // deprecated typedef void SqlTransactionErrorCallback(SqlError error);
FormRegistry class FormRegistry implements FormRegistryInterface The central registry of the Form component. Methods __construct(array $extensions, ResolvedFormTypeFactoryInterface $resolvedTypeFactory) Constructor. ResolvedFormTypeInterface getType(string $name) Returns a form type by name. bool hasType(string $name) Returns whether the given form type is supported. FormTypeGuesserInterface|null getTypeGuesser() Returns the guesser responsible for guessing types. FormExtensionInterface[] getExtensions() Returns the extensions loaded by the framework. Details __construct(array $extensions, ResolvedFormTypeFactoryInterface $resolvedTypeFactory) Constructor. Parameters array $extensions An array of FormExtensionInterface ResolvedFormTypeFactoryInterface $resolvedTypeFactory The factory for resolved form types. Exceptions UnexpectedTypeException if any extension does not implement FormExtensionInterface ResolvedFormTypeInterface getType(string $name) Returns a form type by name. This methods registers the type extensions from the form extensions. Parameters string $name The name of the type Return Value ResolvedFormTypeInterface The type Exceptions InvalidArgumentException if the type can not be retrieved from any extension bool hasType(string $name) Returns whether the given form type is supported. Parameters string $name The name of the type Return Value bool Whether the type is supported FormTypeGuesserInterface|null getTypeGuesser() Returns the guesser responsible for guessing types. Return Value FormTypeGuesserInterface|null FormExtensionInterface[] getExtensions() Returns the extensions loaded by the framework. Return Value FormExtensionInterface[]
public function FormStat8b7c:f320:99b9:690f:4595:cd17:293a:c069disableRedirect public FormStat8b7c:f320:99b9:690f:4595:cd17:293a:c069disableRedirect($no_redirect = TRUE) Prevents the form from redirecting. Parameters bool $no_redirect: If TRUE, the form will not redirect. Return value $this Overrides FormStateInter8b7c:f320:99b9:690f:4595:cd17:293a:c069disableRedirect File core/lib/Drupal/Core/Form/FormState.php, line 639 Class FormState Stores information about the state of a form. Namespace Drupal\Core\Form Code public function disableRedirect($no_redirect = TRUE) { $this->no_redirect = (bool) $no_redirect; return $this; }
matplotlib.axis.Tick.set_alpha Tick.set_alpha(alpha) Set the alpha value used for blending - not supported on all backends. Parameters: alpha : float
HttpXsrfTokenExtractor class npm Package @angular/common Module import { HttpXsrfTokenExtractor } from '@angular/common/http'; Source common/http/src/xsrf.ts Overview class HttpXsrfTokenExtractor { getToken(): string | null } Description Retrieves the current XSRF token to use with the next outgoing request. Members getToken(): string | null Get the XSRF token to use with an outgoing request. Will be called for every request, so the token may change between requests.
Module ets Module Summary Built-in term storage. Description This module is an interface to the Erlang built-in term storage BIFs. These provide the ability to store very large quantities of data in an Erlang runtime system, and to have constant access time to the data. (In the case of ordered_set, see below, access time is proportional to the logarithm of the number of stored objects.) Data is organized as a set of dynamic tables, which can store tuples. Each table is created by a process. When the process terminates, the table is automatically destroyed. Every table has access rights [email protected]. Tables are divided into four different types, set, ordered_set, bag, and duplicate_bag. A set or ordered_set table can only have one object associated with each key. A bag or duplicate_bag table can have many objects associated with each key. Note The number of tables stored at one Erlang node used to be limited. This is no longer the case (except by memory usage). The previous default limit was about 1400 tables and could be increased by setting the environment variable ERL_MAX_ETS_TABLES or the command line option +e before starting the Erlang runtime system. This hard limit has been removed, but it is currently useful to set the ERL_MAX_ETS_TABLES anyway. It should be set to an approximate of the maximum amount of tables used since an internal table for named tables is sized using this value. If large amounts of named tables are used and ERL_MAX_ETS_TABLES hasn't been increased, the performance of named table lookup will degrade. Notice that there is no automatic garbage collection for tables. Even if there are no references to a table from any process, it is not automatically destroyed unless the owner process terminates. To destroy a table explicitly, use function delete/1. The default owner is the process that created the table. To transfer table ownership at process termination, use option heir or call give_away/3. Some implementation details: In the current implementation, every object insert and look-up operation results in a copy of the object. '$end_of_table' is not to be used as a key, as this atom is used to mark the end of the table when using functions first/1 and next/2. Notice the subtle difference between matching and comparing equal, which is demonstrated by table types set and ordered_set: Two Erlang terms match if they are of the same type and have the same value, so that 1 matches 1, but not 1.0 (as 1.0 is a float() and not an integer()). Two Erlang terms compare equal if they either are of the same type and value, or if both are numeric types and extend to the same value, so that 1 compares equal to both 1 and 1.0. The ordered_set works on the Erlang term order and no defined order exists between an integer() and a float() that extends to the same value. Hence the key 1 and the key 1.0 are regarded as equal in an ordered_set table. Failures Functions in this module fail by raising an error exception with error reason: badarg If any argument has the wrong format. badarg If the table identifier is invalid. badarg If the operation is denied because of table access rights (protected or private). system_limit Modification of a value causes it to not be representable internally in the VM. For example, incrementation of a counter past the largest integer representable. system_limit If a match specification passed as argument has excessive nesting which causes scheduler stack exhaustion for the scheduler that the calling process is executing on. Scheduler stack size can be configured when starting the runtime system. Concurrency This module provides some limited support for concurrent access. All updates to single objects are guaranteed to be both atomic and isolated. This means that an updating operation to a single object either succeeds or fails completely without any effect (atomicity) and that no intermediate results of the update can be seen by other processes (isolation). Some functions that update many objects state that they even guarantee atomicity and isolation for the entire operation. In database terms the isolation level can be seen as "serializable", as if all isolated operations are carried out serially, one after the other in a strict order. Table traversal There are different ways to traverse through the objects of a table. Single-step traversal one key at at time, using first/1, next/2, last/1 and prev/2. Search with simple match patterns, using match/1/2/3, match_delete/2 and match_object/1/2/3. Search with more powerful match specifications, using select/1/2/3, select_count/2, select_delete/2, select_replace/2 and select_reverse/1/2/3. Table conversions, using tab2file/2/3 and tab2list/1. No table traversal will guarantee a consistent snapshot of the entire table if the table is also updated by concurrent processes during the traversal. The result of each concurrently updated object may be seen (or not) depending on if it has happened when the traversal visits that part of the table. The only way to guarantee a full consistent table snapshot (if you really need that) is to disallow concurrent updates during the entire traversal. Moreover, traversals not done in a safe way, on tables where keys are inserted or deleted during the traversal, may yield the following undesired effects: Any key may be missed. Any key may be found more than once. The traversal may fail with badarg exception if keys are deleted. A table traversal is safe if either the table is of type ordered_set. the entire table traversal is done within one ETS function call. function safe_fixtable/2 is used to keep the table fixated during the entire traversal. Note Even though the access of a single object is always guaranteed to be atomic and isolated, each traversal through a table to find the next key is not done with such guarantees. This is often not a problem, but may cause rare subtle "unexpected" effects if a concurrent process inserts objects during a traversal. For example, consider one process doing ets:new(t, [ordered_set, named_table]), ets:insert(t, {1}), ets:insert(t, {2}), ets:insert(t, {3}), A concurrent call to ets:first(t), done by another process, may then in rare cases return 2 even though 2 has never existed in the table ordered as the first key. In the same way, a concurrent call to ets:next(t, 1) may return 3 even though 3 never existed in the table ordered directly after 1. Effects like this are improbable but possible. The probability will further be reduced (if not vanish) if table option write_concurrency is not enabled. This can also only be a potential concern for ordered_set where the traversal order is defined. Traversals using match and select functions may not need to scan the entire table depending on how the key is specified. A match pattern with a fully bound key (without any match variables) will optimize the operation to a single key lookup without any table [email protected]. For ordered_set a partially bound key will limit the traversal to only scan a subset of the table based on term order. A partially bound key is either a list or a tuple with a prefix that is fully bound. Example: 1> T = ets:new(t,[ordered_set]), ets:insert(T, {"555-1234", "John Smith"}). true 2> %% Efficient search of all with area code 555 2> ets:match(T,{[$5,$5,$5,$- |'$1'],'$2'}). [["1234","John Smith"]] Match Specifications Some of the functions use a match specification, match_spec. For a brief explanation, see select/2. For a detailed description, see section Match Specifications in Erlang in ERTS User's Guide. A match specifications with excessive nesting will cause a system_limit error exception to be raised. Data Types table_access() = public | protected | private continuation() Opaque continuation used by select/1,3, select_reverse/1,3, match/1,3, and match_object/1,3. match_spec() = [{match_pattern(), [term()], [term()]}] A match specification, see Match Specifications. compiled_match_spec() A compiled match specification. match_pattern() = atom() | tuple() table() = atom() | tid() tid() A table identifier, as returned by new/2. table_type() = set | ordered_set | bag | duplicate_bag Exports all() -> [Table] Types Table = table() Returns a list of all tables at the node. Named tables are specified by their names, unnamed tables are specified by their table identifiers. There is no guarantee of consistency in the returned list. Tables created or deleted by other processes "during" the ets:all() call either are or are not included in the list. Only tables created/deleted before ets:all() is called are guaranteed to be included/excluded. delete(Table) -> true Types Table = table() Deletes the entire table Table. delete(Table, Key) -> true Types Table = table() Key = term() Deletes all objects with key Key from table Table. This function succeeds even if no objects with key Key exist. delete_all_objects(Table) -> true Types Table = table() Delete all objects in the ETS table Table. The operation is guaranteed to be atomic and isolated. delete_object(Table, Object) -> true Types Table = table() Object = tuple() Delete the exact object Object from the ETS table, leaving objects with the same key but other differences (useful for type bag). In a duplicate_bag table, all instances of the object are deleted. file2tab(Filename) -> {ok, Table} | {error, Reason} Types Filename = file:name() Table = table() Reason = term() Reads a file produced by tab2file/2 or tab2file/3 and creates the corresponding table Table. Equivalent to file2tab(Filename, []). file2tab(Filename, Options) -> {ok, Table} | {error, Reason} Types Filename = file:name() Table = table() Options = [Option] Option = {verify, boolean()} Reason = term() Reads a file produced by tab2file/2 or tab2file/3 and creates the corresponding table Table. The only supported option is {verify,boolean()}. If verification is turned on (by specifying {verify,true}), the function uses whatever information is present in the file to assert that the information is not damaged. How this is done depends on which extended_info was written using tab2file/3. If no extended_info is present in the file and {verify,true} is specified, the number of objects written is compared to the size of the original table when the dump was started. This can make verification fail if the table was public and objects were added or removed while the table was dumped to file. To avoid this problem, either do not verify files dumped while updated simultaneously or use option {extended_info, [object_count]} to tab2file/3, which extends the information in the file with the number of objects written. If verification is turned on and the file was written with option {extended_info, [md5sum]}, reading the file is slower and consumes radically more CPU time than otherwise. {verify,false} is the default. first(Table) -> Key | '$end_of_table' Types Table = table() Key = term() Returns the first key Key in table Table. For an ordered_set table, the first key in Erlang term order is returned. For other table types, the first key according to the internal order of the table is returned. If the table is empty, '$end_of_table' is returned. To find subsequent keys in the table, use next/2. foldl(Function, Acc0, Table) -> Acc1 Types Function = fun((Element 8b7c:f320:99b9:690f:4595:cd17:293a:c069 term(), AccIn) -> AccOut) Table = table() Acc0 = Acc1 = AccIn = AccOut = term() Acc0 is returned if the table is empty. This function is similar to lists:foldl/3. The table elements are traversed in an unspecified order, except for ordered_set tables, where they are traversed first to last. If Function inserts objects into the table, or another process inserts objects into the table, those objects can (depending on key ordering) be included in the traversal. foldr(Function, Acc0, Table) -> Acc1 Types Function = fun((Element 8b7c:f320:99b9:690f:4595:cd17:293a:c069 term(), AccIn) -> AccOut) Table = table() Acc0 = Acc1 = AccIn = AccOut = term() Acc0 is returned if the table is empty. This function is similar to lists:foldr/3. The table elements are traversed in an unspecified order, except for ordered_set tables, where they are traversed last to first. If Function inserts objects into the table, or another process inserts objects into the table, those objects can (depending on key ordering) be included in the traversal. from_dets(Table, DetsTab) -> true Types Table = table() DetsTab = dets:tab_name() Fills an already created ETS table with the objects in the already opened Dets table DetsTab. Existing objects in the ETS table are kept unless overwritten. If any of the tables does not exist or the Dets table is not open, a badarg exception is raised. fun2ms(LiteralFun) -> MatchSpec Types LiteralFun = function() MatchSpec = match_spec() Pseudo function that by a parse_transform translates LiteralFun typed as parameter in the function call to a match specification. With "literal" is meant that the fun must textually be written as the parameter of the function, it cannot be held in a variable that in turn is passed to the function. The parse transform is provided in the ms_transform module and the source must include file ms_transform.hrl in STDLIB for this pseudo function to work. Failing to include the hrl file in the source results in a runtime error, not a compile time error. The include file is easiest included by adding line -include_lib("stdlib/include/ms_transform.hrl"). to the source file. The fun is very restricted, it can take only a single parameter (the object to match): a sole variable or a tuple. It must use the is_ guard tests. Language constructs that have no representation in a match specification (if, case, receive, and so on) are not allowed. The return value is the resulting match specification. Example: 1> ets:fun2ms(fun({M,N}) when N > 3 -> M end). [{{'$1','$2'},[{'>','$2',3}],['$1']}] Variables from the environment can be imported, so that the following works: 2> X=3. 3 3> ets:fun2ms(fun({M,N}) when N > X -> M end). [{{'$1','$2'},[{'>','$2',{const,3}}],['$1']}] The imported variables are replaced by match specification const expressions, which is consistent with the static scoping for Erlang funs. However, local or global function calls cannot be in the guard or body of the fun. Calls to built-in match specification functions is of course allowed: 4> ets:fun2ms(fun({M,N}) when N > X, my_fun(M) -> M end). Error: fun containing local Erlang function calls ('my_fun' called in guard) cannot be translated into match_spec {error,transform_error} 5> ets:fun2ms(fun({M,N}) when N > X, is_atom(M) -> M end). [{{'$1','$2'},[{'>','$2',{const,3}},{is_atom,'$1'}],['$1']}] As shown by the example, the function can be called from the shell also. The fun must be literally in the call when used from the shell as well. Warning If the parse_transform is not applied to a module that calls this pseudo function, the call fails in runtime (with a badarg). The ets module exports a function with this name, but it is never to be called except when using the function in the shell. If the parse_transform is properly applied by including header file ms_transform.hrl, compiled code never calls the function, but the function call is replaced by a literal match specification. For more information, see ms_transform(3). give_away(Table, Pid, GiftData) -> true Types Table = table() Pid = pid() GiftData = term() Make process Pid the new owner of table Table. If successful, message {'ETS-TRANSFER',Table,FromPid,GiftData} is sent to the new owner. The process Pid must be alive, local, and not already the owner of the table. The calling process must be the table owner. Notice that this function does not affect option heir of the table. A table owner can, for example, set heir to itself, give the table away, and then get it back if the receiver terminates. i() -> ok Displays information about all ETS tables on a terminal. i(Table) -> ok Types Table = table() Browses table Table on a terminal. info(Table) -> InfoList | undefined Types Table = table() InfoList = [InfoTuple] InfoTuple = {compressed, boolean()} | {decentralized_counters, boolean()} | {heir, pid() | none} | {id, tid()} | {keypos, integer() >= 1} | {memory, integer() >= 0} | {name, atom()} | {named_table, boolean()} | {node, node()} | {owner, pid()} | {protection, table_access()} | {size, integer() >= 0} | {type, table_type()} | {write_concurrency, boolean()} | {read_concurrency, boolean()} Returns information about table Table as a list of tuples. If Table has the correct type for a table identifier, but does not refer to an existing ETS table, undefined is returned. If Table is not of the correct type, a badarg exception is raised. {compressed, boolean()} Indicates if the table is compressed. {decentralized_counters, boolean()} Indicates whether the table uses decentralized_counters. {heir, pid() | none} The pid of the heir of the table, or none if no heir is set. {id, tid()} The table identifier. {keypos, integer() >= 1} The key position. {memory, integer() >= 0} The number of words allocated to the table. {name, atom()} The table name. {named_table, boolean()} Indicates if the table is named. {node, node()} The node where the table is stored. This field is no longer meaningful, as tables cannot be accessed from other nodes. {owner, pid()} The pid of the owner of the table. {protection, access()} The table access rights. {size, integer() >= 0} The number of objects inserted in the table. {type, type()} The table type. {read_concurrency, boolean()} Indicates whether the table uses read_concurrency or not. {write_concurrency, WriteConcurrencyAlternative} Indicates which write_concurrency option the table uses. Note The execution time of this function is affected by the decentralized_counters table option. The execution time is much longer when the decentralized_counters option is set to true than when the decentralized_counters option is set to false. info(Table, Item) -> Value | undefined Types Table = table() Item = binary | compressed | decentralized_counters | fixed | heir | id | keypos | memory | name | named_table | node | owner | protection | safe_fixed | safe_fixed_monotonic_time | size | stats | type | write_concurrency | read_concurrency Value = term() Returns the information associated with Item for table Table, or returns undefined if Table does not refer an existing ETS table. If Table is not of the correct type, or if Item is not one of the allowed values, a badarg exception is raised. In addition to the {Item,Value} pairs defined for info/1, the following items are allowed: Item=binary, Value=BinInfo BinInfo is a list containing miscellaneous information about binaries kept by the table. This Item can be changed or removed without prior notice. In the current implementation BinInfo is a list of tuples {BinaryId,BinarySize,BinaryRefcCount}. Item=fixed, Value=boolean() Indicates if the table is fixed by any process. Item=safe_fixed|safe_fixed_monotonic_time, Value={FixationTime,Info}|false If the table is fixed using safe_fixtable/2, the call returns a tuple where FixationTime is the last time when the table changed from unfixed to fixed. The format and value of FixationTime depends on Item: safe_fixed FixationTime corresponds to the result returned by erlang:timestamp/0 at the time of fixation. Notice that when the system uses single or multi time warp modes this can produce strange results, as the use of safe_fixed is not time warp safe. Time warp safe code must use safe_fixed_monotonic_time instead. safe_fixed_monotonic_time FixationTime corresponds to the result returned by erlang:monotonic_time/0 at the time of fixation. The use of safe_fixed_monotonic_time is time warp safe. Info is a possibly empty lists of tuples {Pid,RefCount}, one tuple for every process the table is fixed by now. RefCount is the value of the reference counter and it keeps track of how many times the table has been fixed by the process. Table fixations are not limited to safe_fixtable/2. Temporary fixations may also be done by for example traversing functions like select and match. Such table fixations are automatically released before the corresponding functions returns, but they may be seen by a concurrent call to ets:info(T,safe_fixed|safe_fixed_monotonic_time). If the table is not fixed at all, the call returns false. Item=stats, Value=tuple() Returns internal statistics about tables on an internal format used by OTP test suites. Not for production use. Note The execution time of this function is affected by the decentralized_counters table option when the second argument of the function is size or memory. The execution time is much longer when the decentralized_counters option is set to true than when the decentralized_counters option is set to false. init_table(Table, InitFun) -> true Types Table = table() InitFun = fun((Arg) -> Res) Arg = read | close Res = end_of_input | {Objects 8b7c:f320:99b9:690f:4595:cd17:293a:c069 [term()], InitFun} | term() Replaces the existing objects of table Table with objects created by calling the input function InitFun, see below. This function is provided for compatibility with the dets module, it is not more efficient than filling a table by using insert/2. When called with argument read, the function InitFun is assumed to return end_of_input when there is no more input, or {Objects, Fun}, where Objects is a list of objects and Fun is a new input function. Any other value Value is returned as an error {error, {init_fun, Value}}. Each input function is called exactly once, and if an error occur, the last function is called with argument close, the reply of which is ignored. If the table type is set and more than one object exists with a given key, one of the objects is chosen. This is not necessarily the last object with the given key in the sequence of objects returned by the input functions. This holds also for duplicated objects stored in tables of type bag. insert(Table, ObjectOrObjects) -> true Types Table = table() ObjectOrObjects = tuple() | [tuple()] Inserts the object or all of the objects in list ObjectOrObjects into table Table. If the table type is set and the key of the inserted objects matches the key of any object in the table, the old object is replaced. If the table type is ordered_set and the key of the inserted object compares equal to the key of any object in the table, the old object is replaced. If the list contains more than one object with matching keys and the table type is set, one is inserted, which one is not defined. The same holds for table type ordered_set if the keys compare equal. The entire operation is guaranteed to be atomic and isolated, even when a list of objects is inserted. insert_new(Table, ObjectOrObjects) -> boolean() Types Table = table() ObjectOrObjects = tuple() | [tuple()] Same as insert/2 except that instead of overwriting objects with the same key (for set or ordered_set) or adding more objects with keys already existing in the table (for bag and duplicate_bag), false is returned. If ObjectOrObjects is a list, the function checks every key before inserting anything. Nothing is inserted unless all keys present in the list are absent from the table. Like insert/2, the entire operation is guaranteed to be atomic and isolated. is_compiled_ms(Term) -> boolean() Types Term = term() Checks if a term represent a valid compiled match specification. A compiled match specifications is only valid on the Erlang node where it was compiled by calling match_spec_compile/1. Note Before STDLIB 3.4 (OTP 20.0) compiled match specifications did not have an external representation. If passed through binary_to_term(term_to_binary(CMS)) or sent to another node and back, the result was always an empty binary <<>>. After STDLIB 3.4 (OTP 20.0) compiled match specifications have an external representation as a node specific reference to the original compiled match specification. If passed through binary_to_term(term_to_binary(CMS)) or sent to another node and back, the result may or may not be a valid compiled match specification depending on if the original compiled match specification was still alive. last(Table) -> Key | '$end_of_table' Types Table = table() Key = term() Returns the last key Key according to Erlang term order in table Table of type ordered_set. For other table types, the function is synonymous to first/1. If the table is empty, '$end_of_table' is returned. To find preceding keys in the table, use prev/2. lookup(Table, Key) -> [Object] Types Table = table() Key = term() Object = tuple() Returns a list of all objects with key Key in table Table. For tables of type set, bag, or duplicate_bag, an object is returned only if the specified key matches the key of the object in the table. For tables of type ordered_set, an object is returned if the specified key compares equal to the key of an object in the table. The difference is the same as between =:= and ==. As an example, one can insert an object with integer() 1 as a key in an ordered_set and get the object returned as a result of doing a lookup/2 with float() 1.0 as the key to search for. For tables of type set or ordered_set, the function returns either the empty list or a list with one element, as there cannot be more than one object with the same key. For tables of type bag or duplicate_bag, the function returns a list of arbitrary length. Notice that the time order of object insertions is preserved; the first object inserted with the specified key is the first in the resulting list, and so on. Insert and lookup times in tables of type set, bag, and duplicate_bag are constant, regardless of the table size. For the ordered_set datatype, time is proportional to the (binary) logarithm of the number of objects. lookup_element(Table, Key, Pos) -> Elem Types Table = table() Key = term() Pos = integer() >= 1 Elem = term() | [term()] For a table Table of type set or ordered_set, the function returns the Pos:th element of the object with key Key. For tables of type bag or duplicate_bag, the functions returns a list with the Pos:th element of every object with key Key. If no object with key Key exists, the function exits with reason badarg. The difference between set, bag, and duplicate_bag on one hand, and ordered_set on the other, regarding the fact that ordered_set view keys as equal when they compare equal whereas the other table types regard them equal only when they match, holds for lookup_element/3. match(Continuation) -> {[Match], Continuation} | '$end_of_table' Types Match = [term()] Continuation = continuation() Continues a match started with match/3. The next chunk of the size specified in the initial match/3 call is returned together with a new Continuation, which can be used in subsequent calls to this function. When there are no more objects in the table, '$end_of_table' is returned. match(Table, Pattern) -> [Match] Types Table = table() Pattern = match_pattern() Match = [term()] Matches the objects in table Table against pattern Pattern. A pattern is a term that can contain: Bound parts (Erlang terms) '_' that matches any Erlang term Pattern variables '$N', where N=0,1,... The function returns a list with one element for each matching object, where each element is an ordered list of pattern variable bindings, for example: 6> ets:match(T, '$1'). % Matches every object in table [[{rufsen,dog,7}],[{brunte,horse,5}],[{ludde,dog,5}]] 7> ets:match(T, {'_',dog,'$1'}). [[7],[5]] 8> ets:match(T, {'_',cow,'$1'}). [] If the key is specified in the pattern, the match is very efficient. If the key is not specified, that is, if it is a variable or an underscore, the entire table must be searched. The search time can be substantial if the table is very large. For tables of type ordered_set, the result is in the same order as in a first/next traversal. match(Table, Pattern, Limit) -> {[Match], Continuation} | '$end_of_table' Types Table = table() Pattern = match_pattern() Limit = integer() >= 1 Match = [term()] Continuation = continuation() Works like match/2, but returns only a limited (Limit) number of matching objects. Term Continuation can then be used in subsequent calls to match/1 to get the next chunk of matching objects. This is a space-efficient way to work on objects in a table, which is faster than traversing the table object by object using first/1 and next/2. If the table is empty, '$end_of_table' is returned. Use safe_fixtable/2 to guarantee safe traversal for subsequent calls to match/1. match_delete(Table, Pattern) -> true Types Table = table() Pattern = match_pattern() Deletes all objects that match pattern Pattern from table Table. For a description of patterns, see match/2. match_object(Continuation) -> {[Object], Continuation} | '$end_of_table' Types Object = tuple() Continuation = continuation() Continues a match started with match_object/3. The next chunk of the size specified in the initial match_object/3 call is returned together with a new Continuation, which can be used in subsequent calls to this function. When there are no more objects in the table, '$end_of_table' is returned. match_object(Table, Pattern) -> [Object] Types Table = table() Pattern = match_pattern() Object = tuple() Matches the objects in table Table against pattern Pattern. For a description of patterns, see match/2. The function returns a list of all objects that match the pattern. If the key is specified in the pattern, the match is very efficient. If the key is not specified, that is, if it is a variable or an underscore, the entire table must be searched. The search time can be substantial if the table is very large. For tables of type ordered_set, the result is in the same order as in a first/next traversal. match_object(Table, Pattern, Limit) -> {[Object], Continuation} | '$end_of_table' Types Table = table() Pattern = match_pattern() Limit = integer() >= 1 Object = tuple() Continuation = continuation() Works like match_object/2, but only returns a limited (Limit) number of matching objects. Term Continuation can then be used in subsequent calls to match_object/1 to get the next chunk of matching objects. This is a space-efficient way to work on objects in a table, which is faster than traversing the table object by object using first/1 and next/2. If the table is empty, '$end_of_table' is returned. Use safe_fixtable/2 to guarantee safe traversal for subsequent calls to match_object/1. match_spec_compile(MatchSpec) -> CompiledMatchSpec Types MatchSpec = match_spec() CompiledMatchSpec = compiled_match_spec() Transforms a match specification into an internal representation that can be used in subsequent calls to match_spec_run/2. The internal representation is opaque. To check the validity of a compiled match specification, use is_compiled_ms/1. If term MatchSpec does not represent a valid match specification, a badarg exception is raised. Note This function has limited use in normal code. It is used by the dets module to perform the dets:select() operations. match_spec_run(List, CompiledMatchSpec) -> list() Types List = [term()] CompiledMatchSpec = compiled_match_spec() Executes the matching specified in a compiled match specification on a list of terms. Term CompiledMatchSpec is to be the result of a call to match_spec_compile/1 and is hence the internal representation of the match specification one wants to use. The matching is executed on each element in List and the function returns a list containing all results. If an element in List does not match, nothing is returned for that element. The length of the result list is therefore equal or less than the length of parameter List. Example: The following two calls give the same result (but certainly not the same execution time): Table = ets:new... MatchSpec = ... % The following call... ets:match_spec_run(ets:tab2list(Table), ets:match_spec_compile(MatchSpec)), % ...gives the same result as the more common (and more efficient) ets:select(Table, MatchSpec), Note This function has limited use in normal code. It is used by the dets module to perform the dets:select() operations and by Mnesia during transactions. member(Table, Key) -> boolean() Types Table = table() Key = term() Works like lookup/2, but does not return the objects. Returns true if one or more elements in the table has key Key, otherwise false. new(Name, Options) -> table() Types Name = atom() Options = [Option] Option = Type | Access | named_table | {keypos, Pos} | {heir, Pid 8b7c:f320:99b9:690f:4595:cd17:293a:c069 pid(), HeirData} | {heir, none} | Tweaks Type = table_type() Access = table_access() WriteConcurrencyAlternative = boolean() | auto Tweaks = {write_concurrency, WriteConcurrencyAlternative} | {read_concurrency, boolean()} | {decentralized_counters, boolean()} | compressed Pos = integer() >= 1 HeirData = term() Creates a new table and returns a table identifier that can be used in subsequent operations. The table identifier can be sent to other processes so that a table can be shared between different processes within a node. Parameter Options is a list of options that specifies table type, access rights, key position, and whether the table is named. Default values are used for omitted options. This means that not specifying any options ([]) is the same as specifying [set, protected, {keypos,1}, {heir,none}, {write_concurrency,false}, {read_concurrency,false}, {decentralized_counters,false}]. set The table is a set table: one key, one object, no order among objects. This is the default table type. ordered_set The table is a ordered_set table: one key, one object, ordered in Erlang term order, which is the order implied by the < and > operators. Tables of this type have a somewhat different behavior in some situations than tables of other types. Most notably, the ordered_set tables regard keys as equal when they compare equal, not only when they match. This means that to an ordered_set table, integer() 1 and float() 1.0 are regarded as equal. This also means that the key used to lookup an element not necessarily matches the key in the returned elements, if float()'s and integer()'s are mixed in keys of a table. bag The table is a bag table, which can have many objects, but only one instance of each object, per key. duplicate_bag The table is a duplicate_bag table, which can have many objects, including multiple copies of the same object, per key. public Any process can read or write to the table. protected The owner process can read and write to the table. Other processes can only read the table. This is the default setting for the access rights. private Only the owner process can read or write to the table. named_table If this option is present, the table is registered under its Name which can then be used instead of the table identifier in subsequent operations. The function will also return the Name instead of the table identifier. To get the table identifier of a named table, use whereis/1. {keypos,Pos} Specifies which element in the stored tuples to use as key. By default, it is the first element, that is, Pos=1. However, this is not always appropriate. In particular, we do not want the first element to be the key if we want to store Erlang records in a table. Notice that any tuple stored in the table must have at least Pos number of elements. {heir,Pid,HeirData} | {heir,none} Set a process as heir. The heir inherits the table if the owner terminates. Message {'ETS-TRANSFER',tid(),FromPid,HeirData} is sent to the heir when that occurs. The heir must be a local process. Default heir is none, which destroys the table when the owner terminates. {write_concurrency,WriteConcurrencyAlternative} Performance tuning. Defaults to false, in which case an operation that mutates (writes to) the table obtains exclusive access, blocking any concurrent access of the same table until finished. If set to true, the table is optimized for concurrent write access. Different objects of the same table can be mutated (and read) by concurrent processes. This is achieved to some degree at the expense of memory consumption and the performance of sequential access and concurrent reading. The auto alternative for the write_concurrency option is similar to the true option but automatically adjusts the synchronization granularity during runtime depending on how the table is used. This is the recommended write_concurrency option when using Erlang/OTP 25 and above as it performs well in most scenarios. The write_concurrency option can be combined with the options read_concurrency and decentralized_counters. You typically want to combine write_concurrency with read_concurrency when large concurrent read bursts and large concurrent write bursts are common; for more information, see option read_concurrency. It is almost always a good idea to combine the write_concurrency option with the decentralized_counters option. Notice that this option does not change any guarantees about atomicity and isolation. Functions that makes such promises over many objects (like insert/2) gain less (or nothing) from this option. The memory consumption inflicted by both write_concurrency and read_concurrency is a constant overhead per table for set, bag and duplicate_bag when the true alternative for the write_concurrency option is not used. For all tables with the auto alternative and ordered_set tables with true alternative the memory overhead depends on the amount of actual detected concurrency during runtime. The memory overhead can be especially large when both write_concurrency and read_concurrency are combined. Note Prior to stdlib-3.7 (OTP-22.0) write_concurrency had no effect on ordered_set. Note The auto alternative for the write_concurrency option is only available in OTP-25.0 and above. {read_concurrency,boolean()} Performance tuning. Defaults to false. When set to true, the table is optimized for concurrent read operations. When this option is enabled read operations become much cheaper; especially on systems with multiple physical processors. However, switching between read and write operations becomes more expensive. You typically want to enable this option when concurrent read operations are much more frequent than write operations, or when concurrent reads and writes comes in large read and write bursts (that is, many reads not interrupted by writes, and many writes not interrupted by reads). You typically do not want to enable this option when the common access pattern is a few read operations interleaved with a few write operations repeatedly. In this case, you would get a performance degradation by enabling this option. Option read_concurrency can be combined with option write_concurrency. You typically want to combine these when large concurrent read bursts and large concurrent write bursts are common. {decentralized_counters,boolean()} Performance tuning. Defaults to true for all tables with the write_concurrency option set to auto. For tables of type ordered_set the option also defaults to true when the write_concurrency option is set to true. The option defaults to false for all other configurations. This option has no effect if the write_concurrency option is set to false. When this option is set to true, the table is optimized for frequent concurrent calls to operations that modify the tables size and/or its memory consumption (e.g., insert/2 and delete/2). The drawback is that calls to info/1 and info/2 with size or memory as the second argument can get much slower when the decentralized_counters option is turned on. When this option is enabled the counters for the table size and memory consumption are distributed over several cache lines and the scheduling threads are mapped to one of those cache lines. The erl option +dcg can be used to control the number of cache lines that the counters are distributed over. compressed If this option is present, the table data is stored in a more compact format to consume less memory. However, it will make table operations slower. Especially operations that need to inspect entire objects, such as match and select, get much slower. The key element is not compressed. next(Table, Key1) -> Key2 | '$end_of_table' Types Table = table() Key1 = Key2 = term() Returns the next key Key2, following key Key1 in table Table. For table type ordered_set, the next key in Erlang term order is returned. For other table types, the next key according to the internal order of the table is returned. If no next key exists, '$end_of_table' is returned. To find the first key in the table, use first/1. Unless a table of type set, bag, or duplicate_bag is fixated using safe_fixtable/2, a call to next/2 will fail if Key1 no longer exists in the table. For table type ordered_set, the function always returns the next key after Key1 in term order, regardless whether Key1 ever existed in the table. prev(Table, Key1) -> Key2 | '$end_of_table' Types Table = table() Key1 = Key2 = term() Returns the previous key Key2, preceding key Key1 according to Erlang term order in table Table of type ordered_set. For other table types, the function is synonymous to next/2. If no previous key exists, '$end_of_table' is returned. To find the last key in an ordered_set table, use last/1. rename(Table, Name) -> Name Types Table = table() Name = atom() Renames the named table Table to the new name Name. Afterwards, the old name cannot be used to access the table. Renaming an unnamed table has no effect. repair_continuation(Continuation, MatchSpec) -> Continuation Types Continuation = continuation() MatchSpec = match_spec() Restores an opaque continuation returned by select/3 or select/1 if the continuation has passed through external term format (been sent between nodes or stored on disk). The reason for this function is that continuation terms contain compiled match specifications and may therefore be invalidated if converted to external term format. Given that the original match specification is kept intact, the continuation can be restored, meaning it can once again be used in subsequent select/1 calls even though it has been stored on disk or on another node. Examples: The following sequence of calls may fail: T=ets:new(x,[]), ... MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end), {_,C} = ets:select(T, MS, 10), MaybeBroken = binary_to_term(term_to_binary(C)), ets:select(MaybeBroken). The following sequence works, as the call to repair_continuation/2 reestablishes the MaybeBroken continuation. T=ets:new(x,[]), ... MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end), {_,C} = ets:select(T,MS,10), MaybeBroken = binary_to_term(term_to_binary(C)), ets:select(ets:repair_continuation(MaybeBroken,MS)). Note This function is rarely needed in application code. It is used by Mnesia to provide distributed select/3 and select/1 sequences. A normal application would either use Mnesia or keep the continuation from being converted to external format. The actual behavior of compiled match specifications when recreated from external format has changed and may change in future releases, but this interface remains for backward compatibility. See is_compiled_ms/1. safe_fixtable(Table, Fix) -> true Types Table = table() Fix = boolean() Fixes a table of type set, bag, or duplicate_bag for safe traversal using first/1 & next/2, match/3 & match/1, match_object/3 & match_object/1, or select/3 & select/1. A process fixes a table by calling safe_fixtable(Table, true). The table remains fixed until the process releases it by calling safe_fixtable(Table, false), or until the process terminates. If many processes fix a table, the table remains fixed until all processes have released it (or terminated). A reference counter is kept on a per process basis, and N consecutive fixes requires N releases to release the table. When a table is fixed, a sequence of first/1 and next/2 calls are guaranteed to succeed even if keys are removed during the traversal. The keys for objects inserted or deleted during a traversal may or may not be returned by next/2 depending on the ordering of keys within the table and if the key exists at the time next/2 is called. Example: clean_all_with_value(Table,X) -> safe_fixtable(Table,true), clean_all_with_value(Table,X,ets:first(Table)), safe_fixtable(Table,false). clean_all_with_value(Table,X,'$end_of_table') -> true; clean_all_with_value(Table,X,Key) -> case ets:lookup(Table,Key) of [{Key,X}] -> ets:delete(Table,Key); _ -> true end, clean_all_with_value(Table,X,ets:next(Table,Key)). Notice that deleted objects are not freed from a fixed table until it has been released. If a process fixes a table but never releases it, the memory used by the deleted objects is never freed. The performance of operations on the table also degrades significantly. To retrieve information about which processes have fixed which tables, use info(Table, safe_fixed_monotonic_time). A system with many processes fixing tables can need a monitor that sends alarms when tables have been fixed for too long. Notice that safe_fixtable/2 is not necessary for table type ordered_set and for traversals done by a single ETS function call, like select/2. select(Continuation) -> {[Match], Continuation} | '$end_of_table' Types Match = term() Continuation = continuation() Continues a match started with select/3. The next chunk of the size specified in the initial select/3 call is returned together with a new Continuation, which can be used in subsequent calls to this function. When there are no more objects in the table, '$end_of_table' is returned. select(Table, MatchSpec) -> [Match] Types Table = table() MatchSpec = match_spec() Match = term() Matches the objects in table Table using a match specification. This is a more general call than match/2 and match_object/2 calls. In its simplest form, the match specification is as follows: MatchSpec = [MatchFunction] MatchFunction = {MatchHead, [Guard], [Result]} MatchHead = "Pattern as in ets:match" Guard = {"Guardtest name", ...} Result = "Term construct" This means that the match specification is always a list of one or more tuples (of arity 3). The first element of the tuple is to be a pattern as described in match/2. The second element of the tuple is to be a list of 0 or more guard tests (described below). The third element of the tuple is to be a list containing a description of the value to return. In almost all normal cases, the list contains exactly one term that fully describes the value to return for each object. The return value is constructed using the "match variables" bound in MatchHead or using the special match variables '$_' (the whole matching object) and '$$' (all match variables in a list), so that the following match/2 expression: ets:match(Table,{'$1','$2','$3'}) is exactly equivalent to: ets:select(Table,[{{'$1','$2','$3'},[],['$$']}]) And that the following match_object/2 call: ets:match_object(Table,{'$1','$2','$1'}) is exactly equivalent to ets:select(Table,[{{'$1','$2','$1'},[],['$_']}]) Composite terms can be constructed in the Result part either by simply writing a list, so that the following code: ets:select(Table,[{{'$1','$2','$3'},[],['$$']}]) gives the same output as: ets:select(Table,[{{'$1','$2','$3'},[],[['$1','$2','$3']]}]) That is, all the bound variables in the match head as a list. If tuples are to be constructed, one has to write a tuple of arity 1 where the single element in the tuple is the tuple one wants to construct (as an ordinary tuple can be mistaken for a Guard). Therefore the following call: ets:select(Table,[{{'$1','$2','$1'},[],['$_']}]) gives the same output as: ets:select(Table,[{{'$1','$2','$1'},[],[{{'$1','$2','$3'}}]}]) This syntax is equivalent to the syntax used in the trace patterns (see the dbg(3)) module in Runtime_Tools. The Guards are constructed as tuples, where the first element is the test name and the remaining elements are the test parameters. To check for a specific type (say a list) of the element bound to the match variable '$1', one would write the test as {is_list, '$1'}. If the test fails, the object in the table does not match and the next MatchFunction (if any) is tried. Most guard tests present in Erlang can be used, but only the new versions prefixed is_ are allowed (is_float, is_atom, and so on). The Guard section can also contain logic and arithmetic operations, which are written with the same syntax as the guard tests (prefix notation), so that the following guard test written in Erlang: is_integer(X), is_integer(Y), X + Y < 4711 is expressed as follows (X replaced with '$1' and Y with '$2'): [{is_integer, '$1'}, {is_integer, '$2'}, {'<', {'+', '$1', '$2'}, 4711}] For tables of type ordered_set, objects are visited in the same order as in a first/next traversal. This means that the match specification is executed against objects with keys in the first/next order and the corresponding result list is in the order of that execution. select(Table, MatchSpec, Limit) -> {[Match], Continuation} | '$end_of_table' Types Table = table() MatchSpec = match_spec() Limit = integer() >= 1 Match = term() Continuation = continuation() Works like select/2, but only returns a limited (Limit) number of matching objects. Term Continuation can then be used in subsequent calls to select/1 to get the next chunk of matching objects. This is a space-efficient way to work on objects in a table, which is still faster than traversing the table object by object using first/1 and next/2. If the table is empty, '$end_of_table' is returned. Use safe_fixtable/2 to guarantee safe traversal for subsequent calls to select/1. select_count(Table, MatchSpec) -> NumMatched Types Table = table() MatchSpec = match_spec() NumMatched = integer() >= 0 Matches the objects in table Table using a match specification. If the match specification returns true for an object, that object considered a match and is counted. For any other result from the match specification the object is not considered a match and is therefore not counted. This function can be described as a select_delete/2 function that does not delete any elements, but only counts them. The function returns the number of objects matched. select_delete(Table, MatchSpec) -> NumDeleted Types Table = table() MatchSpec = match_spec() NumDeleted = integer() >= 0 Matches the objects in table Table using a match specification. If the match specification returns true for an object, that object is removed from the table. For any other result from the match specification the object is retained. This is a more general call than the match_delete/2 call. The function returns the number of objects deleted from the table. Note The match specification has to return the atom true if the object is to be deleted. No other return value gets the object deleted. So one cannot use the same match specification for looking up elements as for deleting them. select_replace(Table, MatchSpec) -> NumReplacedOTP 20.0 Types Table = table() MatchSpec = match_spec() NumReplaced = integer() >= 0 Matches the objects in the table Table using a match specification. For each matched object, the existing object is replaced with the match specification result. The match-and-replace operation for each individual object is guaranteed to be atomic and isolated. The select_replace table traversal as a whole, like all other select functions, does not give such guarantees. The match specifiction must be guaranteed to retain the key of any matched object. If not, select_replace will fail with badarg without updating any objects. For the moment, due to performance and semantic constraints, tables of type bag are not yet supported. The function returns the total number of replaced objects. Example For all 2-tuples with a list in second position, add atom 'marker' first in the list: 1> T = ets:new(x,[]), ets:insert(T, {key, [1, 2, 3]}). true 2> MS = ets:fun2ms(fun({K, L}) when is_list(L) -> {K, [marker | L]} end). [{{'$1','$2'},[{is_list,'$2'}],[{{'$1',[marker|'$2']}}]}] 3> ets:select_replace(T, MS). 1 4> ets:tab2list(T). [{key,[marker,1,2,3]}] A generic single object compare-and-swap operation: [Old] = ets:lookup(T, Key), New = update_object(Old), Success = (1 =:= ets:select_replace(T, [{Old, [], [{const, New}]}])), select_reverse(Continuation) -> {[Match], Continuation} | '$end_of_table' OTP R14B Types Continuation = continuation() Match = term() Continues a match started with select_reverse/3. For
Deprecation: run_command and popen4 helper method removal (OHAI-3) [edit on GitHub] Ohai ships a command mixin for use by plugin authors in shelling out to external commands. This mixin originally included run_command and popen4 methods, which were deprecated in Ohai 8.11.1 (Chef Client 12.8.1) in favor of the more robust mixlib-shellout gem functionality. In Chef Client 13 these deprecated methods will be removed, breaking any Ohai plugins authored using the deprecated methods. Remediation Plugins should be updated to use mixlib-shellout instead of the run_command. Deprecated run_command based code: status, stdout, stderr = run_command(command: 'myapp --version') if status == 0 version = stdout end Updated code for mixlib shellout: so = shell_out('myapp --version') if so.exitstatus == 0 version = so.stdout end See the mixlib-shellout repo for additional usage information.
tf.data.experimental.prefetch_to_device View source on GitHub A transformation that prefetches dataset values to the given device. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.data.experimental.prefetch_to_device tf.data.experimental.prefetch_to_device( device, buffer_size=None ) Note: Although the transformation creates a tf.data.Dataset, the transformation must be the final Dataset in the input pipeline. For example, >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) >>> dataset = dataset.apply(tf.data.experimental.prefetch_to_device("/cpu:0")) >>> for element in dataset: ... print(f'Tensor {element} is on device {element.device}') Tensor 1 is on device /job:localhost/replica:0/task:0/device:CPU:0 Tensor 2 is on device /job:localhost/replica:0/task:0/device:CPU:0 Tensor 3 is on device /job:localhost/replica:0/task:0/device:CPU:0 Args device A string. The name of a device to which elements will be prefetched. buffer_size (Optional.) The number of elements to buffer on device. Defaults to an automatically chosen value. Returns A Dataset transformation function, which can be passed to tf.data.Dataset.apply.
dart:core remainder method BigInt remainder( BigInt other ) Returns the remainder of the truncating division of this by other. The result r of this operation satisfies: this == (this ~/ other) * other + r. As a consequence the remainder r has the same sign as the divider this. Example: print(BigInt.from(5).remainder(BigInt.from(3))); // 2 print(BigInt.from(-5).remainder(BigInt.from(3))); // -2 print(BigInt.from(5).remainder(BigInt.from(-3))); // 2 print(BigInt.from(-5).remainder(BigInt.from(-3))); // -2 Implementation BigInt remainder(BigInt other);
Loading / Error Substates The Ember Router allows you to provide feedback that a route is loading, as well as when an error occurs in loading a route. The error and loading substates exist as a part of each route, so they should not be added to your router.js file. To utilize a substate, the route, controller, and template may be optionally defined as desired. loading substates During the beforeModel, model, and afterModel hooks, data may take some time to load. Technically, the router pauses the transition until the promises returned from each hook fulfill. Consider the following: Router.map(function() { this.route('slow-model'); }); import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class SlowModelRoute extends Route { @service store; model() { return this.store.findAll('slow-model'); } } If you navigate to slow-model, in the model hook using Ember Data, the query may take a long time to complete. During this time, your UI isn't really giving you any feedback as to what's happening. If you're entering this route after a full page refresh, your UI will be entirely blank, as you have not actually finished fully entering any route and haven't yet displayed any templates. If you're navigating to slow-model from another route, you'll continue to see the templates from the previous route until the model finish loading, and then, boom, suddenly all the templates for slow-model load. So, how can we provide some visual feedback during the transition? Simply define a template called loading (and optionally a corresponding route) that Ember will transition to. The intermediate transition into the loading substate happens immediately (synchronously), the URL won't be updated, and, unlike other transitions, the currently active transition won't be aborted. Once the main transition into slow-model completes, the loading route will be exited and the transition to slow-model will continue. For nested routes, like: Router.map(function() { this.route('user', function() { this.route('about', function() { this.route('slow-model'); }); }); }); Each of the following assumes a transition from the application or index route. When accessing user.about.slow-model route then Ember will alternate trying to find a routeName-loading or loading template in the hierarchy starting with user.about.slow-model-loading: user.about.slow-model-loading user.about.loading or user.about-loading user.loading or user-loading loading or application-loading It's important to note that for slow-model itself, Ember will not try to find a slow-model.loading template but for the rest of the hierarchy either syntax is acceptable. This can be useful for creating a custom loading screen for a leaf route like slow-model. When accessing user.about route then Ember will search for: user.about-loading user.loading or user-loading loading or application-loading It's important to note that user.about.loading template is not considered now. Ember will not look above the common parent in a transition between child routes. For example, if the user transitions from user.about.index to user.about.slow-model the following search for template will happen: user.about.slow-model-loading user.about.loading or user.about-loading Notice that user.loading, user-loading, loading, and application-loading are not included here, Since about is the common parent for index and slow-model. This means we'll need to handle loading at every level within the route hierarchy where loading feedback is important. The loading event If the various beforeModel/model/afterModel hooks don't immediately resolve, a loading event will be fired on that route. import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { action } from '@ember/object'; export default class FooSlowModelRoute extends Route { @service store; model() { return this.store.findAll('slow-model'); } @action loading(transition, originRoute) { let controller = this.controllerFor('foo'); controller.set('currentlyLoading', true); return true; // allows the loading template to be shown } } If the loading handler is not defined at the specific route, the event will continue to bubble above a transition's parent route, providing the application route the opportunity to manage it. When using the loading handler, we can make use of the transition promise to know when the loading event is over: import Route from '@ember/routing/route'; import { action } from '@ember/object'; export default class FooSlowModelRoute extends Route { // ... @action async loading(transition, originRoute) { let controller = this.controllerFor('foo'); controller.set('currentlyLoading', true); transition.promise.finally(function() { controller.set('currentlyLoading', false); }); } }; In case we want both custom logic and the default behavior for the loading substate, we can implement the loading action and let it bubble by returning true. import Route from '@ember/routing/route'; import { action } from '@ember/object'; export default class FooSlowModelRoute extends Route { // ... @action loading(transition) { let start = new Date(); transition.promise.finally(() => { this.notifier.notify(`Took ${new Date() - start}ms to load`); }); return true; } }; error substates Ember provides an analogous approach to loading substates in the case of errors encountered during a transition. Similar to how the default loading event handlers are implemented, the default error handlers will look for an appropriate error substate to enter, if one can be found. Router.map(function() { this.route('articles', function() { this.route('overview'); }); }); As with the loading substate, on a thrown error or rejected promise returned from the articles.overview route's model hook (or beforeModel or afterModel) Ember will look for an error template or route in the following order: articles.overview-error articles.error or articles-error error or application-error If one of the above is found, the router will immediately transition into that substate (without updating the URL). The "reason" for the error (i.e. the exception thrown or the promise reject value) will be passed to that error state as its model. The model hooks (beforeModel, model, and afterModel) of an error substate are not called. Only the setupController method of the error substate is called with the error as the model. See example below: setupController(controller, error) { console.log(error.message); super.setupController(...arguments) } If no viable error substates can be found, an error message will be logged. The error event If the articles.overview route's model hook returns a promise that rejects (for instance the server returned an error, the user isn't logged in, etc.), an error event will fire from that route and bubble upward. This error event can be handled and used to display an error message, redirect to a login page, etc. import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { action } from '@ember/object'; export default class ArticlesOverviewRoute extends Route { @service store; model(params) { return this.store.findAll('privileged-model'); } @action error(error, transition) { if (error.status === '403') { this.replaceWith('login'); } else { // Let the route above this handle the error. return true; } } }; Analogous to the loading event, you could manage the error event at the application level to avoid writing the same code for multiple routes. In case we want to run some custom logic and have the default behavior of rendering the error template, we can handle the error event and let it bubble by returning true. import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { action } from '@ember/object'; export default class ArticlesOverviewRoute extends Route { @service store; model(params) { return this.get('store').findAll('privileged-model'); } @action error(error) { this.notifier.error(error); return true; } };
Annotation Interface JavaBean @Documented @Target(TYPE) @Retention(RUNTIME) public @interface JavaBean An annotation used to specify some class-related information for the automatically generated BeanInfo classes. This annotation is not used if the annotated class has a corresponding user-defined BeanInfo class, which does not imply the automatic analysis. Since: 9 See Also: BeanInfo.getBeanDescriptor() Optional Element Summary Modifier and Type Optional Element Description String defaultEventSet The name of the default event set is used to calculate its index in the array of event sets defined in the annotated class. String defaultProperty The name of the default property is used to calculate its index in the array of properties defined in the annotated class. String description The short description for the bean descriptor of the annotated class. Element Details description String description The short description for the bean descriptor of the annotated class. Returns: the bean description, or an empty string if the description is not set. Default: "" defaultProperty String defaultProperty The name of the default property is used to calculate its index in the array of properties defined in the annotated class. If the name is not set or the annotated class does not define a property with the specified name, the default property index will be calculated automatically by the Introspector depending on its state. Returns: the name of the default property, or an empty string if the name is not set. Default: "" defaultEventSet String defaultEventSet The name of the default event set is used to calculate its index in the array of event sets defined in the annotated class. If the name is not set or the annotated class does not define an event set with the specified name, the default event set index will be calculated automatically by the Introspector depending on its state. Returns: the name of the default event set, or an empty string if the name is not set. Default: ""
Module snmpa_mpd Module Summary Message Processing and Dispatch module for the SNMP agent Description The module snmpa_mpd implements the version independent Message Processing and Dispatch functionality in SNMP for the agent. It is supposed to be used from a Network Interface process (Definition of Agent Net if). Data types See the data types in snmpa_conf. Exports init(Vsns) -> mpd_state() Types This function can be called from the net_if [email protected]. The options list defines which versions to use. It also initializes some SNMP counters. process_packet(Packet, From, State, NoteStore, Log) -> {ok, Vsn, Pdu, PduMS, ACMData} | {discarded, Reason} | {discovery, DiscoPacket} OTP 17.3 process_packet(Packet, From, LocalEngineID, State, NoteStore, Log) -> {ok, Vsn, Pdu, PduMS, ACMData} | {discarded, Reason} | {discovery, DiscoPacket} OTP R14B Types Processes an incoming packet. Performs authentication and decryption as necessary. The return values should be passed to the agent. Note Note that the use of the LocalEngineID argument is only intended for special cases, if the agent is to "emulate" multiple EngineIDs! By default, the agent uses the value of SnmpEngineID (see SNMP-FRAMEWORK-MIB). generate_response_msg(Vsn, RePdu, Type, ACMData, Log) -> {ok, Packet} | {discarded, Reason} OTP R14B generate_response_msg(Vsn, RePdu, Type, ACMData, LocalEngineID, Log) -> {ok, Packet} | {discarded, Reason} OTP R14B Types Generates a possibly encrypted response packet to be sent to the network. Type is the #pdu.type of the original request. Note Note that the use of the LocalEngineID argument is only intended for special cases, if the agent is to "emulate" multiple EngineIDs! By default, the agent uses the value of SnmpEngineID (see SNMP-FRAMEWORK-MIB). generate_msg(Vsn, NoteStore, Pdu, MsgData, To) -> {ok, PacketsAndAddresses} | {discarded, Reason} OTP R14B generate_msg(Vsn, NoteStore, Pdu, MsgData, LocalEngineID, To) -> {ok, PacketsAndAddresses} | {discarded, Reason} OTP R14B Types Generates a possibly encrypted request packet to be sent to the network. MsgData is the message specific data used in the SNMP message. This value is received in a send_pdu or send_pdu_req message from the agent. In SNMPv1 and SNMPv2c, this message data is the community string. In SNMPv3, it is the context information. To is a list of destination addresses and their corresponding security parameters. This value is received in the same message from the agent and then transformed trough process_taddrs before passed to this function. Note Note that the use of the LocalEngineID argument is only intended for special cases, if the agent is to "emulate" multiple EngineIDs! By default, the agent uses the value of SnmpEngineID (see SNMP-FRAMEWORK-MIB). process_taddrs(TDests) -> Dests OTP 17.3 Types Transforms addresses from internal MIB format to one more useful to Agent Net if. See also generate_msg. discarded_pdu(Variable) -> void() Types Increments the variable associated with a discarded pdu. This function can be used when the net_if process receives a discarded_pdu message from the agent. Copyright © 1997-2020 Ericsson AB. All Rights Reserved.
torch.divide torch.divide(input, other, *, rounding_mode=None, out=None) → Tensor Alias for torch.div().
public function LocalStream8b7c:f320:99b9:690f:4595:cd17:293a:c069stream_seek public LocalStream8b7c:f320:99b9:690f:4595:cd17:293a:c069stream_seek($offset, $whence = SEEK_SET) Seeks to specific location in a stream. This method is called in response to fseek(). The read/write position of the stream should be updated according to the offset and whence. Parameters int $offset: The byte offset to seek to. int $whence: Possible values: SEEK_SET: Set position equal to offset bytes. SEEK_CUR: Set position to current location plus offset. SEEK_END: Set position to end-of-file plus offset. Defaults to SEEK_SET. Return value bool TRUE if the position was updated, FALSE otherwise. Overrides PhpStreamWrapperInter8b7c:f320:99b9:690f:4595:cd17:293a:c069stream_seek See also http://php.net/manual/streamwrapper.stream-seek.php File core/lib/Drupal/Core/StreamWrapper/LocalStream.php, line 244 Class LocalStream Defines a Drupal stream wrapper base class for local files. Namespace Drupal\Core\StreamWrapper Code public function stream_seek($offset, $whence = SEEK_SET) { // fseek returns 0 on success and -1 on a failure. // stream_seek 1 on success and 0 on a failure. return !fseek($this->handle, $offset, $whence); }
CompilerInterface interface CompilerInterface (View source) Methods string getCompiledPath(string $path) Get the path to the compiled version of a view. bool isExpired(string $path) Determine if the given view is expired. void compile(string $path) Compile the view at the given path. Details string getCompiledPath(string $path) Get the path to the compiled version of a view. Parameters string $path Return Value string bool isExpired(string $path) Determine if the given view is expired. Parameters string $path Return Value bool void compile(string $path) Compile the view at the given path. Parameters string $path Return Value void
apply_filters( 'media_library_show_video_playlist', bool|null $show ) Allows showing or hiding the “Create Video Playlist” button in the media library. Description By default, the "Create Video Playlist" button will always be shown in the media library. If this filter returns null, a query will be run to determine whether the media library contains any video items. This was the default behavior prior to version 4.8.0, but this query is expensive for large media libraries. Parameters $show bool|null Whether to show the button, or null to decide based on whether any video files exist in the media library. Source File: wp-includes/media.php. View all references $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true ); Related Used By Used By Description wp_enqueue_media() wp-includes/media.php Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. Changelog Version Description 4.8.0 The filter's default value is true rather than null. 4.7.4 Introduced.
apply_filters( 'domain_exists', int|null $result, string $domain, string $path, int $network_id ) Filters whether a site name is taken. Description The name is the site’s subdomain or the site’s subdirectory path depending on the network settings. Parameters $result int|null The site ID if the site name exists, null otherwise. $domain string Domain to be checked. $path string Path to be checked. $network_id int Network ID. Relevant only on multi-network installations. Source File: wp-includes/ms-functions.php. View all references return apply_filters( 'domain_exists', $result, $domain, $path, $network_id ); Related Used By Used By Description domain_exists() wp-includes/ms-functions.php Checks whether a site name is already taken. Changelog Version Description 3.5.0 Introduced.
Date.prototype.getYear() Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The getYear() method returns the year in the specified date according to local time. Because getYear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getFullYear() method. Syntax getYear() Return value A number representing the year of the given date, according to local time, minus 1900.Description For years greater than or equal to 2000, the value returned by getYear() is 100 or greater. For example, if the year is 2026, getYear() returns 126. For years between and including 1900 and 1999, the value returned by getYear() is between 0 and 99. For example, if the year is 1976, getYear() returns 76. For years less than 1900, the value returned by getYear() is less than 0. For example, if the year is 1800, getYear() returns -100. To take into account years before and after 2000, you should use getFullYear() instead of getYear() so that the year is specified in full. Backward compatibility Behavior in JavaScript 1.2 and earlier The getYear() method returns either a 2-digit or 4-digit year: For years between and including 1900 and 1999, the value returned by getYear() is the year minus 1900. For example, if the year is 1976, the value returned is 76. For years less than 1900 or greater than 1999, the value returned by getYear() is the four-digit year. For example, if the year is 1856, the value returned is 1856. If the year is 2026, the value returned is 2026. Examples Years between 1900 and 1999 The second statement assigns the value 95 to the variable year. const xmas = new Date('December 25, 1995 23:15:00'); const year = xmas.getYear(); // returns 95 Years above 1999 The second statement assigns the value 100 to the variable year. const xmas = new Date('December 25, 2000 23:15:00'); const year = xmas.getYear(); // returns 100 Years below 1900 The second statement assigns the value -100 to the variable year. const xmas = new Date('December 25, 1800 23:15:00'); const year = xmas.getYear(); // returns -100 Setting and getting a year between 1900 and 1999 The third statement assigns the value 95 to the variable year, representing the year 1995. const xmas = new Date('December 25, 2015 23:15:00'); xmas.setYear(95); const year = xmas.getYear(); // returns 95 Specifications Specification ECMAScript Language Specification # sec-date.prototype.getyear Browser compatibility Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js getYear 1 12 1 3 3 1 4.4 18 4 10.1 1 1.0 1.0 0.10.0 See also Polyfill of Date.prototype.getYear in core-js Date.prototype.getFullYear() Date.prototype.getUTCFullYear() Date.prototype.setYear() Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Sep 5, 2022, by MDN contributors
wp_xmlrpc_server8b7c:f320:99b9:690f:4595:cd17:293a:c069wp_getPageTemplates( array $args ): array|IXR_Error Retrieve page templates. Parameters $args array Required Method arguments. Note: arguments must be ordered as documented. intBlog ID (unused). 1stringUsername. 2stringPassword. Return array|IXR_Error Source File: wp-includes/class-wp-xmlrpc-server.php. View all references public function wp_getPageTemplates( $args ) { $this->escape( $args ); $username = $args[1]; $password = $args[2]; $user = $this->login( $username, $password ); if ( ! $user ) { return $this->error; } if ( ! current_user_can( 'edit_pages' ) ) { return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) ); } $templates = get_page_templates(); $templates['Default'] = 'default'; return $templates; } Related Uses Uses Description get_page_templates() wp-admin/includes/theme.php Gets the page templates available in this theme. IXR_Error8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() wp-includes/IXR/class-IXR-error.php PHP5 constructor. current_user_can() wp-includes/capabilities.php Returns whether the current user has the specified capability. __() wp-includes/l10n.php Retrieves the translation of $text. wp_xmlrpc_server8b7c:f320:99b9:690f:4595:cd17:293a:c069scape() wp-includes/class-wp-xmlrpc-server.php Escape string or array of strings for database. wp_xmlrpc_server8b7c:f320:99b9:690f:4595:cd17:293a:c069login() wp-includes/class-wp-xmlrpc-server.php Log user in. Changelog Version Description 2.6.0 Introduced.
Command start Command Summary OTP start script example for Unix. Description The start script is an example script on how to start up the Erlang system in embedded mode on Unix. For more information about the use, see the Embedded System User's Guide in System Documentation. Exports start [ data_file ] Argument: data_file Optional. Specifies what start_erl.data file to use. Environment variable RELDIR can be set before calling this example, which sets the directory where to find the release files. See Also run_erl(1), start_erl(1) Copyright © 1997-2022 Ericsson AB. All Rights Reserved.
newrelic_alert_channel Example Usage resource "newrelic_alert_channel" "foo" { name = "foo" type = "email" configuration = { recipients = "[email protected]" include_json_attachment = "1" } } Argument Reference The following arguments are supported: name - (Required) The name of the channel. type - (Required) The type of channel. One of: campfire, email, hipchat, opsgenie, pagerduty, slack, victorops, or webhook. configuration - (Required) A map of key / value pairs with channel type specific values. Attributes Reference The following attributes are exported: id - The ID of the channel. Import Alert channels can be imported using the id, e.g. $ terraform import newrelic_alert_channel.main 12345
vsphere_tag The vsphere_tag resource can be used to create and manage tags, which allow you to attach metadata to objects in the vSphere inventory to make these objects more sortable and searchable. For more information about tags, click here. NOTE: Tagging support is unsupported on direct ESXi connections and requires vCenter 6.0 or higher. Example Usage This example creates a tag named terraform-test-tag. This tag is assigned the terraform-test-category category, which was created by the vsphere_tag_category resource. The resulting tag can be assigned to VMs and datastores only, and can be the only value in the category that can be assigned, as per the restrictions defined by the category. resource "vsphere_tag_category" "category" { name = "terraform-test-category" cardinality = "SINGLE" description = "Managed by Terraform" associable_types = [ "VirtualMachine", "Datastore", ] } resource "vsphere_tag" "tag" { name = "terraform-test-tag" category_id = "${vsphere_tag_category.category.id}" description = "Managed by Terraform" } Using Tags in a Supported Resource Tags can be applied to vSphere resources in Terraform via the tags argument in any supported resource. The following example builds on the above example by creating a vsphere_virtual_machine and applying the created tag to it: resource "vsphere_tag_category" "category" { name = "terraform-test-category" cardinality = "SINGLE" description = "Managed by Terraform" associable_types = [ "VirtualMachine", "Datastore", ] } resource "vsphere_tag" "tag" { name = "terraform-test-tag" category_id = "${vsphere_tag_category.category.id}" description = "Managed by Terraform" } resource "vsphere_virtual_machine" "web" { ... tags = ["${vsphere_tag.tag.id}"] } Argument Reference The following arguments are supported: name - (Required) The display name of the tag. The name must be unique within its category. category_id - (Required) The unique identifier of the parent category in which this tag will be created. Forces a new resource if changed. description - (Optional) A description for the tag. Attribute Reference The only attribute that is exported for this resource is the id, which is the uniform resource name (URN) of this tag. Importing An existing tag can be imported into this resource by supplying both the tag's category name and the name of the tag as a JSON string to terraform import, as per the example below: terraform import vsphere_tag.tag \ '{"category_name": "terraform-test-category", "tag_name": "terraform-test-tag"}'
[Java] Class NodeIterator groovy.xml.slurpersupport.NodeIterator All Implemented Interfaces and Traits: Iterator public abstract class NodeIterator extends Object implements Iterator Helper class for iterating through nodes. Constructor Summary Constructors Constructor and description NodeIterator(Iterator iter) Methods Summary Methods Type Params Return Type Name and description protected abstract Object getNextNode(Iterator iter) public boolean hasNext() public Object next() public void remove() Inherited Methods Summary Inherited Methods Methods inherited from class Name class Object wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll Constructor Detail public NodeIterator(Iterator iter) Method Detail protected abstract Object getNextNode(Iterator iter) @Override public boolean hasNext() @Override public Object next() @Override public void remove()
public function FormStateInter8b7c:f320:99b9:690f:4595:cd17:293a:c069setTemporary public FormStateInter8b7c:f320:99b9:690f:4595:cd17:293a:c069setTemporary(array $temporary) Sets temporary data. Parameters array $temporary: Temporary data accessible during the current page request only. Return value $this File core/lib/Drupal/Core/Form/FormStateInterface.php, line 962 Class FormStateInterface Provides an interface for an object containing the current state of a form. Namespace Drupal\Core\Form Code public function setTemporary(array $temporary);
(File):getBuffer Available since LÖVE 0.9.0 This function is not supported in earlier versions. Gets the buffer mode of a file. Function Synopsis mode, size = File:getBuffer( ) Arguments None. Returns BufferMode mode The current buffer mode of the file. number size The maximum size in bytes of the file's buffer. See Also File File:setBuffer File:write
CompletionItemResolveResult package haxe.display import haxe.display.Display Available on all platforms Alias alias for haxe.display.Response<{item:haxe.display.DisplayItem<Dynamic>}>
tf.math.count_nonzero View source on GitHub Computes number of nonzero elements across dimensions of a tensor. tf.math.count_nonzero( input, axis=None, keepdims=None, dtype=tf.dtypes.int64, name=None ) Reduces input along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned. Note: Floating point comparison to zero is done by exact floating point equality check. Small values are not rounded to zero for purposes of the nonzero check. For example: x = tf.constant([[0, 1, 0], [1, 1, 0]]) tf.math.count_nonzero(x) # 3 tf.math.count_nonzero(x, 0) # [1, 2, 0] tf.math.count_nonzero(x, 1) # [1, 2] tf.math.count_nonzero(x, 1, keepdims=True) # [[1], [2]] tf.math.count_nonzero(x, [0, 1]) # 3 Note: Strings are compared against zero-length empty string "". Any string with a size greater than zero is already considered as nonzero. For example: x = tf.constant(["", "a", " ", "b", ""]) tf.math.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings. Args input The tensor to reduce. Should be of numeric type, bool, or string. axis The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input), rank(input)). keepdims If true, retains reduced dimensions with length 1. dtype The output dtype; defaults to tf.int64. name A name for the operation (optional). Returns The reduced tensor (number of nonzero values).
1 ODBC Release Notes This document describes the changes made to the odbc application. 1.1 odbc 2.14 Improvements and New Features Input for configure scripts adapted to autoconf 2.71. Own Id: OTP-17414 Aux Id: PR-4967 1.2 odbc 2.13.5 Fixed Bugs and Malfunctions Commit of generated configure script. Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821 1.3 odbc 2.13.4 Fixed Bugs and Malfunctions Fix compiler warnings produced by the clang compiler. Own Id: OTP-17105 Aux Id: PR-2872 1.4 odbc (614)220-6831 Fixed Bugs and Malfunctions Commit of generated configure script. Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821 1.5 odbc 2.13.3 Fixed Bugs and Malfunctions Make sure odbc c-process exits when erlang process orders it to shutdown. Own Id: OTP-17188 Aux Id: ERL-1448 1.6 odbc 2.13.2 Fixed Bugs and Malfunctions Fixed usage of AC_CONFIG_AUX_DIRS() macros in configure script sources. Own Id: OTP-17093 Aux Id: ERL-1447, PR-2948 1.7 odbc 2.13.1 Improvements and New Features Changes in order to build on the Haiku operating system. Thanks to Calvin Buckley Own Id: OTP-16707 Aux Id: PR-2638 1.8 odbc 2.13 Fixed Bugs and Malfunctions Fix various compiler warnings on 64-bit Windows. Own Id: OTP-15800 Improvements and New Features Rewrite due to the removal of erl_interface legacy functions. Own Id: OTP-16544 Aux Id: OTP-16328 1.9 odbc (614)220-6831 Fixed Bugs and Malfunctions Commit of generated configure script. Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821 1.10 odbc 2.12.4 Improvements and New Features Minor adjustments made to build system for parallel configure. Own Id: OTP-15340 Aux Id: OTP-14625 1.11 odbc 2.12.3 Fixed Bugs and Malfunctions Enhance error handling to avoid stack corruption Own Id: OTP-15667 Aux Id: ERL-808, PR-2065 1.12 odbc 2.12.2 Fixed Bugs and Malfunctions Improved documentation. Own Id: OTP-15190 1.13 odbc 2.12.1 Fixed Bugs and Malfunctions Removed all old unused files in the documentation. Own Id: OTP-14475 Aux Id: ERL-409, PR-1493 1.14 odbc 2.12 Improvements and New Features Change configure to skip odbc for old MACs, the change in PR-1227 is not backwards compatible with old MACs, and we do not see a need to continue support for such old versions. However it is still possible to make it work on such machines using the --with-odbc configure option. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-14083 1.15 odbc 2.11.3 Fixed Bugs and Malfunctions ODBC build configure has been updated to accept Mac OS X El Capitan. Fixed by Lee Bannard. Own Id: OTP-13781 1.16 odbc 2.11.2 Improvements and New Features Configure enhancement for better handling program paths used in the build process Own Id: OTP-13559 1.17 odbc 2.11.1 Improvements and New Features New application variable to set timeout of internal communication setup between the erlang code and the c-port program that interfaces the odbc driver. This can be useful if you have an underlying system that is slow due to heavy [email protected]. With this environment variable you can easily bypass and tailor odbc to the needs of the underlying actual system without changing the configuration. Which is a good thing because this value is very system specific. Own Id: OTP-12935 1.18 odbc 2.11 Improvements and New Features Change license text from Erlang Public License to Apache Public License v2 Own Id: OTP-12845 1.19 odbc 2.10.22 Fixed Bugs and Malfunctions OS X Mavericks is based on Darwin version 13.x, and Yosemite on 14.x. Change the ODBC configure.in script to recognize these versions. Own Id: OTP-12260 Improvements and New Features The commands longer than 127 chars sent to odbc server crashed it, e.g. a connection string with driver path and some additional parameters. Own Id: OTP-12346 Distribute autoconf helpers to applications at build time instead of having multiple identical copies committed in the repository. Own Id: OTP-12348 1.20 odbc 2.10.21 Fixed Bugs and Malfunctions Fix compiler warnings reported by LLVM Own Id: OTP-12138 Implement --enable-sanitizers[=sanitizers]. Similar to debugging with Valgrind, it's very useful to enable -fsanitize= switches to catch [email protected]. Own Id: OTP-12153 1.21 odbc 2.10.20 Fixed Bugs and Malfunctions Application upgrade (appup) files are corrected for the following applications: asn1, common_test, compiler, crypto, debugger, dialyzer, edoc, eldap, erl_docgen, et, eunit, gs, hipe, inets, observer, odbc, os_mon, otp_mibs, parsetools, percept, public_key, reltool, runtime_tools, ssh, syntax_tools, test_server, tools, typer, webtool, wx, xmerl A new test utility for testing appup files is added to test_server. This is now used by most applications in OTP. (Thanks to Tobias Schlager) Own Id: OTP-11744 Improvements and New Features Removed warnings at compile time by adding missing include file (Thanks to Anthony Ramine) Own Id: OTP-11569 Apple has removed iODBC in OS X 10.9 Mavericks, but forgot to remove all binaries, adopt configure so that will be possible to build odbc with own installation. Own Id: OTP-11630 1.22 odbc 2.10.19 Fixed Bugs and Malfunctions Updated configure test for header files sql.h and sqlext.h to function correctly on windows. Own Id: OTP-11574 1.23 odbc 2.10.18 Improvements and New Features Configure now also checks for the existence of the sql.h header file Own Id: OTP-11483 1.24 odbc 2.10.17 Fixed Bugs and Malfunctions The format of the xml source for documentation is corrected in order to conform to the DTDs and to pass xmllint without errors. Own Id: OTP-11193 Improvements and New Features Introduced functionality for inspection of system and build configuration. Own Id: OTP-11196 Prevent odbcserver crash if it's executed and supplied incorrect data to stdin. Thanks to Sergei Golovan. Own Id: OTP-11233 1.25 odbc 2.10.16 Improvements and New Features Fix a 64bit related bug in odbcserver. Thanks to Satoshi Kinoshita. Own Id: OTP-10993 Postscript files no longer needed for the generation of PDF files have been removed. Own Id: OTP-11016 Fix checking for odbc in standard locations when "with-odbc" flag present. Thanks to Alexey Saltanov. Own Id: OTP-11126 1.26 odbc 2.10.15 Improvements and New Features Fixed calling odbc:param_query/3 and odbc:param_query/4 with unparameterized query string and empty parameters list. Thanks to Danil Onishchenko. Own Id: OTP-10798 1.27 odbc 2.10.14 Improvements and New Features Under Unix enable TCP_NODELAY to disable Nagel's socket algorithm. Thanks to Andy Richards Impact: Performance gain on Unix systems Own Id: OTP-10506 Added extended_errors option to ODBC When enabled, this option alters the return code of ODBC operations that produce errors to include the ODBC error code as well as the native error code, in addition to the ODBC reason field which is returned by default. Thanks to Bernard Duggan. Own Id: OTP-10603 Where necessary a comment stating encoding has been added to Erlang files. The comment is meant to be removed in Erlang/OTP R17B when UTF-8 becomes the default encoding. Own Id: OTP-10630 Some examples overflowing the width of PDF pages have been corrected. Own Id: OTP-10665 Fix aotocommit for Oracle ODBC driver in Linux. Thanks to Danil Onishchenko. Own Id: OTP-10735 1.28 odbc 2.10.13 Fixed Bugs and Malfunctions Add support for NULL value in odbc:param_query Support atom 'null' in odbc:param_query as database NULL value Fix "ODBC: received unexpected info:{tcp_closed, ...}" when connection is terminated. Fix possible access violation with 64bit ODBC. Thanks to Maxim Zrazhevskiy Own Id: OTP-10206 1.29 odbc 2.10.12 Fixed Bugs and Malfunctions An ODBC process should exit normally if its client exits with 'shutdown' There is nothing strange about the client shutting down, so the ODBC process should exit normally to avoid generating a crash report for a non-problem. (Thanks to Magnus Henoch) Own Id: OTP-9716 Improvements and New Features Erlang/OTP can now be built using parallel make if you limit the number of jobs, for instance using 'make -j6' or 'make -j10'. 'make -j' does not work at the moment because of some missing dependencies. Own Id: OTP-9451 1.30 odbc 2.10.11 Fixed Bugs and Malfunctions When using output parameters the internal odbc state was not correctly cleaned causing the next call to param_query to misbehave. Own Id: OTP-9444 XML files have been corrected. Own Id: OTP-9550 Aux Id: OTP-9541 Improvements and New Features Add code to handle old ODBC drivers on solaris. Also adds tests with MySQL. Own Id: OTP-8407 Odbc now supports SQL_WLONGVARCHAR, thanks to Hanfei Shen for the patch. Own Id: OTP-8493 1.31 odbc 2.10.10 Fixed Bugs and Malfunctions Better error messages for connection issues. Own Id: OTP-9111 1.32 odbc 2.10.9 Improvements and New Features Ipv6 is now supported on Windows as well as on UNIX for internal socket communication. (ODBC uses sockets instead of the "Erlang port pipes" as some ODBC-drivers are known to mess with stdin/stdout.) Loopback address constants are used when connecting the c-side to the erlang-side over local socket API avoiding getaddrinfo problems, and the {ip, loopback} option is added as a listen option on the erlang-side. Also cleaned up the TIME_STAMP contribution. Own Id: OTP-8917 1.33 odbc 2.10.8 Improvements and New Features ODBC now handles the types SQL_WCHAR and SQL_WVARCHAR. Thanks to Juhani Ränkimies. ODBC also has a new connection option to return all strings as binaries and also expect strings to be binaries in the param_query function. These changes provides some unicode support. Own Id: OTP-7452 Now supports SQL_TYPE_TIMESTAMP on the format {{YY, MM, DD}, {HH, MM, SS}}. Thanks to Juhani Ränkimies. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-8511 1.34 odbc 2.10.7 Fixed Bugs and Malfunctions The odbc application can now be compiled on FreeBSD. (Thanks to Kenji Rikitake.) Own Id: OTP-8444 Improvements and New Features Cross compilation improvements and other build system improvements. Most notable: Lots of cross compilation improvements. The old cross compilation support was more or less non-existing as well as broken. Please, note that the cross compilation support should still be considered as experimental. Also note that old cross compilation configurations cannot be used without modifications. For more information on cross compiling Erlang/OTP see the $ERL_TOP/INSTALL-CROSS.md file. Support for staged install using DESTDIR. The old broken INSTALL_PREFIX has also been fixed. For more information see the $ERL_TOP/INSTALL.md file. Documentation of the release target of the top Makefile. For more information see the $ERL_TOP/INSTALL.md file. make install now by default creates relative symbolic links instead of absolute ones. For more information see the $ERL_TOP/INSTALL.md file. $ERL_TOP/configure --help=recursive now works and prints help for all applications with configure scripts. Doing make install, or make release directly after make all no longer triggers miscellaneous rebuilds. Existing bootstrap system is now used when doing make install, or make release without a preceding make all. The crypto and ssl applications use the same runtime library path when dynamically linking against libssl.so and libcrypto.so. The runtime library search path has also been extended. The configure scripts of erl_interface and odbc now search for thread libraries and thread library quirks the same way as ERTS do. The configure script of the odbc application now also looks for odbc libraries in lib64 and lib/64 directories when building on a 64-bit system. The config.h.in file in the erl_interface application is now automatically generated in instead of statically updated which reduces the risk of configure tests without any effect. (Thanks to Henrik Riomar for suggestions and testing) (Thanks to Winston Smith for the AVR32-Linux cross configuration and testing) *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-8323 The documentation is now possible to build in an open source environment after a number of bugs are fixed and some features are added in the documentation build process. - The arity calculation is updated. - The module prefix used in the function names for bif's are removed in the generated links so the links will look like "http://www.erlang.org/doc/man/erlang.html#append_element-2" instead of "http://www.erlang.org/doc/man/erlang.html#erlang:append_element-2". - Enhanced the menu positioning in the html documentation when a new page is loaded. - A number of corrections in the generation of man pages (thanks to Sergei Golovan) - The legal notice is taken from the xml book file so OTP's build process can be used for non OTP applications. Own Id: OTP-8343 odbc:param_query() now properly indicates if nothing was updated. (Thanks to Paul Oliver.) Own Id: OTP-8347 Known Bugs and Problems The ODBC test cases are failing for linux and MacOSX There is problems with setting of options on odbc-connections, and the odbcserver just exits with an exit code. Own Id: OTP-8407 1.35 odbc 2.10.6 Fixed Bugs and Malfunctions Applied a patch from Andrew Thompson, which fixes some error cases. Own Id: OTP-8291 Improvements and New Features The documentation is now built with open source tools (xsltproc and fop) that exists on most platforms. One visible change is that the frames are removed. Own Id: OTP-8250 1.36 odbc 2.10.5 Fixed Bugs and Malfunctions A missing return statement in a non void function has been fixed in odbc. (Thanks to Nico Kruber) Own Id: OTP-7978 1.37 odbc 2.10.4 Improvements and New Features param_query now handles the in_or_out parameter correctly. Own Id: OTP-7720 Changed the internal socket use so that it will become more robust to non-functional ipv6 and fallback on ipv4. Own Id: OTP-7721 1.38 odbc 2.10.3 Improvements and New Features Configure update for mac. Own Id: OTP-7418 Known Bugs and Problems describe_table/[2,3] on mac gives an empty result Own Id: OTP-7478 1.39 odbc 2.10.2 Fixed Bugs and Malfunctions SQLINTEGERs where not retrieved correctly on 64 bit platforms as an SQLINTEGER is defined to be a 32 bit integer and not a true long. Own Id: OTP-7297 1.40 odbc 2.10.1 Improvements and New Features Now supports out and input parameters for stored procedures. Own Id: OTP-7019 ODBC is now prebuilt for SLES10 in the commercial build and parameters to error_logger:error_report/1 has been corrected. Own Id: OTP-7294 Parametrized queries will now work correctly when using Erlang R12B-2 on Linux (SuSE 10.3), MySQL 5.0.45, myodbc 3.51 and unixODBC 2.2.12. Earlier it could happen that an error was returned even though data was correctly inserted into the database. Own Id: OTP-7307 Known Bugs and Problems SQLINTEGERs are not retrieved correctly on 64 bit platforms as an SQLINTEGER seems to be defined to be a 32 bit integer and not a true long. Own Id: OTP-7297 1.41 odbc 2.10 Improvements and New Features Enhanced configure to among other things work better when there is a library found but it is not usable e.i. 32 bit library in 64 bit build. Own Id: OTP-7062 1.42 odbc 2.0.9 Improvements and New Features The odbc application now has to be explicitly started and stopped e.i. it will not automatically be started as a temporary application as it did before. Although a practical feature when testing things in the shell, it is not desirable that people take advantage of this and not start the odbc application in a correct way in their products. Added functions to the odbc API that calls application:start/stop. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-6984 Changed Makefile.in so that odbc is not disabled on 64-bits architectures. It was earlier disabled due to that it had never been tested in that environment. Own Id: OTP-6987 1.43 odbc 2.0.8 Improvements and New Features Minor Makefile changes. Own Id: OTP-6689 1.44 odbc 2.0.7 Fixed Bugs and Malfunctions When using a parameterized query on a windows platform the data was inserted in the table on the sql-server but the connection was lost, this seems to be due to a compiler error that has now been worked around, but further investigation is ongoing to verify that that really was the problem. Own Id: OTP-5504 param_query/[3,4] could return an unexpected row count for some drivers, in this case a postgresdriver. Own Id: OTP-6363 1.45 odbc 2.0.6 Fixed Bugs and Malfunctions pthread header and library mismatch on linux systems (at least some SuSE and Debian) with both NPTL and Linuxthreads libraries installed. Own Id: OTP-5981 Improvements and New Features Changed configure to find odbc in /usr/local too Own Id: OTP-5966 Known Bugs and Problems When using a parameterized query on a windows platform the data is inserted in the table on the sql-server but for some reason the connection is lost. Own Id: OTP-5504 1.46 odbc 2.0.5 Fixed Bugs and Malfunctions Fixed bug, reported error when deleting nonexisting rows, thanks to Laura M. Castro for reporting this. Own Id: OTP-5759 Known Bugs and Problems When using a parameterized query on a windows platform the data is inserted in the table on the sql-server but for some reason the connection is lost. Own Id: OTP-5504 1.47 Odbc 2.0.4 Improvements and New Features /usr was added as a default place for configure to look for the odbc library on unix/linux platforms. Own Id: OTP-5501 A legacy timer in the c port program was set to infinity. All timeout handling is handled by the erlang code and a extra timeout in the c code will just lead to confusion if it is released. Own Id: OTP-5502 Known Bugs and Problems When using a parameterized query on a windows platform the data is inserted in the table on the sql-server but for some reason the connection is lost. Own Id: OTP-5504 1.48 Odbc 2.0.3 Improvements and New Features odbc now uses configure as all "normal" applications instead of providing special Makefiles for each commercial supported platform. This also makes it easier to build odbc on non supported platforms. Own Id: OTP-5437 1.49 odbc 2.0.2 Fixed Bugs and Malfunctions When issuing a batch of queries and one of the queries fail the odbc port program crashed. This is no longer the case. Own Id: OTP-5176 1.50 odbc 2.0.1 Improvements and New Features Added use of the socket option TCP_NODELAY, as in the case of Erlang odbc the Nagel algorithm will never help, but always cause an unnecessary delay. Own Id: OTP-5100 1.51 odbc 2.0 Improvements and New Features Erlang ODBC now handles batches of queries and can return multiple result sets. Own Id: OTP-4642 Aux Id: seq7766 The old interface that became deprecated in odbc 1.0 has now been removed. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-4794 The port program now sends different exit codes to Erlang when it exits due to failure. This instead of sending the same exit code and then trying to write to stderr. Erlang encodes the exit code to a descriptive atom. Own Id: OTP-4813 Erlang ODBC now supports parameterized queries for the most common ODBC data types. Own Id: OTP-4821 SQL_NUMERIC and SQL_DECIMAL columns are converted to integer and float values if possible. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-4826 Result sets are now by default returned as a list of tuples which is the most intuitive and useful mapping. To keep some degree of backwards compatibility you may turn this off to get the old behavior that result sets are returned as lists of lists. However do not use this in new code as it is considered a deprecated feature that eventually will disappear. *** POTENTIAL INCOMPATIBILITY *** Own Id: OTP-4850 The odbc implementation now mostly uses sockets to communicate between the c and the erlang process, this is to avoid a lot of problems arising from different odbc-drivers doing strange things that disturbed the port-program communication mechanism. Own Id: OTP-4875 Copyright © 1999-2022 Ericsson AB. All Rights Reserved.
toChar kotlin-stdlib / kotlin / Char / toChar Platform and version requirements: JVM (1.0), JS (1.0), Native (1.3) fun toChar(): Char Returns the value of this character as a Char.
XRWebGLLayer.antialias The read-only XRWebGLLayer property antialias is a Boolean value which is true if the rendering layer's frame buffer supports antialiasing. Otherwise, this property's value is false. The specific antialiasing technique used is left to the user agent's discretion and cannot be specified by the web site or web app. Syntax let antialiasingSupported = xrWebGLLayer.antialias; Value A Boolean value which is true if the WebGL rendering layer's frame buffer is configured to support antialiasing. Otherwise, this property is false. When the WebXR compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the WebGL context's getContentAttributes() method. Usage notes Since this is a read-only property, you can set the antialiasing mode only when initially creating the XRWebGLLayer, by specifying the antialias property in the XRWebGLLayer() constructor's layerInit configuration object. Examples This snippet checks the value of antialias to see if it should perform additional work to attempt to compensate for the lack of antialiasing on the WebGL layer. let glLayer = xrSession.renderState.baseLayer; gl.bindFrameBuffer(gl.FRAMEBUFFER, glLayer.framebuffer); /* .. */ if (!glLayer.antialias) { /* compensate for lack of antialiasing */ } Specifications Specification WebXR Device API # dom-xrwebgllayer-antialias Browser compatibility Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet antialias 79 79 No No No No No 79 No No No 11.2 See also WebXR Device API WebGLLayerInit Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Feb 18, 2022, by MDN contributors
fortios_wireless_controller_inter_controller – Configure inter wireless controller operation in Fortinet’s FortiOS and FortiGate New in version 2.9. Synopsis Requirements Parameters Notes Examples Return Values Status Synopsis This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify wireless_controller feature and inter_controller category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 Requirements The below requirements are needed on the host that executes this module. fortiosapi>=0.9.8 Parameters Parameter Choices/Defaults Comments host string FortiOS or FortiGate IP address. https boolean Choices: no yes ← Indicates if the requests towards FortiGate must use HTTPS protocol. password string Default:"" FortiOS or FortiGate password. ssl_verify boolean Choices: no yes ← Ensures FortiGate certificate must be verified by a proper CA. username string FortiOS or FortiGate username. vdom string Default:"root" Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. wireless_controller_inter_controller dictionary Default:null Configure inter wireless controller operation. fast_failover_max integer Maximum number of retransmissions for fast failover HA messages between peer wireless controllers (3 - 64). fast_failover_wait integer Minimum wait time before an AP transitions from secondary controller to primary controller (10 - 86400 sec). inter_controller_key string Secret key for inter-controller communications. inter_controller_mode string Choices: disable l2-roaming 1+1 Configure inter-controller mode (disable, l2-roaming, 1+1). inter_controller_peer list Fast failover peer wireless controller list. id integer / required ID. peer_ip string Peer wireless controller's IP address. peer_port integer Port used by the wireless controller's for inter-controller communications (1024 - 49150). peer_priority string Choices: primary secondary Peer wireless controller's priority (primary or secondary). inter_controller_pri string Choices: primary secondary Configure inter-controller's priority (primary or secondary). Notes Note Requires fortiosapi library developed by Fortinet Run as a local_action in your playbook Examples - hosts: localhost vars: host: "9035908416" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure inter wireless controller operation. fortios_wireless_controller_inter_controller: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" wireless_controller_inter_controller: fast_failover_max: "3" fast_failover_wait: "4" inter_controller_key: "<your_own_value>" inter_controller_mode: "disable" inter_controller_peer: - id: "8" peer_ip: "<your_own_value>" peer_port: "10" peer_priority: "primary" inter_controller_pri: "primary" Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description build string always Build number of the fortigate image Sample: 1547 http_method string always Last method used to provision the content into FortiGate Sample: PUT http_status string always Last result given by FortiGate on last operation applied Sample: 200 mkey string success Master key (id) used in the last call to FortiGate Sample: id name string always Name of the table used to fulfill the request Sample: urlfilter path string always Path of the table used to fulfill the request Sample: webfilter revision string always Internal revision number Sample: 30.210-46-22078 serial string always Serial number of the unit Sample: FGVMEVYYQT3AB5352 status string always Indication of the operation's result Sample: success vdom string always Virtual domain used Sample: root version string always Version of the FortiGate Sample: v5.6.3 Status This module is not guaranteed to have a backwards compatible interface. [preview] This module is maintained by the Ansible Community. [community] Authors Miguel Angel Munoz (@mamunozgonzalez) Nicolas Thomas (@thomnico) Hint If you notice any issues in this documentation, you can edit this document to improve it. © 2012–2018 Michael DeHaan
BUILD_WITH_INSTALL_NAME_DIR BUILD_WITH_INSTALL_NAME_DIR is a boolean specifying whether the macOS install_name of a target in the build tree uses the directory given by INSTALL_NAME_DIR. This setting only applies to targets on macOS. This property is initialized by the value of the variable CMAKE_BUILD_WITH_INSTALL_NAME_DIR if it is set when a target is created. If this property is not set and policy CMP0068 is not NEW, the value of BUILD_WITH_INSTALL_RPATH is used in its place.
Getting Started with Qt Purchasing in C++ This guide assumes that you have registered the in-app products for your application in the external store. For more information about registering products, see Registering Products in Google Play, Registering Products in App Store, and Registering Products in Windows Store. Preparing the Application Use the following include statement to access the C++ classes: #include <QtPurchasing> Before building your application, add the following statement to your .pro file to link against the Qt Purchasing library: QT += purchasing Registering Products In order to allow in-app purchases in your application, register the products in your application. Start by creating an application-global instance of QInAppStore, and use the registerProduct() function to register each product. The following example is a hypothetical role-playing game, which provides two in-app products to the user. MyApplication8b7c:f320:99b9:690f:4595:cd17:293a:c069MyApplication(QObject *parent) : QObject(parent) { m_myStore = new QInAppStore(this); setupConnections(); m_myStore->registerProduct(QInAppProduct8b7c:f320:99b9:690f:4595:cd17:293a:c069onsumable, QStringLiteral("healthPotion")); m_myStore->registerProduct(QInAppProduct8b7c:f320:99b9:690f:4595:cd17:293a:c069Unlockable, QStringLiteral("dlcForestOfFooBar")); } As you can see, there are consumable products and unlockable products. The former can be purchased any number of times by the same user, whereas the latter can only be purchased once. In our example, the "healthPotion" is a consumable product, because the user should be able to buy any number of health potions and add them to their in-game inventory. The "dlcForestOfFooBar" is downloadable content, which unlocks a new part of the game, and once it is bought, the purchase should be persistent across the user's devices and across reinstallations. Making Connections Registering a product is an asynchronous operation, as are all operations supported by Qt Purchasing. Before you start registering a product, you must listen to the QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069productRegistered() and QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069productUnknown() signals in QInAppStore to know the status of your registration. If the application intends to allow users to purchase products, it also needs to listen for the QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069transactionReady() signal to be notified when a transaction is pending. void MyApplication8b7c:f320:99b9:690f:4595:cd17:293a:c069setupConnections() { connect(m_myStore, SIGNAL(productRegistered(QInAppProduct*)), this, SLOT(markProductAvailable(QInAppProduct*))); connect(m_myStore, SIGNAL(productUnknown(QInAppProduct*)), this, SLOT(handleErrorGracefully(QInAppProduct*))); connect(m_myStore, SIGNAL(transactionReady(QInAppTransaction*)), this, SLOT(handleTransaction(QInAppTransaction*))); } Purchasing A Product When the user wants to purchase a product, call QInAppProduct8b7c:f320:99b9:690f:4595:cd17:293a:c069purchase() on the product. This launches a platform-specific, asynchronous process to purchase the product, for example by requesting the user's password and confirmation of the purchase. In most cases, you must make sure that the application UI is not accepting input while the purchase request is being processed, as this is not handled automatically on all platforms. void MyApplication8b7c:f320:99b9:690f:4595:cd17:293a:c069purchaseHealthPotion() { QInAppProduct *product = m_myStore->registeredProduct(QStringLiteral("healthPotion")); // Should not get here if product is not registered Q_ASSERT(product != 0); product->purchase(); } When this function is called, the purchase process is initiated. At some point during the process, the QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069transactionReady() signal is emitted, and the slot registered earlier is called. In this function, you can save data about a successful purchase so that it survives across application runs. After verifying that the data has been stored, finalize the transaction. If the transaction fails, display information about the failure to the user and finalize the transaction. void MyApplication8b7c:f320:99b9:690f:4595:cd17:293a:c069handleTransaction(QInAppTransaction *transaction) { if (transaction->status() == QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseApproved && transaction->product()->identifier() == QStringLiteral("healthPotion")) { if (!hasAlreadyStoredTransaction(transaction->orderId()) { ++m_healthPotions; if (!addHealthPotionToPersistentStorage(transaction->orderId()) popupErrorDialog(tr("Unable to write to persistent storage. Please make sure there is sufficient space and restart.")) else transaction->finalize(); } } else if (transaction->status() == QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseFailed) { popupErrorDialog(tr("Purchase not completed.")); transaction->finalize(); } } If a transaction is not finalized, the transactionReady() signal is emitted again for the same transaction the next time the product is registered, providing another chance to store the data. The transaction for a consumable product must be finalized before the product can be purchased again. Restoring Previously Purchased Products If the application is uninstalled and subsequently reinstalled (or installed by the same user on a different device), you must provide a way to restore the previously purchased unlockable products. To start the process of restoring purchases, call the QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069restorePurchases() function. This emits the QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069transactionReady() signal for each of the application's unlockable products that were purchased previously by the current user. The status of these transactions will be QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseRestored. Continuing on the example from earlier, lets imagine that the game has downloadable content that you can buy to extend the game further. This must be an unlockable product, because the user need not purchase it more than once. void MyApplication8b7c:f320:99b9:690f:4595:cd17:293a:c069handleTransaction(QInAppTransaction *transaction) { if ((transaction->status() == QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseApproved || transaction->status() == QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseRestored) && transaction->product()->identifier() == QStringLiteral("dlcForestOfFooBar")) { if (!hasMap(QStringLiteral("forestOfFooBar.map")) { if (!downloadExtraMap(QStringLiteral("forestOfFooBar.map"))) popupErrorDialog(tr("Unable to download The Forest of FooBar map. Please make sure there is sufficient space and restart.")) else transaction->finalize() } } else if (transaction->status() == QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseApproved && transaction->product()->identifier() == QStringLiteral("healthPotion")) { // ... handle healthPotion purchase } else { popupErrorDialog(tr("Purchase not completed.")); transaction->finalize(); } } If a user buys the downloadable content and later either installs the game on another device or uninstalls and reinstalls the game, you can provide a way to restore the purchase by calling QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069restorePurchases(). Purchases must be restored in response to a user input, as it may present a password dialog on some platforms. Note: While the function behaves as documented on Android, this functionality is technically not needed there. Android manages all unlockable purchases with no intervention from the application. If an application is uninstalled and reinstalled (or installed on a different Android device), QInAppStor8b7c:f320:99b9:690f:4595:cd17:293a:c069transactionReady() is emitted at application start-up for each previously purchased unlockable product, with the QInAppTransaction8b7c:f320:99b9:690f:4595:cd17:293a:c069PurchaseApproved status.
is_object (PHP 4, PHP 5, PHP 7, PHP 8) is_object — Finds whether a variable is an object Description is_object(mixed $value): bool Finds whether the given variable is an object. Parameters value The variable being evaluated. Return Values Returns true if value is an object, false otherwise. Changelog Version Description 7.2.0 is_object() now returns true for unserialized objects without a class definition (class of __PHP_Incomplete_Class). Previously false was returned. Examples Example #1 is_object() example <?php // Declare a simple function to return an  // array from our object function get_students($obj) {     if (!is_object($obj)) {         return false;     }     return $obj->students; } // Declare a new class instance and fill up  // some values $obj = new stdClass(); $obj->students = array('Kalle', 'Ross', 'Felipe'); var_dump(get_students(null)); var_dump(get_students($obj)); ?> See Also is_bool() - Finds out whether a variable is a boolean is_int() - Find whether the type of a variable is integer is_float() - Finds whether the type of a variable is float is_string() - Find whether the type of a variable is string is_array() - Finds whether a variable is an array
st8b7c:f320:99b9:690f:4595:cd17:293a:c069basic_string_view<CharT,Traits>8b7c:f320:99b9:690f:4595:cd17:293a:c069operator[] constexpr const_reference operator[]( size_type pos ) const; (since C++17) Returns a const reference to the character at specified location pos. No bounds checking is performed: the behavior is undefined if pos >= size(). Parameters pos - position of the character to return Return value Const reference to the requested character. Exceptions Does not throw. Complexity Constant. Notes Unlike st8b7c:f320:99b9:690f:4595:cd17:293a:c069basic_string8b7c:f320:99b9:690f:4595:cd17:293a:c069operator[], st8b7c:f320:99b9:690f:4595:cd17:293a:c069basic_string_view8b7c:f320:99b9:690f:4595:cd17:293a:c069operator[](size()) has undefined behavior instead of returning CharT(). Example #include <iostream> #include <string_view> int main() { st8b7c:f320:99b9:690f:4595:cd17:293a:c069string str = "Exemplar"; st8b7c:f320:99b9:690f:4595:cd17:293a:c069string_view v = str; st8b7c:f320:99b9:690f:4595:cd17:293a:c069cout << v[2] << '\n'; // v[2] = 'y'; // Error: cannot modify through a string view str[2] = 'y'; st8b7c:f320:99b9:690f:4595:cd17:293a:c069cout << v[2] << '\n'; } Output: e y See also at (C++17) accesses the specified character with bounds checking (public member function) operator[] accesses the specified character (public member function of st8b7c:f320:99b9:690f:4595:cd17:293a:c069basic_string<CharT,Traits,Allocator>)
ce_ntp - Manages core NTP configuration on HUAWEI CloudEngine switches. New in version 2.4. Synopsis Parameters Examples Return Values Status Author Synopsis Manages core NTP configuration on HUAWEI CloudEngine switches. Parameters Parameter Choices/Defaults Comments is_preferred Choices: enable disable Default:None Makes given NTP server or peer the preferred NTP server or peer for the device. key_id Default:None Authentication key identifier to use with given NTP server or peer. peer Default:None Network address of NTP peer. server Default:None Network address of NTP server. source_int Default:None Local source interface from which NTP messages are sent. Must be fully qualified interface name, i.e. 40GE1/0/22, vlanif10. Interface types, such as 10GE, 40GE, 100GE, Eth-Trunk, LoopBack, MEth, NULL, Tunnel, Vlanif. state Choices: present ← absent Manage the state of the resource. vpn_name Default:_public_ Makes the device communicate with the given NTP server or peer over a specific vpn. Examples - name: NTP test hosts: cloudengine connection: local gather_facts: no vars: cli: host: "{{ inventory_hostname }}" port: "{{ ansible_ssh_port }}" username: "{{ username }}" password: "{{ password }}" transport: cli tasks: - name: "Set NTP Server with parameters" ce_ntp: server: (909)220-3029 vpn_name: js source_int: vlanif4001 is_preferred: enable key_id: 32 provider: "{{ cli }}" - name: "Set NTP Peer with parameters" ce_ntp: peer: (909)220-3029 vpn_name: js source_int: vlanif4001 is_preferred: enable key_id: 32 provider: "{{ cli }}" Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description changed boolean always check to see if a change was made on the device Sample: True end_state dict always k/v pairs of ntp info after module execution Sample: {'key_id': '48', 'vpn_name': 'js', 'server': '(909)220-3029', 'is_preferred': 'enable', 'source_int': 'vlanif4002'} existing dict always k/v pairs of existing ntp server/peer Sample: {'key_id': '32', 'vpn_name': 'js', 'server': '(909)220-3029', 'is_preferred': 'disable', 'source_int': 'vlanif4002'} proposed dict always k/v pairs of parameters passed into module Sample: {'state': 'present', 'is_preferred': 'enable', 'key_id': '48', 'vpn_name': 'js', 'server': '(909)220-3029', 'source_int': 'vlanif4002'} updates list always command sent to the device Sample: ['ntp server (909)220-3029 authentication-keyid 48 source-interface vlanif4002 vpn-instance js preferred'] Status This module is flagged as preview which means that it is not guaranteed to have a backwards compatible interface. Author Zhijin Zhou (@CloudEngine-Ansible) Hint If you notice any issues in this documentation you can edit this document to improve it. © 2012–2018 Michael DeHaan
tf.raw_ops.EncodeJpegVariableQuality JPEG encode input image with provided compression quality. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.raw_ops.EncodeJpegVariableQuality tf.raw_ops.EncodeJpegVariableQuality( images, quality, name=None ) image is a 3-D uint8 Tensor of shape [height, width, channels]. quality is an int32 jpeg compression quality value between 0 and 100. Args images A Tensor of type uint8. Images to adjust. At least 3-D. quality A Tensor of type int32. An int quality to encode to. name A name for the operation (optional). Returns A Tensor of type string.
iam_role - Manage AWS IAM roles New in version 2.3. Synopsis Requirements (on host that executes module) Options Examples Return Values Notes Status Synopsis Manage AWS IAM roles Requirements (on host that executes module) boto boto3 botocore python >= 2.6 Options parameter required default choices comments assume_role_policy_document no The trust relationship policy document that grants an entity permission to assume the role. This parameter is required when state: present. aws_access_key no AWS access key. If not set then the value of the AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY or EC2_ACCESS_KEY environment variable is used. aliases: ec2_access_key, access_key aws_secret_key no AWS secret key. If not set then the value of the AWS_SECRET_ACCESS_KEY, AWS_SECRET_KEY, or EC2_SECRET_KEY environment variable is used. aliases: ec2_secret_key, secret_key ec2_url no Url to use to connect to EC2 or your Eucalyptus cloud (by default the module will use EC2 endpoints). Ignored for modules where region is required. Must be specified for all other modules if region is not used. If not set then the value of the EC2_URL environment variable, if any, is used. managed_policy yes A list of managed policy ARNs or, since Ansible 2.4, a list of either managed policy ARNs or friendly names. To embed an inline policy, use iam_policy. To remove existing policies, use an empty list item. aliases: managed_policies name yes The name of the role to create. path no / The path to the role. For more information about paths, see http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html. profile(added in 1.6) no Uses a boto profile. Only works with boto >= 2.24.0. security_token(added in 1.6) no AWS STS security token. If not set then the value of the AWS_SECURITY_TOKEN or EC2_SECURITY_TOKEN environment variable is used. aliases: access_token state yes present absent Create or remove the IAM role validate_certs(added in 1.5) no yes yes no When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0. Examples # Note: These examples do not set authentication details, see the AWS Guide for details. # Create a role - iam_role: name: mynewrole assume_role_policy_document: "{{ lookup('file','policy.json') }}" state: present # Create a role and attach a managed policy called "PowerUserAccess" - iam_role: name: mynewrole assume_role_policy_document: "{{ lookup('file','policy.json') }}" state: present managed_policy: - arn:aws:iam8b7c:f320:99b9:690f:4595:cd17:293a:c069ws:policy/PowerUserAccess # Keep the role created above but remove all managed policies - iam_role: name: mynewrole assume_role_policy_document: "{{ lookup('file','policy.json') }}" state: present managed_policy: - # Delete the role - iam_role: name: mynewrole assume_role_policy_document: "{{ lookup('file','policy.json') }}" state: absent Return Values Common return values are documented here Return Values, the following are the fields unique to this module: name description returned type sample arn the Amazon Resource Name (ARN) specifying the role always string arn:aws:iam8b7c:f320:99b9:690f:4595:cd17:293a:c069567890:role/mynewrole assume_role_policy_document the policy that grants an entity permission to assume the role always string {'version': '2012-10-17', 'statement': [{'action': 'sts:AssumeRole', 'principal': {'service': 'ec2.amazonaws.com'}, 'effect': 'Allow', 'sid': ''}]} attached_policies a list of dicts containing the name and ARN of the managed IAM policies attached to the role always list [{'policy_arn': 'arn:aws:iam8b7c:f320:99b9:690f:4595:cd17:293a:c069ws:policy/PowerUserAccess', 'policy_name': 'PowerUserAccess'}] create_date the date and time, in ISO 8601 date-time format, when the role was created always string 2016-08-14T04:36:28+00:00 path the path to the role always string / role_id the stable and unique string identifying the role always string ABCDEFF4EZ4ABCDEFV4ZC role_name the friendly name that identifies the role always string myrole Notes Note If parameters are not set within the module, the following environment variables can be used in decreasing order of precedence AWS_URL or EC2_URL, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY, AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN or EC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See http://boto.readthedocs.org/en/latest/boto_config_tut.html AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but this can also be configured in the boto config file Status This module is flagged as preview which means that it is not guaranteed to have a backwards compatible interface. For help in developing on modules, should you be so inclined, please read Community Information & Contributing, Testing Ansible and Developing Modules. © 2012–2018 Michael DeHaan
numpy.polynomial.chebyshev.chebvander2d polynomial.chebyshev.chebvander2d(x, y, deg)[source] Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees deg and sample points (x, y). The pseudo-Vandermonde matrix is defined by \[V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),\] where 0 <= i <= deg[0] and 0 <= j <= deg[1]. The leading indices of V index the points (x, y) and the last index encodes the degrees of the Chebyshev polynomials. If V = chebvander2d(x, y, [xdeg, ydeg]), then the columns of V correspond to the elements of a 2-D coefficient array c of shape (xdeg + 1, ydeg + 1) in the order \[c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\] and np.dot(V, c.flat) and chebval2d(x, y, c) will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Chebyshev series of the same degrees and sample points. Parameters x, yarray_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deglist of ints List of maximum degrees of the form [x_deg, y_deg]. Returns vander2dndarray The shape of the returned matrix is x.shape + (order,), where \(order = (deg[0]+1)*(deg[1]+1)\). The dtype will be the same as the converted x and y. See also chebvander, chebvander3d, chebval2d, chebval3d Notes New in version 1.7.0.
IAuthManager Package system.base Inheritance interface IAuthManager Subclasses CAuthManager, CDbAuthManager, CPhpAuthManager Since 1.0 Source Code framework/base/interfaces.php IAuthManager interface is implemented by an auth manager application component. An auth manager is mainly responsible for providing role-based access control (RBAC) service. Public Methods Method Description Defined By addItemChild() Adds an item as a child of another item. IAuthManager assign() Assigns an authorization item to a user. IAuthManager checkAccess() Performs access check for the specified user. IAuthManager clearAll() Removes all authorization data. IAuthManager clearAuthAssignments() Removes all authorization assignments. IAuthManager createAuthItem() Creates an authorization item. IAuthManager executeBizRule() Executes a business rule. IAuthManager getAuthAssignment() Returns the item assignment information. IAuthManager getAuthAssignments() Returns the item assignments for the specified user. IAuthManager getAuthItem() Returns the authorization item with the specified name. IAuthManager getAuthItems() Returns the authorization items of the specific type and user. IAuthManager getItemChildren() Returns the children of the specified item. IAuthManager hasItemChild() Returns a value indicating whether a child exists within a parent. IAuthManager isAssigned() Returns a value indicating whether the item has been assigned to the user. IAuthManager removeAuthItem() Removes the specified authorization item. IAuthManager removeItemChild() Removes a child from its parent. IAuthManager revoke() Revokes an authorization assignment from a user. IAuthManager save() Saves authorization data into persistent storage. IAuthManager saveAuthAssignment() Saves the changes to an authorization assignment. IAuthManager saveAuthItem() Saves an authorization item to persistent storage. IAuthManager Method Details addItemChild() method abstract public void addItemChild(string $itemName, string $childName) $itemName string the parent item name $childName string the child item name Source Code: framework/base/interfaces.php#399 (show) public function addItemChild($itemName,$childName); Adds an item as a child of another item. assign() method abstract public CAuthAssignment assign(string $itemName, mixed $userId, string $bizRule=NULL, mixed $data=NULL) $itemName string the item name $userId mixed the user ID (see IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId) $bizRule string the business rule to be executed when checkAccess is called for this particular authorization item. $data mixed additional data associated with this assignment {return} CAuthAssignment the authorization assignment information. Source Code: framework/base/interfaces.php#433 (show) public function assign($itemName,$userId,$bizRule=null,$data=null); Assigns an authorization item to a user. checkAccess() method abstract public boolean checkAccess(string $itemName, mixed $userId, array $params=array ( )) $itemName string the name of the operation that we are checking access to $userId mixed the user ID. This should be either an integer or a string representing the unique identifier of a user. See IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId. $params array name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user. {return} boolean whether the operations can be performed by the user. Source Code: framework/base/interfaces.php#347 (show) public function checkAccess($itemName,$userId,$params=array()); Performs access check for the specified user. clearAll() method abstract public void clearAll() Source Code: framework/base/interfaces.php#472 (show) public function clearAll(); Removes all authorization data. clearAuthAssignments() method abstract public void clearAuthAssignments() Source Code: framework/base/interfaces.php#476 (show) public function clearAuthAssignments(); Removes all authorization assignments. createAuthItem() method abstract public CAuthItem createAuthItem(string $name, integer $type, string $description='', string $bizRule=NULL, mixed $data=NULL) $name string the item name. This must be a unique identifier. $type integer the item type (0: operation, 1: task, 2: role). $description string description of the item $bizRule string business rule associated with the item. This is a piece of PHP code that will be executed when checkAccess is called for the item. $data mixed additional data associated with the item. {return} CAuthItem the authorization item Source Code: framework/base/interfaces.php#364 (show) public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null); Creates an authorization item. An authorization item represents an action permission (e.g. creating a post). It has three types: operation, task and role. Authorization items form a hierarchy. Higher level items inherit permissions representing by lower level items. executeBizRule() method abstract public boolean executeBizRule(string $bizRule, array $params, mixed $data) $bizRule string the business rule to be executed. $params array additional parameters to be passed to the business rule when being executed. $data mixed additional data that is associated with the corresponding authorization item or assignment {return} boolean whether the execution returns a true value. If the business rule is empty, it will also return true. Source Code: framework/base/interfaces.php#494 (show) public function executeBizRule($bizRule,$params,$data); Executes a business rule. A business rule is a piece of PHP code that will be executed when checkAccess is called. getAuthAssignment() method abstract public CAuthAssignment getAuthAssignment(string $itemName, mixed $userId) $itemName string the item name $userId mixed the user ID (see IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId) {return} CAuthAssignment the item assignment information. Null is returned if the item is not assigned to the user. Source Code: framework/base/interfaces.php#455 (show) public function getAuthAssignment($itemName,$userId); Returns the item assignment information. getAuthAssignments() method abstract public array getAuthAssignments(mixed $userId) $userId mixed the user ID (see IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId) {return} array the item assignment information for the user. An empty array will be returned if there is no item assigned to the user. Source Code: framework/base/interfaces.php#462 (show) public function getAuthAssignments($userId); Returns the item assignments for the specified user. getAuthItem() method abstract public CAuthItem getAuthItem(string $name) $name string the name of the item {return} CAuthItem the authorization item. Null if the item cannot be found. Source Code: framework/base/interfaces.php#385 (show) public function getAuthItem($name); Returns the authorization item with the specified name. getAuthItems() method abstract public array getAuthItems(integer $type=NULL, mixed $userId=NULL) $type integer the item type (0: operation, 1: task, 2: role). Defaults to null, meaning returning all items regardless of their type. $userId mixed the user ID. Defaults to null, meaning returning all items even if they are not assigned to a user. {return} array the authorization items of the specific type. Source Code: framework/base/interfaces.php#379 (show) public function getAuthItems($type=null,$userId=null); Returns the authorization items of the specific type and user. getItemChildren() method abstract public array getItemChildren(mixed $itemName) $itemName mixed the parent item name. This can be either a string or an array. The latter represents a list of item names. {return} array all child items of the parent Source Code: framework/base/interfaces.php#421 (show) public function getItemChildren($itemName); Returns the children of the specified item. hasItemChild() method abstract public boolean hasItemChild(string $itemName, string $childName) $itemName string the parent item name $childName string the child item name {return} boolean whether the child exists Source Code: framework/base/interfaces.php#414 (show) public function hasItemChild($itemName,$childName); Returns a value indicating whether a child exists within a parent. isAssigned() method abstract public boolean isAssigned(string $itemName, mixed $userId) $itemName string the item name $userId mixed the user ID (see IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId) {return} boolean whether the item has been assigned to the user. Source Code: framework/base/interfaces.php#447 (show) public function isAssigned($itemName,$userId); Returns a value indicating whether the item has been assigned to the user. removeAuthItem() method abstract public boolean removeAuthItem(string $name) $name string the name of the item to be removed {return} boolean whether the item exists in the storage and has been removed Source Code: framework/base/interfaces.php#370 (show) public function removeAuthItem($name); Removes the specified authorization item. removeItemChild() method abstract public boolean removeItemChild(string $itemName, string $childName) $itemName string the parent item name $childName string the child item name {return} boolean whether the removal is successful Source Code: framework/base/interfaces.php#407 (show) public function removeItemChild($itemName,$childName); Removes a child from its parent. Note, the child item is not deleted. Only the parent-child relationship is removed. revoke() method abstract public boolean revoke(string $itemName, mixed $userId) $itemName string the item name $userId mixed the user ID (see IWebUser8b7c:f320:99b9:690f:4595:cd17:293a:c069getId) {return} boolean whether removal is successful Source Code: framework/base/interfaces.php#440 (show) public function revoke($itemName,$userId); Revokes an authorization assignment from a user. save() method abstract public void save() Source Code: framework/base/interfaces.php#483 (show) public function save(); Saves authorization data into persistent storage. If any change is made to the authorization data, please make sure you call this method to save the changed data into persistent storage. saveAuthAssignment() method abstract public void saveAuthAssignment(CAuthAssignment $assignment) $assignment CAuthAssignment the assignment that has been changed. Source Code: framework/base/interfaces.php#467 (show) public function saveAuthAssignment($assignment); Saves the changes to an authorization assignment. saveAuthItem() method abstract public void saveAuthItem(CAuthItem $item, string $oldName=NULL) $item CAuthItem the item to be saved. $oldName string the old item name. If null, it means the item name is not changed. Source Code: framework/base/interfaces.php#391 (show) public function saveAuthItem($item,$oldName=null); Saves an authorization item to persistent storage.
QCategoryAxis Class The QCategoryAxis class places named ranges on the axis. More... Header: #include <QCategoryAxis> Instantiated By: CategoryAxis Inherits: QValueAxis List of all members, including inherited members Public Types enum AxisLabelsPosition { AxisLabelsPositionCenter, AxisLabelsPositionOnValue } Properties categoriesLabels : const QStringList count : const int labelsPosition : AxisLabelsPosition startValue : qreal 5 properties inherited from QValueAxis 27 properties inherited from QAbstractAxis 1 property inherited from QObject Public Functions QCategoryAxis(QObject *parent = Q_NULLPTR) ~QCategoryAxis() void append(const QString &categoryLabel, qreal categoryEndValue) QStringList categoriesLabels() int count() const qreal endValue(const QString &categoryLabel) const QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition labelsPosition() const void remove(const QString &categoryLabel) void replaceLabel(const QString &oldLabel, const QString &newLabel) void setLabelsPosition(QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition position) void setStartValue(qreal min) qreal startValue(const QString &categoryLabel = QString()) const Reimplemented Public Functions virtual AxisType type() const 12 public functions inherited from QValueAxis 58 public functions inherited from QAbstractAxis 32 public functions inherited from QObject Signals void categoriesChanged() void labelsPositionChanged(QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition position) 6 signals inherited from QValueAxis 25 signals inherited from QAbstractAxis 2 signals inherited from QObject Additional Inherited Members 1 public slot inherited from QValueAxis 1 public slot inherited from QObject 11 static public members inherited from QObject 9 protected functions inherited from QObject Detailed Description The QCategoryAxis class places named ranges on the axis. This class can be used to explain the underlying data by adding labeled categories. Unlike QBarCategoryAxis, QCategoryAxis allows the widths of the category ranges to be specified freely. Example code on how to use QCategoryAxis: QChartView *chartView = new QChartView; QLineSeries *series = new QLineSeries; // ... chartView->chart()->addSeries(series); QCategoryAxis *axisY = new QCategoryAxis; axisY->setMin(0); axisY->setMax(52); axisY->setStartValue(15); axisY->append("First", 20); axisY->append("Second", 37); axisY->append("Third", 52); chartView->chart()->setAxisY(axisY, series); Member Type Documentation enum QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition This enum describes the position of the category labels. Constant Value Description QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPositionCenter 0x0 Labels are centered to category. QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPositionOnValue 0x1 Labels are positioned to the high end limit of the category. Property Documentation categoriesLabels : const QStringList This property holds the category labels as a string list. Access functions: QStringList categoriesLabels() count : const int This property holds the number of categories. Access functions: int count() const labelsPosition : AxisLabelsPosition This property holds the position of the category labels. The labels in the beginning and in the end of the axes may overlap other axes' labels when positioned on value. Access functions: QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition labelsPosition() const void setLabelsPosition(QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition position) Notifier signal: void labelsPositionChanged(QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069xisLabelsPosition position) startValue : qreal This property holds the low end of the first category on the axis. Access functions: qreal startValue(const QString &categoryLabel = QString()) const void setStartValue(qreal min) Member Function Documentation QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069QCategoryAxis(QObject *parent = Q_NULLPTR) Constructs an axis object that is a child of parent. QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069~QCategoryAxis() Destroys the object. void QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069ppend(const QString &categoryLabel, qreal categoryEndValue) Appends a new category to the axis with the label categoryLabel. A category label has to be unique. categoryEndValue specifies the high end limit of the category. It has to be greater than the high end limit of the previous category. Otherwise the method returns without adding a new category. [signal] void QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069tegoriesChanged() This signal is emitted when the categories of the axis change. QStringList QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069tegoriesLabels() Returns the list of the categories' labels. Note: Getter function for property categoriesLabels. int QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069ount() const Returns the number of categories. Note: Getter function for property count. qreal QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069ndValue(const QString &categoryLabel) const Returns the high end limit of the category specified by categoryLabel. void QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069remove(const QString &categoryLabel) Removes a category specified by the label categoryLabel from the axis. void QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069replaceLabel(const QString &oldLabel, const QString &newLabel) Replaces an existing category label specified by oldLabel with newLabel. If the old label does not exist, the method returns without making any changes. void QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069setStartValue(qreal min) Sets min to be the low end limit of the first category on the axis. If categories have already been added to the axis, the passed value must be less than the high end value of the already defined first category range. Otherwise nothing is done. Note: Setter function for property startValue. See also startValue(). qreal QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069startValue(const QString &categoryLabel = QString()) const Returns the low end limit of the category specified by categoryLabel. Note: Getter function for property startValue. See also setStartValue(). [virtual] AxisType QCategoryAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069type() const Reimplemented from QAbstractAxis8b7c:f320:99b9:690f:4595:cd17:293a:c069type(). Returns the type of the axis.
public function PoStreamWriter8b7c:f320:99b9:690f:4595:cd17:293a:c069open public PoStreamWriter8b7c:f320:99b9:690f:4595:cd17:293a:c069open() Open the stream. Set the URI for the stream earlier with setURI(). Overrides PoStreamInter8b7c:f320:99b9:690f:4595:cd17:293a:c069open File core/lib/Drupal/Component/Gettext/PoStreamWriter.php, line 74 Class PoStreamWriter Defines a Gettext PO stream writer. Namespace Drupal\Component\Gettext Code public function open() { // Open in write mode. Will overwrite the stream if it already exists. $this->_fd = fopen($this->getURI(), 'w'); // Write the header at the start. $this->writeHeader(); }
ForbiddenOverwriteException class ForbiddenOverwriteException extends InvalidConfigurationException This exception is thrown when a configuration path is overwritten from a subsequent configuration file, but the entry node specifically forbids this. Methods setPath($path) from InvalidConfigurationException getPath() from InvalidConfigurationException addHint(string $hint) Adds extra information that is suffixed to the original exception message. from InvalidConfigurationException Details setPath($path) Parameters $path getPath() addHint(string $hint) Adds extra information that is suffixed to the original exception message. Parameters string $hint
rst This module implements a reStructuredText parser. A large subset is implemented. Some features of the markdown wiki syntax are also supported. Note: Import packages/docutils/rst to use this module Imports rstast Types RstParseOption = enum roSkipPounds, ## skip ``#`` at line beginning (documentation ## embedded in Nim comments) roSupportSmilies, ## make the RST parser support smilies like ``:)`` roSupportRawDirective, ## support the ``raw`` directive (don't support ## it for sandboxing) roSupportMarkdown ## support additional features of markdown options for the RST parser Source Edit RstParseOptions = set[RstParseOption] Source Edit MsgClass = enum mcHint = "Hint", mcWarning = "Warning", mcError = "Error" Source Edit MsgKind = enum meCannotOpenFile, meExpected, meGridTableNotImplemented, meNewSectionExpected, meGeneralParseError, meInvalidDirective, mwRedefinitionOfLabel, mwUnknownSubstitution, mwUnsupportedLanguage, mwUnsupportedField the possible messages Source Edit MsgHandler = proc (filename: string; line, col: int; msgKind: MsgKind; arg: string) {...}{.closure, gcsafe.} what to do in case of an error Source Edit FindFileHandler = proc (filename: string): string {...}{.closure, gcsafe.} Source Edit EParseError = object of ValueError Source Edit Procs proc whichMsgClass(k: MsgKind): MsgClass {...}{.raises: [], tags: [].} returns which message class k belongs to. Source Edit proc defaultMsgHandler(filename: string; line, col: int; msgkind: MsgKind; arg: string) {...}{.raises: [ValueError, EParseError, IOError], tags: [WriteIOEffect].} Source Edit proc defaultFindFile(filename: string): string {...}{.raises: [], tags: [ReadDirEffect].} Source Edit proc addNodes(n: PRstNode): string {...}{.raises: [], tags: [].} Source Edit proc rstnodeToRefname(n: PRstNode): string {...}{.raises: [], tags: [].} Source Edit proc getFieldValue(n: PRstNode): string {...}{.raises: [], tags: [].} Returns the value of a specific rnField node. This proc will assert if the node is not of the expected type. The empty string will be returned as a minimum. Any value in the rst will be stripped form leading/trailing whitespace. Source Edit proc getFieldValue(n: PRstNode; fieldname: string): string {...}{.raises: [], tags: [].} Source Edit proc getArgument(n: PRstNode): string {...}{.raises: [], tags: [].} Source Edit proc rstParse(text, filename: string; line, column: int; hasToc: var bool; options: RstParseOptions; findFile: FindFileHandler = nil; msgHandler: MsgHandler = nil): PRstNode {...}{.raises: [Exception], tags: [ReadEnvEffect, RootEffect].} Source Edit
Imagick8b7c:f320:99b9:690f:4595:cd17:293a:c069getImageAlphaChannel (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick8b7c:f320:99b9:690f:4595:cd17:293a:c069getImageAlphaChannel — Checks if the image has an alpha channel Description public Imagick8b7c:f320:99b9:690f:4595:cd17:293a:c069getImageAlphaChannel(): bool Returns whether the image has an alpha channel. Parameters This function has no parameters. Return Values Returns true if the image has an alpha channel value and false if not, i.e. the image is RGB rather than RGBA or CMYK rather than CMYKA. Errors/Exceptions Throws ImagickException on error. Changelog Version Description imagick 3.6.0 Returns a bool now; previously, an int was returned.
wp_delete_attachment( int $post_id, bool $force_delete = false ): WP_Post|false|null Trashes or deletes an attachment. Description When an attachment is permanently deleted, the file will also be removed.Deletion removes all post meta fields, taxonomy, comments, etc. associated with the attachment (except the main post). The attachment is moved to the Trash instead of permanently deleted unless Trash for media is disabled, item is already in the Trash, or $force_delete is true. Parameters $post_id int Required Attachment ID. $force_delete bool Optional Whether to bypass Trash and force deletion. Default: false Return WP_Post|false|null Post data on success, false or null on failure. Source File: wp-includes/post.php. View all references function wp_delete_attachment( $post_id, $force_delete = false ) { global $wpdb; $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) ); if ( ! $post ) { return $post; } $post = get_post( $post ); if ( 'attachment' !== $post->post_type ) { return false; } if ( ! $force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' !== $post->post_status ) { return wp_trash_post( $post_id ); } /** * Filters whether an attachment deletion should take place. * * @since 5.5.0 * * @param WP_Post|false|null $delete Whether to go forward with deletion. * @param WP_Post $post Post object. * @param bool $force_delete Whether to bypass the Trash. */ $check = apply_filters( 'pre_delete_attachment', null, $post, $force_delete ); if ( null !== $check ) { return $check; } delete_post_meta( $post_id, '_wp_trash_meta_status' ); delete_post_meta( $post_id, '_wp_trash_meta_time' ); $meta = wp_get_attachment_metadata( $post_id ); $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true ); $file = get_attached_file( $post_id ); if ( is_multisite() && is_string( $file ) && ! empty( $file ) ) { clean_dirsize_cache( $file ); } /** * Fires before an attachment is deleted, at the start of wp_delete_attachment(). * * @since 2.0.0 * @since 5.5.0 Added the `$post` parameter. * * @param int $post_id Attachment ID. * @param WP_Post $post Post object. */ do_action( 'delete_attachment', $post_id, $post ); wp_delete_object_term_relationships( $post_id, array( 'category', 'post_tag' ) ); wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) ); // Delete all for any posts. delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); wp_defer_comment_counting( true ); $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d ORDER BY comment_ID DESC", $post_id ) ); foreach ( $comment_ids as $comment_id ) { wp_delete_comment( $comment_id, true ); } wp_defer_comment_counting( false ); $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ) ); foreach ( $post_meta_ids as $mid ) { delete_metadata_by_mid( 'post', $mid ); } /** This action is documented in wp-includes/post.php */ do_action( 'delete_post', $post_id, $post ); $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) ); if ( ! $result ) { return false; } /** This action is documented in wp-includes/post.php */ do_action( 'deleted_post', $post_id, $post ); wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file ); clean_post_cache( $post ); return $post; } Hooks do_action( 'deleted_post', int $postid, WP_Post $post ) Fires immediately after a post is deleted from the database. do_action( 'delete_attachment', int $post_id, WP_Post $post ) Fires before an attachment is deleted, at the start of wp_delete_attachment() . do_action( 'delete_post', int $postid, WP_Post $post ) Fires immediately before a post is deleted from the database. apply_filters( 'pre_delete_attachment', WP_Post|false|null $delete, WP_Post $post, bool $force_delete ) Filters whether an attachment deletion should take place. Related Uses Uses Description clean_dirsize_cache() wp-includes/functions.php Cleans directory size cache used by recurse_dirsize() . wp_delete_attachment_files() wp-includes/post.php Deletes all files that belong to the given attachment. delete_metadata() wp-includes/meta.php Deletes metadata for the specified object. wp_delete_comment() wp-includes/comment.php Trashes or deletes a comment. wp_defer_comment_counting() wp-includes/comment.php Determines whether to defer comment counting. wp8b7c:f320:99b9:690f:4595:cd17:293a:c069delete() wp-includes/class-wpdb.php Deletes a row in the table. wp8b7c:f320:99b9:690f:4595:cd17:293a:c069get_col() wp-includes/class-wpdb.php Retrieves one column from the database. wp8b7c:f320:99b9:690f:4595:cd17:293a:c069get_row() wp-includes/class-wpdb.php Retrieves one row from the database. get_attached_file() wp-includes/post.php Retrieves attached file path based on attachment ID. delete_metadata_by_mid() wp-includes/meta.php Deletes metadata by meta ID. delete_post_meta() wp-includes/post.php Deletes a post meta field for the given post ID. wp_trash_post() wp-includes/post.php Moves a post or page to the Trash wp_get_attachment_metadata() wp-includes/post.php Retrieves attachment metadata for attachment ID. clean_post_cache() wp-includes/post.php Will clean the post in the cache. get_object_taxonomies() wp-includes/taxonomy.php Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. wp_delete_object_term_relationships() wp-includes/taxonomy.php Unlinks the object from the taxonomy or taxonomies. get_post() wp-includes/post.php Retrieves post data given a post ID or post object. do_action() wp-includes/plugin.php Calls the callback functions that have been added to an action hook. apply_filters() wp-includes/plugin.php Calls the callback functions that have been added to a filter hook. wp8b7c:f320:99b9:690f:4595:cd17:293a:c069prepare() wp-includes/class-wpdb.php Prepares a SQL query for safe execution. is_multisite() wp-includes/load.php If Multisite is enabled. get_post_meta() wp-includes/post.php Retrieves a post meta field for the given post ID. Used By Used By Description wp_ajax_media_create_image_subsizes() wp-admin/includes/ajax-actions.php Ajax handler for creating missing image sub-sizes for just uploaded images. File_Upload_Upgrader8b7c:f320:99b9:690f:4595:cd17:293a:c069leanup() wp-admin/includes/class-file-upload-upgrader.php Delete the attachment/uploaded file. wp_import_cleanup() wp-admin/includes/import.php Cleanup importer. wp_delete_post() wp-includes/post.php Trashes or deletes a post or page. Changelog Version Description 2.0.0 Introduced.
Queues Introduction Writing Job Classes Generating Job Classes Job Class Structure Pushing Jobs Onto The Queue Delayed Jobs Dispatching Jobs From Requests Job Events Running The Queue Listener Supervisor Configuration Daemon Queue Listener Deploying With Daemon Queue Listeners Dealing With Failed Jobs Failed Job Events Retrying Failed Jobs Introduction The Laravel queue service provides a unified API across a variety of different queue back-ends. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time which drastically speeds up web requests to your application. Configuration The queue configuration file is stored in config/queue.php. In this file you will find connection configurations for each of the queue drivers that are included with the framework, which includes a database, Beanstalkd, IronMQ, Amazon SQS, Redis, and synchronous (for local use) driver. A null queue driver is also included which simply discards queued jobs. Driver Prerequisites Database In order to use the database queue driver, you will need a database table to hold the jobs. To generate a migration that creates this table, run the queue:table Artisan command. Once the migration is created, you may migrate your database using the migrate command: php artisan queue:table php artisan migrate Other Queue Dependencies The following dependencies are needed for the listed queue drivers: Amazon SQS: aws/aws-sdk-php ~3.0 Beanstalkd: pda/pheanstalk ~3.0 IronMQ: iron-io/iron_mq ~2.0|~4.0 Redis: predis/predis ~1.0 Writing Job Classes Generating Job Classes By default, all of the queueable jobs for your application are stored in the app/Jobs directory. You may generate a new queued job using the Artisan CLI: php artisan make:job SendReminderEmail --queued This command will generate a new class in the app/Jobs directory, and the class will implement the Illuminate\Contracts\Queue\ShouldQueue interface, indicating to Laravel that the job should be pushed onto the queue instead of run synchronously. Job Class Structure Job classes are very simple, normally containing only a handle method which is called when the job is processed by the queue. To get started, let's take a look at an example job class: <?php namespace App\Jobs; use App\User; use App\Jobs\Job; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; class SendReminderEmail extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels; protected $user; /** * Create a new job instance. * * @param User $user * @return void */ public function __construct(User $user) { $this->user = $user; } /** * Execute the job. * * @param Mailer $mailer * @return void */ public function handle(Mailer $mailer) { $mailer->send('emails.reminder', ['user' => $this->user], function ($m) { // }); $this->user->reminders()->create(...); } } In this example, note that we were able to pass an Eloquent model directly into the queued job's constructor. Because of the SerializesModels trait that the job is using, Eloquent models will be gracefully serialized and unserialized when the job is processing. If your queued job accepts an Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database. It's all totally transparent to your application and prevents issues that can arise from serializing full Eloquent model instances. The handle method is called when the job is processed by the queue. Note that we are able to type-hint dependencies on the handle method of the job. The Laravel service container automatically injects these dependencies. When Things Go Wrong If an exception is thrown while the job is being processed, it will automatically be released back onto the queue so it may be attempted again. The job will continue to be released until it has been attempted the maximum number of times allowed by your application. The number of maximum attempts is defined by the --tries switch used on the queue:listen or queue:work Artisan jobs. More information on running the queue listener can be found below. Manually Releasing Jobs If you would like to release the job manually, the InteractsWithQueue trait, which is already included in your generated job class, provides access to the queue job release method. The release method accepts one argument: the number of seconds you wish to wait until the job is made available again: public function handle(Mailer $mailer) { if (condition) { $this->release(10); } } Checking The Number Of Run Attempts As noted above, if an exception occurs while the job is being processed, it will automatically be released back onto the queue. You may check the number of attempts that have been made to run the job using the attempts method: public function handle(Mailer $mailer) { if ($this->attempts() > 3) { // } } Pushing Jobs Onto The Queue The default Laravel controller located in app/Http/Controllers/Controller.php uses a DispatchesJobs trait. This trait provides several methods allowing you to conveniently push jobs onto the queue, such as the dispatch method: <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Jobs\SendReminderEmail; use App\Http\Controllers\Controller; class UserController extends Controller { /** * Send a reminder e-mail to a given user. * * @param Request $request * @param int $id * @return Response */ public function sendReminderEmail(Request $request, $id) { $user = User8b7c:f320:99b9:690f:4595:cd17:293a:c069indOrFail($id); $this->dispatch(new SendReminderEmail($user)); } } Of course, sometimes you may wish to dispatch a job from somewhere in your application besides a route or controller. For that reason, you can include the DispatchesJobs trait on any of the classes in your application to gain access to its various dispatch methods. For example, here is a sample class that uses the trait: <?php namespace App; use Illuminate\Foundation\Bus\DispatchesJobs; class ExampleClass { use DispatchesJobs; } Specifying The Queue For A Job You may also specify the queue a job should be sent to. By pushing jobs to different queues, you may "categorize" your queued jobs, and even prioritize how many workers you assign to various queues. This does not push jobs to different queue "connections" as defined by your queue configuration file, but only to specific queues within a single connection. To specify the queue, use the onQueue method on the job instance. The onQueue method is provided by the Illuminate\Bus\Queueable trait, which is already included on the App\Jobs\Job base class: <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Jobs\SendReminderEmail; use App\Http\Controllers\Controller; class UserController extends Controller { /** * Send a reminder e-mail to a given user. * * @param Request $request * @param int $id * @return Response */ public function sendReminderEmail(Request $request, $id) { $user = User8b7c:f320:99b9:690f:4595:cd17:293a:c069indOrFail($id); $job = (new SendReminderEmail($user))->onQueue('emails'); $this->dispatch($job); } } Delayed Jobs Sometimes you may wish to delay the execution of a queued job. For instance, you may wish to queue a job that sends a customer a reminder e-mail 15 minutes after sign-up. You may accomplish this using the delay method on your job class, which is provided by the Illuminate\Bus\Queueable trait: <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Jobs\SendReminderEmail; use App\Http\Controllers\Controller; class UserController extends Controller { /** * Send a reminder e-mail to a given user. * * @param Request $request * @param int $id * @return Response */ public function sendReminderEmail(Request $request, $id) { $user = User8b7c:f320:99b9:690f:4595:cd17:293a:c069indOrFail($id); $job = (new SendReminderEmail($user))->delay(60); $this->dispatch($job); } } In this example, we're specifying that the job should be delayed in the queue for 60 seconds before being made available to workers. Note: The Amazon SQS service has a maximum delay time of 15 minutes. Dispatching Jobs From Requests It is very common to map HTTP request variables into jobs. So, instead of forcing you to do this manually for each request, Laravel provides some helper methods to make it a cinch. Let's take a look at the dispatchFrom method available on the DispatchesJobs trait. By default, this trait is included on the base Laravel controller class: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CommerceController extends Controller { /** * Process the given order. * * @param Request $request * @param int $id * @return Response */ public function processOrder(Request $request, $id) { // Process the request... $this->dispatchFrom('App\Jobs\ProcessOrder', $request); } } This method will examine the constructor of the given job class and extract variables from the HTTP request (or any other ArrayAccess object) to fill the needed constructor parameters of the job. So, if our job class accepts a productId variable in its constructor, the job bus will attempt to pull the productId parameter from the HTTP request. You may also pass an array as the third argument to the dispatchFrom method. This array will be used to fill any constructor parameters that are not available on the request: $this->dispatchFrom('App\Jobs\ProcessOrder', $request, [ 'taxPercentage' => 20, ]); Job Events Job Completion Event The Queu8b7c:f320:99b9:690f:4595:cd17:293a:c069after method allows you to register a callback to be executed when a queued job executes successfully. This callback is a great opportunity to perform additional logging, queue a subsequent job, or increment statistics for a dashboard. For example, we may attach a callback to this event from the AppServiceProvider that is included with Laravel: <?php namespace App\Providers; use Queue; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Queu8b7c:f320:99b9:690f:4595:cd17:293a:c069after(function ($connection, $job, $data) { // }); } /** * Register the service provider. * * @return void */ public function register() { // } } Running The Queue Listener Starting The Queue Listener Laravel includes an Artisan command that will run new jobs as they are pushed onto the queue. You may run the listener using the queue:listen command: php artisan queue:listen You may also specify which queue connection the listener should utilize: php artisan queue:listen connection Note that once this task has started, it will continue to run until it is manually stopped. You may use a process monitor such as Supervisor to ensure that the queue listener does not stop running. Queue Priorities You may pass a comma-delimited list of queue connections to the listen job to set queue priorities: php artisan queue:listen --queue=high,low In this example, jobs on the high queue will always be processed before moving onto jobs from the low queue. Specifying The Job Timeout Parameter You may also set the length of time (in seconds) each job should be allowed to run: php artisan queue:listen --timeout=60 Specifying Queue Sleep Duration In addition, you may specify the number of seconds to wait before polling for new jobs: php artisan queue:listen --sleep=5 Note that the queue only "sleeps" if no jobs are on the queue. If more jobs are available, the queue will continue to work them without sleeping. Supervisor Configuration Supervisor is a process monitor for the Linux operating system, and will automatically restart your queue:listen or queue:work commands if they fail. To install Supervisor on Ubuntu, you may use the following command: sudo apt-get install supervisor Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a laravel-worker.conf file that starts and monitors a queue:work process: [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3 --daemon autostart=true autorestart=true user=forge numprocs=8 redirect_stderr=true stdout_logfile=/home/forge/app.com/worker.log In this example, the numprocs directive will instruct Supervisor to run 8 queue:work processes and monitor all of them, automatically restarting them if they fail. Of course, you should change the queue:work sqs portion of the command directive to reflect your chosen queue driver. Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands: sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start laravel-worker:* For more information on configuring and using Supervisor, consult the Supervisor documentation. Alternatively, you may use Laravel Forge to automatically configure and manage your Supervisor configuration from a convenient web interface. Daemon Queue Listener The queue:work Artisan command includes a --daemon option for forcing the queue worker to continue processing jobs without ever re-booting the framework. This results in a significant reduction of CPU usage when compared to the queue:listen command: To start a queue worker in daemon mode, use the --daemon flag: php artisan queue:work connection --daemon php artisan queue:work connection --daemon --sleep=3 php artisan queue:work connection --daemon --sleep=3 --tries=3 As you can see, the queue:work job supports most of the same options available to queue:listen. You may use the php artisan help queue:work job to view all of the available options. Coding Considerations For Daemon Queue Listeners Daemon queue workers do not restart the framework before processing each job. Therefore, you should be careful to free any heavy resources before your job finishes. For example, if you are doing image manipulation with the GD library, you should free the memory with imagedestroy when you are done. Similarly, your database connection may disconnect when being used by a long-running daemon. You may use the 8b7c:f320:99b9:690f:4595:cd17:293a:c069reconnect method to ensure you have a fresh connection. Deploying With Daemon Queue Listeners Since daemon queue workers are long-lived processes, they will not pick up changes in your code without being restarted. So, the simplest way to deploy an application using daemon queue workers is to restart the workers during your deployment script. You may gracefully restart all of the workers by including the following command in your deployment script: php artisan queue:restart This command will gracefully instruct all queue workers to restart after they finish processing their current job so that no existing jobs are lost. Note: This command relies on the cache system to schedule the restart. By default, APCu does not work for CLI jobs. If you are using APCu, add apc.enable_cli=1 to your APCu configuration. Dealing With Failed Jobs Since things don't always go as planned, sometimes your queued jobs will fail. Don't worry, it happens to the best of us! Laravel includes a convenient way to specify the maximum number of times a job should be attempted. After a job has exceeded this amount of attempts, it will be inserted into a failed_jobs table. The name of the table can be configured via the config/queue.php configuration file. To create a migration for the failed_jobs table, you may use the queue:failed-table command: php artisan queue:failed-table When running your queue listener, you may specify the maximum number of times a job should be attempted using the --tries switch on the queue:listen command: php artisan queue:listen connection-name --tries=3 Failed Job Events If you would like to register an event that will be called when a queued job fails, you may use the Queu8b7c:f320:99b9:690f:4595:cd17:293a:c069failing method. This event is a great opportunity to notify your team via e-mail or HipChat. For example, we may attach a callback to this event from the AppServiceProvider that is included with Laravel: <?php namespace App\Providers; use Queue; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Queu8b7c:f320:99b9:690f:4595:cd17:293a:c069failing(function ($connection, $job, $data) { // Notify team of failing job... }); } /** * Register the service provider. * * @return void */ public function register() { // } } Failed Method On Job Classes For more granular control, you may define a failed method directly on a queue job class, allowing you to perform job specific actions when a failure occurs: <?php namespace App\Jobs; use App\Jobs\Job; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; class SendReminderEmail extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels; /** * Execute the job. * * @param Mailer $mailer * @return void */ public function handle(Mailer $mailer) { // } /** * Handle a job failure. * * @return void */ public function failed() { // Called when the job is failing... } } Retrying Failed Jobs To view all of your failed jobs that have been inserted into your failed_jobs database table, you may use the queue:failed Artisan command: php artisan queue:failed The queue:failed command will list the job ID, connection, queue, and failure time. The job ID may be used to retry the failed job. For instance, to retry a failed job that has an ID of 5, the following command should be issued: php artisan queue:retry 5 To retry all of your failed jobs, use queue:retry with all as the ID: php artisan queue:retry all If you would like to delete a failed job, you may use the queue:forget command: php artisan queue:forget 5 To delete all of your failed jobs, you may use the queue:flush command: php artisan queue:flush
DeleteOptions DeleteOptions may be provided when deleting an API object. import "k8s.io/apimachinery/pkg/apis/meta/v1" DeleteOptions may be provided when deleting an API object. apiVersion (string) APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources dryRun ([]string) When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed gracePeriodSeconds (int64) The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. kind (string) Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds orphanDependents (boolean) Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. preconditions (Preconditions) Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out. preconditions.resourceVersion (string) Specifies the target ResourceVersion preconditions.uid (string) Specifies the target UID. propagationPolicy (string) Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. Feedback Was this page helpful? Yes No Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it on Stack Overflow. Open an issue in the GitHub repo if you want to report a problem or suggest an improvement. Last modified January 19, 2021 at 8:51 PM PST: New API Reference presentation on /content/en/docs/reference/kubernetes-api (add24db3e) Edit this page Create child page Create an issue Print entire section © 2022 The Kubernetes Authors | Documentation Distributed under CC BY 4.0 Copyright
Array.prototype.keys() The keys() method returns a new Array Iterator object that contains the keys for each index in the array. Try it Syntax keys() Return value A new Array iterator object.Examples Key iterator doesn't ignore holes const arr = ['a', , 'c']; const sparseKeys = Object.keys(arr); const denseKeys = [...arr.keys()]; console.log(sparseKeys); // ['0', '2'] console.log(denseKeys); // [0, 1, 2] Specifications Specification ECMAScript Language Specification # sec-array.prototype.keys Browser compatibility Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js keys 38 12 28 No 25 8 38 38 28 25 8 3.0 1.0 0.12.0 See also Polyfill of Array.prototype.keys in core-js Array.prototype.values() Array.prototype.entries() Iteration protocols A polyfill Found a problem with this page? Edit on GitHub Source on GitHub Report a problem with this content on GitHub Want to fix the problem yourself? See our Contribution guide. Last modified: Mar 8, 2022, by MDN contributors
dart:html midiMessageEvent constant EventStreamProvider<MidiMessageEvent> midiMessageEvent = const EventStreamProvider<MidiMessageEvent>('midimessage') Static factory designed to expose midimessage events to event handlers that are not necessarily instances of MidiInput. See EventStreamProvider for usage information.
dart:developer serverUri property Uri serverUri final The Uri to access the service. If the web server is not running, this will be null.
TestBedStatic interface Static methods implemented by the TestBed. interface TestBedStatic extends TestBed { new (...args: any[]): TestBed // inherited from core/testing/TestBed platform: PlatformRef ngModule: Type<any> | Type<any>[] initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, options?: TestEnvironmentOptions): void resetTestEnvironment(): void resetTestingModule(): TestBed configureCompiler(config: { providers?: any[]; useJit?: boolean; }): void configureTestingModule(moduleDef: TestModuleMetadata): TestBed compileComponents(): Promise<any> inject<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false; }): T get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any execute(tokens: any[], fn: Function, context?: any): any overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed overrideTemplate(component: Type<any>, template: string): TestBed overrideProvider(token: any, provider: { useFactory: Function; deps: any[]; }): TestBed overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed createComponent<T>(component: Type<T>): ComponentFixture<T> } Methods construct signature new (...args: any[]): TestBed Parameters args any[] Returns TestBed
public static function EntityListBuilder8b7c:f320:99b9:690f:4595:cd17:293a:c069reateInstance public static EntityListBuilder8b7c:f320:99b9:690f:4595:cd17:293a:c069reateInstance(ContainerInterface $container, EntityTypeInterface $entity_type) Instantiates a new instance of this entity handler. This is a factory method that returns a new instance of this object. The factory should pass any needed dependencies into the constructor of this object, but not the container itself. Every call to this method must return a new instance of this object; that is, it may not implement a singleton. Parameters \Symfony\Component\DependencyInjection\ContainerInterface $container: The service container this object should use. \Drupal\Core\Entity\EntityTypeInterface $entity_type: The entity type definition. Return value static A new instance of the entity handler. Overrides EntityHandlerInter8b7c:f320:99b9:690f:4595:cd17:293a:c069createInstance File core/lib/Drupal/Core/Entity/EntityListBuilder.php, line 48 Class EntityListBuilder Defines a generic implementation to build a listing of entities. Namespace Drupal\Core\Entity Code public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) { return new static( $entity_type, $container->get('entity.manager')->getStorage($entity_type->id()) ); }
dart:collection toString method String toString() Returns a string representation of (some of) the elements of this. Elements are represented by their own toString results. The default representation always contains the first three elements. If there are less than a hundred elements in the iterable, it also contains the last two elements. If the resulting string isn't above 80 characters, more elements are included from the start of the iterable. The conversion may omit calling toString on some elements if they are known to not occur in the output, and it may stop iterating after a hundred elements. Source String toString() => IterableBase.iterableToFullString(this, '{', '}');
Class Identity java.lang.Object java.security.Identity All Implemented Interfaces: Serializable, Principal Direct Known Subclasses: IdentityScope, Signer @Deprecated(since="1.2", forRemoval=true) public abstract class Identity extends Object implements Principal, Serializable Deprecated, for removal: This API element is subject to removal in a future version. This class is deprecated and subject to removal in a future version of Java SE. It has been replaced by java.security.KeyStore, the java.security.cert package, and java.security.Principal. This class represents identities: real-world objects such as people, companies or organizations whose identities can be authenticated using their public keys. Identities may also be more abstract (or concrete) constructs, such as daemon threads or smart cards. All Identity objects have a name and a public key. Names are immutable. Identities may also be scoped. That is, if an Identity is specified to have a particular scope, then the name and public key of the Identity are unique within that scope. An Identity also has a set of certificates (all certifying its own public key). The Principal names specified in these certificates need not be the same, only the key. An Identity can be subclassed, to include postal and email addresses, telephone numbers, images of faces and logos, and so on. Since: 1.1 See Also: IdentityScope Signer Principal Serialized Form Constructor Summary Identity() Identity(String name) Identity(String name, IdentityScope scope) Modifier Constructor Description protected Deprecated, for removal: This API element is subject to removal in a future version. Constructor for serialization only. Deprecated, for removal: This API element is subject to removal in a future version. Constructs an identity with the specified name and no scope. Deprecated, for removal: This API element is subject to removal in a future version. Constructs an identity with the specified name and scope. Method Summary Modifier and Type Method Description void addCertificate(Certificate certificate) Deprecated, for removal: This API element is subject to removal in a future version. Adds a certificate for this identity. Certificate[] certificates() Deprecated, for removal: This API element is subject to removal in a future version. Returns a copy of all the certificates for this identity. final boolean equals(Object identity) Deprecated, for removal: This API element is subject to removal in a future version. Tests for equality between the specified object and this identity. String getInfo() Deprecated, for removal: This API element is subject to removal in a future version. Returns general information previously specified for this identity. final String getName() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's name. PublicKey getPublicKey() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's public key. final IdentityScope getScope() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's scope. int hashCode() Deprecated, for removal: This API element is subject to removal in a future version. Returns a hashcode for this identity. protected boolean identityEquals(Identity identity) Deprecated, for removal: This API element is subject to removal in a future version. Tests for equality between the specified identity and this identity. void removeCertificate(Certificate certificate) Deprecated, for removal: This API element is subject to removal in a future version. Removes a certificate from this identity. void setInfo(String info) Deprecated, for removal: This API element is subject to removal in a future version. Specifies a general information string for this identity. void setPublicKey(PublicKey key) Deprecated, for removal: This API element is subject to removal in a future version. Sets this identity's public key. String toString() Deprecated, for removal: This API element is subject to removal in a future version. Returns a short string describing this identity, telling its name and its scope (if any). String toString(boolean detailed) Deprecated, for removal: This API element is subject to removal in a future version. Returns a string representation of this identity, with optionally more details than that provided by the toString method without any arguments. Methods declared in class java.lang.Object clone, finalize, getClass, notify, notifyAll, wait, wait, wait Methods declared in interface java.security.Principal implies Constructor Details Identity protected Identity() Deprecated, for removal: This API element is subject to removal in a future version. Constructor for serialization only. Identity public Identity(String name, IdentityScope scope) throws KeyManagementException Deprecated, for removal: This API element is subject to removal in a future version. Constructs an identity with the specified name and scope. Parameters: name - the identity name. scope - the scope of the identity. Throws: KeyManagementException - if there is already an identity with the same name in the scope. Identity public Identity(String name) Deprecated, for removal: This API element is subject to removal in a future version. Constructs an identity with the specified name and no scope. Parameters: name - the identity name. Method Details getName public final String getName() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's name. Specified by: getName in interface Principal Returns: the name of this identity. getScope public final IdentityScope getScope() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's scope. Returns: the scope of this identity. getPublicKey public PublicKey getPublicKey() Deprecated, for removal: This API element is subject to removal in a future version. Returns this identity's public key. Returns: the public key for this identity. See Also: setPublicKey(java.security.PublicKey) setPublicKey public void setPublicKey(PublicKey key) throws KeyManagementException Deprecated, for removal: This API element is subject to removal in a future version. Sets this identity's public key. The old key and all of this identity's certificates are removed by this operation. First, if there is a security manager, its checkSecurityAccess method is called with "setIdentityPublicKey" as its argument to see if it's ok to set the public key. Parameters: key - the public key for this identity. Throws: KeyManagementException - if another identity in the identity's scope has the same public key, or if another exception occurs. SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow setting the public key. See Also: getPublicKey() SecurityManager.checkSecurityAccess(java.lang.String) setInfo public void setInfo(String info) Deprecated, for removal: This API element is subject to removal in a future version. Specifies a general information string for this identity. First, if there is a security manager, its checkSecurityAccess method is called with "setIdentityInfo" as its argument to see if it's ok to specify the information string. Parameters: info - the information string. Throws: SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow setting the information string. See Also: getInfo() SecurityManager.checkSecurityAccess(java.lang.String) getInfo public String getInfo() Deprecated, for removal: This API element is subject to removal in a future version. Returns general information previously specified for this identity. Returns: general information about this identity. See Also: setInfo(java.lang.String) addCertificate public void addCertificate(Certificate certificate) throws KeyManagementException Deprecated, for removal: This API element is subject to removal in a future version. Adds a certificate for this identity. If the identity has a public key, the public key in the certificate must be the same, and if the identity does not have a public key, the identity's public key is set to be that specified in the certificate. First, if there is a security manager, its checkSecurityAccess method is called with "addIdentityCertificate" as its argument to see if it's ok to add a certificate. Parameters: certificate - the certificate to be added. Throws: KeyManagementException - if the certificate is not valid, if the public key in the certificate being added conflicts with this identity's public key, or if another exception occurs. SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow adding a certificate. See Also: SecurityManager.checkSecurityAccess(java.lang.String) removeCertificate public void removeCertificate(Certificate certificate) throws KeyManagementException Deprecated, for removal: This API element is subject to removal in a future version. Removes a certificate from this identity. First, if there is a security manager, its checkSecurityAccess method is called with "removeIdentityCertificate" as its argument to see if it's ok to remove a certificate. Parameters: certificate - the certificate to be removed. Throws: KeyManagementException - if the certificate is missing, or if another exception occurs. SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow removing a certificate. See Also: SecurityManager.checkSecurityAccess(java.lang.String) certificates public Certificate[] certificates() Deprecated, for removal: This API element is subject to removal in a future version. Returns a copy of all the certificates for this identity. Returns: a copy of all the certificates for this identity. equals public final boolean equals(Object identity) Deprecated, for removal: This API element is subject to removal in a future version. Tests for equality between the specified object and this identity. This first tests to see if the entities actually refer to the same object, in which case it returns true. Next, it checks to see if the entities have the same name and the same scope. If they do, the method returns true. Otherwise, it calls identityEquals, which subclasses should override. Specified by: equals in interface Principal Overrides: equals in class Object Parameters: identity - the object to test for equality with this identity. Returns: true if the objects are considered equal, false otherwise. See Also: identityEquals(java.security.Identity) identityEquals protected boolean identityEquals(Identity identity) Deprecated, for removal: This API element is subject to removal in a future version. Tests for equality between the specified identity and this identity. This method should be overridden by subclasses to test for equality. The default behavior is to return true if the names and public keys are equal. Parameters: identity - the identity to test for equality with this identity. Returns: true if the identities are considered equal, false otherwise. See Also: equals(java.lang.Object) toString public String toString() Deprecated, for removal: This API element is subject to removal in a future version. Returns a short string describing this identity, telling its name and its scope (if any). First, if there is a security manager, its checkSecurityAccess method is called with "printIdentity" as its argument to see if it's ok to return the string. Specified by: toString in interface Principal Overrides: toString in class Object Returns: information about this identity, such as its name and the name of its scope (if any). Throws: SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow returning a string describing this identity. See Also: SecurityManager.checkSecurityAccess(java.lang.String) toString public String toString(boolean detailed) Deprecated, for removal: This API element is subject to removal in a future version. Returns a string representation of this identity, with optionally more details than that provided by the toString method without any arguments. First, if there is a security manager, its checkSecurityAccess method is called with "printIdentity" as its argument to see if it's ok to return the string. Parameters: detailed - whether or not to provide detailed information. Returns: information about this identity. If detailed is true, then this method returns more information than that provided by the toString method without any arguments. Throws: SecurityException - if a security manager exists and its checkSecurityAccess method doesn't allow returning a string describing this identity. See Also: toString() SecurityManager.checkSecurityAccess(java.lang.String) hashCode public int hashCode() Deprecated, for removal: This API element is subject to removal in a future version. Returns a hashcode for this identity. Specified by: hashCode in interface Principal Overrides: hashCode in class Object Returns: a hashcode for this identity. See Also: Object.equals(java.lang.Object) System.identityHashCode(java.lang.Object)