text
stringlengths 0
13M
|
---|
svn_repos_open (PECL svn >= 0.1.0)
svn_repos_open — Open a shared lock on a repository Description svn_repos_open(string $path): resource
WarningThis function is currently not documented; only its argument list is available.
Open a shared lock on a repository. Notes
WarningThis function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
|
[Groovy] Class JListElementsBinding
groovy.swing.binding.JListElementsBinding
All Implemented Interfaces and Traits:
ListDataListener, PropertyChangeListener
class JListElementsBinding
extends AbstractSyntheticBinding
Inherited fields
Fields inherited from class Fields class AbstractFullBinding converter, reverseConverter, sourceBinding, targetBinding, validator Properties Summary
Properties
Type Name and description
JList
boundList
Constructor Summary
Constructors
Constructor and description JListElementsBinding
(PropertyBinding propertyBinding, TargetBinding target)
Methods Summary
Methods
Type Params Return Type Name and description void
contentsChanged(ListDataEvent e)
void
intervalAdded(ListDataEvent e)
void
intervalRemoved(ListDataEvent e)
void
propertyChange(PropertyChangeEvent event)
protected void
syntheticBind()
protected void
syntheticUnbind()
Inherited Methods Summary
Inherited Methods
Methods inherited from class Name class AbstractSyntheticBinding bind, rebind, setSourceBinding, setTargetBinding, syntheticBind, syntheticUnbind, unbind class AbstractFullBinding getConverter, getReverseConverter, getSourceBinding, getTargetBinding, getValidator, reverseUpdate, setConverter, setReverseConverter, setSourceBinding, setTargetBinding, setValidator, update Property Detail
JList boundList
Constructor Detail
JListElementsBinding(PropertyBinding propertyBinding, TargetBinding target) Method Detail void contentsChanged(ListDataEvent e) void intervalAdded(ListDataEvent e) void intervalRemoved(ListDataEvent e) void propertyChange(PropertyChangeEvent event) protected void syntheticBind() protected void syntheticUnbind()
|
Job interface Job (View source) Methods string getJobId() Get the job identifier. array payload() Get the decoded body of the job. void fire() Fire the job. void release(int $delay = 0) Release the job back into the queue. bool isReleased() Determine if the job was released back into the queue. void delete() Delete the job from the queue. bool isDeleted() Determine if the job has been deleted. bool isDeletedOrReleased() Determine if the job has been deleted or released. int attempts() Get the number of times the job has been attempted. bool hasFailed() Determine if the job has been marked as a failure. void markAsFailed() Mark the job as "failed". void fail(Throwable|null $e = null) Delete the job, call the "failed" method, and raise the failed job event. int|null maxTries() Get the number of times to attempt a job. int|null timeout() Get the number of seconds the job can run. int|null timeoutAt() Get the timestamp indicating when the job should timeout. string getName() Get the name of the queued job class. string resolveName() Get the resolved name of the queued job class. string getConnectionName() Get the name of the connection the job belongs to. string getQueue() Get the name of the queue the job belongs to. string getRawBody() Get the raw body string for the job. Details string
getJobId()
Get the job identifier. Return Value string array
payload()
Get the decoded body of the job. Return Value array void
fire()
Fire the job. Return Value void void
release(int $delay = 0)
Release the job back into the queue. Accepts a delay specified in seconds. Parameters int $delay Return Value void bool
isReleased()
Determine if the job was released back into the queue. Return Value bool void
delete()
Delete the job from the queue. Return Value void bool
isDeleted()
Determine if the job has been deleted. Return Value bool bool
isDeletedOrReleased()
Determine if the job has been deleted or released. Return Value bool int
attempts()
Get the number of times the job has been attempted. Return Value int bool
hasFailed()
Determine if the job has been marked as a failure. Return Value bool void
markAsFailed()
Mark the job as "failed". Return Value void void
fail(Throwable|null $e = null)
Delete the job, call the "failed" method, and raise the failed job event. Parameters
Throwable|null $e Return Value void int|null
maxTries()
Get the number of times to attempt a job. Return Value int|null int|null
timeout()
Get the number of seconds the job can run. Return Value int|null int|null
timeoutAt()
Get the timestamp indicating when the job should timeout. Return Value int|null string
getName()
Get the name of the queued job class. Return Value string string
resolveName()
Get the resolved name of the queued job class. Resolves the name of "wrapped" jobs such as class-based handlers. Return Value string string
getConnectionName()
Get the name of the connection the job belongs to. Return Value string string
getQueue()
Get the name of the queue the job belongs to. Return Value string string
getRawBody()
Get the raw body string for the job. Return Value string
|
cisco.ucs.ucs_timezone – Configures timezone on Cisco UCS Manager Note This plugin is part of the cisco.ucs collection (version 1.6.0). To install it use: ansible-galaxy collection install cisco.ucs. To use it in a playbook, specify: cisco.ucs.ucs_timezone. New in version 2.7: of cisco.ucs Synopsis Requirements Parameters Examples Synopsis Configures timezone on Cisco UCS Manager. Requirements The below requirements are needed on the host that executes this module. ucsmsdk Parameters Parameter Choices/Defaults Comments admin_state string
Choices: disabled
enabled ← The admin_state setting The enabled admin_state indicates the timezone configuration is utilized by UCS Manager. The disabled admin_state indicates the timezone configuration is ignored by UCS Manager. description string Default:"" A user-defined description of the timezone. Enter up to 256 characters. You can use any characters or spaces except the following: ` (accent mark), (backslash), ^ (carat), " (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).
aliases: descr hostname string / required IP address or hostname of Cisco UCS Manager. Modules can be used with the UCS Platform Emulator https://cs.co/ucspe
password string / required Password for Cisco UCS Manager authentication. port integer Port number to be used during connection (by default uses 443 for https and 80 for http connection). proxy string If use_proxy is no, specfies proxy to be used for connection. e.g. 'http://proxy.xy.z:8080' state string
Choices: absent
present ← If absent, will unset timezone. If present, will set or update timezone. timezone string The timezone name. Time zone names are from the tz database
The timezone name is case sensitive. The timezone name can be between 0 and 510 alphanumeric characters. You cannot use spaces or any special characters other than "-" (hyphen), "_" (underscore), "/" (backslash). use_proxy boolean
Choices: no
yes ← If no, will not use the proxy as defined by system environment variable. use_ssl boolean
Choices: no
yes ← If no, an HTTP connection will be used instead of the default HTTPS connection. username string Default:"admin" Username for Cisco UCS Manager authentication. Examples - name: Configure Time Zone
cisco.ucs.ucs_timezone:
hostname: +1-661-668-2295
username: admin
password: password
state: present
admin_state: enabled
timezone: America/Los_Angeles
description: 'Time Zone for Los Angeles'
- name: Unconfigure Time Zone
cisco.ucs.ucs_timezone:
hostname: +1-661-668-2295
username: admin
password: password
state: absent
admin_state: disabled
Authors David Soper (@dsoper2) John McDonough (@movinalot) CiscoUcs (@CiscoUcs)
© 2012–2018 Michael DeHaan
|
salt.modules.monit Monit service module. This module will create a monit type service watcher. salt.modules.monit.configtest()
New in version 2016.3.0. Test monit configuration syntax CLI Example: salt '*' monit.configtest
salt.modules.monit.id_(reset=False)
New in version 2016.3.0. Return monit unique id. resetFalse
Reset current id and generate a new id when it's True. CLI Example: salt '*' monit.id [reset=True]
salt.modules.monit.monitor(name)
monitor service via monit CLI Example: salt '*' monit.monitor <service name>
salt.modules.monit.reload_()
New in version 2016.3.0. Reload monit configuration CLI Example: salt '*' monit.reload
salt.modules.monit.restart(name)
Restart service via monit CLI Example: salt '*' monit.restart <service name>
salt.modules.monit.start(name)
CLI Example: salt '*' monit.start <service name>
salt.modules.monit.status(svc_name='')
Display a process status from monit CLI Example: salt '*' monit.status
salt '*' monit.status <service name>
salt.modules.monit.stop(name)
Stops service via monit CLI Example: salt '*' monit.stop <service name>
salt.modules.monit.summary(svc_name='')
Display a summary from monit CLI Example: salt '*' monit.summary
salt '*' monit.summary <service name>
salt.modules.monit.unmonitor(name)
Unmonitor service via monit CLI Example: salt '*' monit.unmonitor <service name>
salt.modules.monit.validate()
New in version 2016.3.0. Check all services CLI Example: salt '*' monit.validate
salt.modules.monit.version()
New in version 2016.3.0. Return version from monit -V CLI Example: salt '*' monit.version
|
6.58.2 Alpha Built-in Functions These built-in functions are available for the Alpha family of processors, depending on the command-line switches used.
The following built-in functions are always available. They all generate the machine instruction that is part of the name.
long __builtin_alpha_implver (void)
long __builtin_alpha_rpcc (void)
long __builtin_alpha_amask (long)
long __builtin_alpha_cmpbge (long, long)
long __builtin_alpha_extbl (long, long)
long __builtin_alpha_extwl (long, long)
long __builtin_alpha_extll (long, long)
long __builtin_alpha_extql (long, long)
long __builtin_alpha_extwh (long, long)
long __builtin_alpha_extlh (long, long)
long __builtin_alpha_extqh (long, long)
long __builtin_alpha_insbl (long, long)
long __builtin_alpha_inswl (long, long)
long __builtin_alpha_insll (long, long)
long __builtin_alpha_insql (long, long)
long __builtin_alpha_inswh (long, long)
long __builtin_alpha_inslh (long, long)
long __builtin_alpha_insqh (long, long)
long __builtin_alpha_mskbl (long, long)
long __builtin_alpha_mskwl (long, long)
long __builtin_alpha_mskll (long, long)
long __builtin_alpha_mskql (long, long)
long __builtin_alpha_mskwh (long, long)
long __builtin_alpha_msklh (long, long)
long __builtin_alpha_mskqh (long, long)
long __builtin_alpha_umulh (long, long)
long __builtin_alpha_zap (long, long)
long __builtin_alpha_zapnot (long, long) The following built-in functions are always with -mmax or -mcpu=cpu where cpu is pca56 or later. They all generate the machine instruction that is part of the name.
long __builtin_alpha_pklb (long)
long __builtin_alpha_pkwb (long)
long __builtin_alpha_unpkbl (long)
long __builtin_alpha_unpkbw (long)
long __builtin_alpha_minub8 (long, long)
long __builtin_alpha_minsb8 (long, long)
long __builtin_alpha_minuw4 (long, long)
long __builtin_alpha_minsw4 (long, long)
long __builtin_alpha_maxub8 (long, long)
long __builtin_alpha_maxsb8 (long, long)
long __builtin_alpha_maxuw4 (long, long)
long __builtin_alpha_maxsw4 (long, long)
long __builtin_alpha_perr (long, long) The following built-in functions are always with -mcix or -mcpu=cpu where cpu is ev67 or later. They all generate the machine instruction that is part of the name.
long __builtin_alpha_cttz (long)
long __builtin_alpha_ctlz (long)
long __builtin_alpha_ctpop (long) The following built-in functions are available on systems that use the OSF/1 PALcode. Normally they invoke the rduniq and wruniq PAL calls, but when invoked with -mtls-kernel, they invoke rdval and wrval.
void *__builtin_thread_pointer (void)
void __builtin_set_thread_pointer (void *)
|
MailFake class MailFake implements Factory, Mailer, MailQueue (View source) Traits ReflectsClosures Properties protected string $currentMailer The mailer currently being used to send a message. protected array $mailables All of the mailables that have been sent. protected array $queuedMailables All of the mailables that have been queued. Methods array closureParameterTypes(Closure $closure) Get the class names / types of the parameters of the given Closure. from ReflectsClosures string firstClosureParameterType(Closure $closure) Get the class name of the first parameter of the given Closure. from ReflectsClosures void assertSent(string|Closure $mailable, callable|int|null $callback = null) Assert if a mailable was sent based on a truth-test callback. void assertSentTimes(string $mailable, int $times = 1) Assert if a mailable was sent a number of times. void assertNotSent(string $mailable, callable|null $callback = null) Determine if a mailable was not sent based on a truth-test callback. void assertNothingSent() Assert that no mailables were sent. void assertQueued(string|Closure $mailable, callable|int|null $callback = null) Assert if a mailable was queued based on a truth-test callback. void assertQueuedTimes(string $mailable, int $times = 1) Assert if a mailable was queued a number of times. void assertNotQueued(string $mailable, callable|null $callback = null) Determine if a mailable was not queued based on a truth-test callback. void assertNothingQueued() Assert that no mailables were queued. Collection sent(string $mailable, callable|null $callback = null) Get all of the mailables matching a truth-test callback. bool hasSent(string $mailable) Determine if the given mailable has been sent. Collection queued(string $mailable, callable|null $callback = null) Get all of the queued mailables matching a truth-test callback. bool hasQueued(string $mailable) Determine if the given mailable has been queued. Collection mailablesOf(string $type) Get all of the mailed mailables for a given type. Collection queuedMailablesOf(string $type) Get all of the mailed mailables for a given type. Mailer mailer(string|null $name = null) Get a mailer instance by name. PendingMail to(mixed $users) Begin the process of mailing a mailable class instance. PendingMail bcc(mixed $users) Begin the process of mailing a mailable class instance. void raw(string $text, mixed $callback) Send a new message with only a raw text part. void send(Mailable|string|array $view, array $data = [], Closure|string|null $callback = null) Send a new message using a view. mixed queue(Mailable|string|array $view, string|null $queue = null) Queue a new e-mail message for sending. mixed later(DateTimeInterface|DateInterval|int $delay, Mailable|string|array $view, string|null $queue = null) Queue a new e-mail message for sending after (n) seconds. array failures() Get the array of failed recipients. Details protected array
closureParameterTypes(Closure $closure)
Get the class names / types of the parameters of the given Closure. Parameters Closure $closure Return Value array Exceptions ReflectionException protected string
firstClosureParameterType(Closure $closure)
Get the class name of the first parameter of the given Closure. Parameters Closure $closure Return Value string Exceptions RuntimeException void
assertSent(string|Closure $mailable, callable|int|null $callback = null)
Assert if a mailable was sent based on a truth-test callback. Parameters string|Closure
$mailable callable|int|null $callback Return Value void protected void
assertSentTimes(string $mailable, int $times = 1)
Assert if a mailable was sent a number of times. Parameters string $mailable int $times Return Value void void
assertNotSent(string $mailable, callable|null $callback = null)
Determine if a mailable was not sent based on a truth-test callback. Parameters string $mailable callable|null $callback Return Value void void
assertNothingSent()
Assert that no mailables were sent. Return Value void void
assertQueued(string|Closure $mailable, callable|int|null $callback = null)
Assert if a mailable was queued based on a truth-test callback. Parameters string|Closure
$mailable callable|int|null $callback Return Value void protected void
assertQueuedTimes(string $mailable, int $times = 1)
Assert if a mailable was queued a number of times. Parameters string $mailable int $times Return Value void void
assertNotQueued(string $mailable, callable|null $callback = null)
Determine if a mailable was not queued based on a truth-test callback. Parameters string $mailable callable|null $callback Return Value void void
assertNothingQueued()
Assert that no mailables were queued. Return Value void Collection
sent(string $mailable, callable|null $callback = null)
Get all of the mailables matching a truth-test callback. Parameters string $mailable callable|null $callback Return Value Collection bool
hasSent(string $mailable)
Determine if the given mailable has been sent. Parameters string $mailable Return Value bool Collection
queued(string $mailable, callable|null $callback = null)
Get all of the queued mailables matching a truth-test callback. Parameters string $mailable callable|null $callback Return Value Collection bool
hasQueued(string $mailable)
Determine if the given mailable has been queued. Parameters string $mailable Return Value bool protected Collection
mailablesOf(string $type)
Get all of the mailed mailables for a given type. Parameters string $type Return Value Collection protected Collection
queuedMailablesOf(string $type)
Get all of the mailed mailables for a given type. Parameters string $type Return Value Collection Mailer
mailer(string|null $name = null)
Get a mailer instance by name. Parameters string|null $name Return Value Mailer PendingMail
to(mixed $users)
Begin the process of mailing a mailable class instance. Parameters mixed $users Return Value PendingMail PendingMail
bcc(mixed $users)
Begin the process of mailing a mailable class instance. Parameters mixed $users Return Value PendingMail void
raw(string $text, mixed $callback)
Send a new message with only a raw text part. Parameters string $text mixed $callback Return Value void void
send(Mailable|string|array $view, array $data = [], Closure|string|null $callback = null)
Send a new message using a view. Parameters
Mailable|string|array $view array $data
Closure|string|null $callback Return Value void mixed
queue(Mailable|string|array $view, string|null $queue = null)
Queue a new e-mail message for sending. Parameters
Mailable|string|array $view string|null $queue Return Value mixed mixed
later(DateTimeInterface|DateInterval|int $delay, Mailable|string|array $view, string|null $queue = null)
Queue a new e-mail message for sending after (n) seconds. Parameters
DateTimeInterface|DateInterval|int $delay
Mailable|string|array $view string|null $queue Return Value mixed array
failures()
Get the array of failed recipients. Return Value array
|
Enabling Vars Plugins Using Vars Plugins Plugin Lists
Vars Plugins Vars plugins inject additional variable data into Ansible runs that did not come from an inventory source, playbook, or command line. Playbook constructs like ‘host_vars’ and ‘group_vars’ work using vars plugins. Vars plugins were partially implemented in Ansible 2.0 and rewritten to be fully implemented starting with Ansible 2.4. The host_group_vars plugin shipped with Ansible enables reading variables from Host Variables and Group Variables. Enabling Vars Plugins You can activate a custom vars plugin by either dropping it into a vars_plugins directory adjacent to your play, inside a role, or by putting it in one of the directory sources configured in ansible.cfg. Using Vars Plugins Vars plugins are used automatically after they are enabled. Plugin Lists You can use ansible-doc -t vars -l to see the list of available plugins. Use ansible-doc -t vars <plugin name> to see specific plugin-specific documentation and examples. host_group_vars - In charge of loading group_vars and host_vars See also Action Plugins Ansible Action plugins Cache Plugins Ansible Cache plugins Callback Plugins Ansible callback plugins Connection Plugins Ansible connection plugins Inventory Plugins Ansible inventory plugins Shell Plugins Ansible Shell plugins Strategy Plugins Ansible Strategy plugins User Mailing List Have a question? Stop by the google group! irc.freenode.net #ansible IRC chat channel
© 2012–2018 Michael DeHaan
|
Conditionals In a playbook, you may want to execute different tasks, or have different goals, depending on the value of a fact (data about the remote system), a variable, or the result of a previous task. You may want the value of some variables to depend on the value of other variables. Or you may want to create additional groups of hosts based on whether the hosts match other criteria. You can do all of these things with conditionals. Ansible uses Jinja2 tests and filters in conditionals. Ansible supports all the standard tests and filters, and adds some unique ones as well. Note There are many options to control execution flow in Ansible. You can find more examples of supported conditionals at https://jinja.palletsprojects.com/en/master/templates/#comparisons.
Basic conditionals with when Conditionals based on ansible_facts Conditions based on registered variables Conditionals based on variables Using conditionals in loops Loading custom facts
Conditionals with re-use Conditionals with imports Conditionals with includes Conditionals with roles
Selecting variables, files, or templates based on facts Selecting variables files based on facts Selecting files and templates based on facts
Commonly-used facts ansible_facts[‘distribution’] ansible_facts[‘distribution_major_version’] ansible_facts[‘os_family’] Basic conditionals with when
The simplest conditional statement applies to a single task. Create the task, then add a when statement that applies a test. The when clause is a raw Jinja2 expression without double curly braces (see group_by – Create Ansible groups based on facts). When you run the task or playbook, Ansible evaluates the test for all hosts. On any host where the test passes (returns a value of True), Ansible runs that task. For example, if you are installing mysql on multiple machines, some of which have SELinux enabled, you might have a task to configure SELinux to allow mysql to run. You would only want that task to run on machines that have SELinux enabled: tasks:
- name: Configure SELinux to start mysql on any port
ansible.posix.seboolean:
name: mysql_connect_any
state: true
persistent: yes
when: ansible_selinux.status == "enabled"
# all variables can be used directly in conditionals without double curly braces
Conditionals based on ansible_facts Often you want to execute or skip a task based on facts. Facts are attributes of individual hosts, including IP address, operating system, the status of a filesystem, and many more. With conditionals based on facts: You can install a certain package only when the operating system is a particular version. You can skip configuring a firewall on hosts with internal IP addresses. You can perform cleanup tasks only when a filesystem is getting full. See Commonly-used facts for a list of facts that frequently appear in conditional statements. Not all facts exist for all hosts. For example, the ‘lsb_major_release’ fact used in an example below only exists when the lsb_release package is installed on the target host. To see what facts are available on your systems, add a debug task to your playbook: - name: Show facts available on the system
ansible.builtin.debug:
var: ansible_facts
Here is a sample conditional based on a fact: tasks:
- name: Shut down Debian flavored systems
ansible.builtin.command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
If you have multiple conditions, you can group them with parentheses: tasks:
- name: Shut down CentOS 6 and Debian 7 systems
ansible.builtin.command: /sbin/shutdown -t now
when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
(ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")
You can use logical operators to combine conditions. When you have multiple conditions that all need to be true (that is, a logical and), you can specify them as a list: tasks:
- name: Shut down CentOS 6 systems
ansible.builtin.command: /sbin/shutdown -t now
when:
- ansible_facts['distribution'] == "CentOS"
- ansible_facts['distribution_major_version'] == "6"
If a fact or variable is a string, and you need to run a mathematical comparison on it, use a filter to ensure that Ansible reads the value as an integer: tasks:
- ansible.builtin.shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release'] | int >= 6
Conditions based on registered variables Often in a playbook you want to execute or skip a task based on the outcome of an earlier task. For example, you might want to configure a service after it is upgraded by an earlier task. To create a conditional based on a registered variable: Register the outcome of the earlier task as a variable. Create a conditional test based on the registered variable. You create the name of the registered variable using the register keyword. A registered variable always contains the status of the task that created it as well as any output that task generated. You can use registered variables in templates and action lines as well as in conditional when statements. You can access the string contents of the registered variable using variable.stdout. For example: - name: Test play
hosts: all
tasks:
- name: Register a variable
ansible.builtin.shell: cat /etc/motd
register: motd_contents
- name: Use the variable in conditional statement
ansible.builtin.shell: echo "motd contains the word hi"
when: motd_contents.stdout.find('hi') != -1
You can use registered results in the loop of a task if the variable is a list. If the variable is not a list, you can convert it into a list, with either stdout_lines or with variable.stdout.split(). You can also split the lines by other fields: - name: Registered variable usage as a loop list
hosts: all
tasks:
- name: Retrieve the list of home directories
ansible.builtin.command: ls /home
register: home_dirs
- name: Add home dirs to the backup spooler
ansible.builtin.file:
path: /mnt/bkspool/{{ item }}
src: /home/{{ item }}
state: link
loop: "{{ home_dirs.stdout_lines }}"
# same as loop: "{{ home_dirs.stdout.split() }}"
The string content of a registered variable can be empty. If you want to run another task only on hosts where the stdout of your registered variable is empty, check the registered variable’s string contents for emptiness: - name: check registered variable for emptiness
hosts: all
tasks:
- name: List contents of directory
ansible.builtin.command: ls mydir
register: contents
- name: Check contents for emptiness
ansible.builtin.debug:
msg: "Directory is empty"
when: contents.stdout == ""
Ansible always registers something in a registered variable for every host, even on hosts where a task fails or Ansible skips a task because a condition is not met. To run a follow-up task on these hosts, query the registered variable for is skipped (not for “undefined” or “default”). See Registering variables for more information. Here are sample conditionals based on the success or failure of a task. Remember to ignore errors if you want Ansible to continue executing on a host when a failure occurs: tasks:
- name: Register a variable, ignore errors and continue
ansible.builtin.command: /bin/false
register: result
ignore_errors: true
- name: Run only if the task that registered the "result" variable fails
ansible.builtin.command: /bin/something
when: result is failed
- name: Run only if the task that registered the "result" variable succeeds
ansible.builtin.command: /bin/something_else
when: result is succeeded
- name: Run only if the task that registered the "result" variable is skipped
ansible.builtin.command: /bin/still/something_else
when: result is skipped
Note Older versions of Ansible used success and fail, but succeeded and failed use the correct tense. All of these options are now valid. Conditionals based on variables You can also create conditionals based on variables defined in the playbooks or inventory. Because conditionals require boolean input (a test must evaluate as True to trigger the condition), you must apply the | bool filter to non boolean variables, such as string variables with content like ‘yes’, ‘on’, ‘1’, or ‘true’. You can define variables like this: vars:
epic: true
monumental: "yes"
With the variables above, Ansible would run one of these tasks and skip the other: tasks:
- name: Run the command if "epic" or "monumental" is true
ansible.builtin.shell: echo "This certainly is epic!"
when: epic or monumental | bool
- name: Run the command if "epic" is false
ansible.builtin.shell: echo "This certainly isn't epic!"
when: not epic
If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example: tasks:
- name: Run the command if "foo" is defined
ansible.builtin.shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- name: Fail if "bar" is undefined
ansible.builtin.fail: msg="Bailing out. This play requires 'bar'"
when: bar is undefined
This is especially useful in combination with the conditional import of vars files (see below). As the examples show, you do not need to use {{ }} to use variables inside conditionals, as these are already implied. Using conditionals in loops If you combine a when statement with a loop, Ansible processes the condition separately for each item. This is by design, so you can execute the task on some items in the loop and skip it on other items. For example: tasks:
- name: Run with items greater than 5
ansible.builtin.command: echo {{ item }}
loop: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
If you need to skip the whole task when the loop variable is undefined, use the |default filter to provide an empty iterator. For example, when looping over a list: - name: Skip the whole task when a loop variable is undefined
ansible.builtin.command: echo {{ item }}
loop: "{{ mylist|default([]) }}"
when: item > 5
You can do the same thing when looping over a dict: - name: The same as above using a dict
ansible.builtin.command: echo {{ item.key }}
loop: "{{ query('dict', mydict|default({})) }}"
when: item.value > 5
Loading custom facts You can provide your own facts, as described in Should you develop a module?. To run them, just make a call to your own custom fact gathering module at the top of your list of tasks, and variables returned there will be accessible to future tasks: tasks:
- name: Gather site specific fact data
action: site_facts
- name: Use a custom fact
ansible.builtin.command: /usr/bin/thingy
when: my_custom_fact_just_retrieved_from_the_remote_system == '1234'
Conditionals with re-use You can use conditionals with re-usable tasks files, playbooks, or roles. Ansible executes these conditional statements differently for dynamic re-use (includes) and for static re-use (imports). See Re-using Ansible artifacts for more information on re-use in Ansible. Conditionals with imports When you add a conditional to an import statement, Ansible applies the condition to all tasks within the imported file. This behavior is the equivalent of Tag inheritance: adding tags to multiple tasks. Ansible applies the condition to every task, and evaluates each task separately. For example, you might have a playbook called main.yml and a tasks file called other_tasks.yml: # all tasks within an imported file inherit the condition from the import statement
# main.yml
- import_tasks: other_tasks.yml # note "import"
when: x is not defined
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
- name: Print a variable
ansible.builtin.debug:
var: x
Ansible expands this at execution time to the equivalent of: - name: Set a variable if not defined
ansible.builtin.set_fact:
x: foo
when: x is not defined
# this task sets a value for x
- name: Do the task if "x" is not defined
ansible.builin.debug:
var: x
when: x is not defined
# Ansible skips this task, because x is now defined
Thus if x is initially undefined, the debug task will be skipped. If this is not the behavior you want, use an include_* statement to apply a condition only to that statement itself. You can apply conditions to import_playbook as well as to the other import_* statements. When you use this approach, Ansible returns a ‘skipped’ message for every task on every host that does not match the criteria, creating repetitive output. In many cases the group_by module can be a more streamlined way to accomplish the same objective; see Handling OS and distro differences. Conditionals with includes When you use a conditional on an include_* statement, the condition is applied only to the include task itself and not to any other tasks within the included file(s). To contrast with the example used for conditionals on imports above, look at the same playbook and tasks file, but using an include instead of an import: # Includes let you re-use a file to define a variable when it is not already defined
# main.yml
- include_tasks: other_tasks.yml
when: x is not defined
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
- name: Print a variable
ansible.builtin.debug:
var: x
Ansible expands this at execution time to the equivalent of: # main.yml
- include_tasks: other_tasks.yml
when: x is not defined
# if condition is met, Ansible includes other_tasks.yml
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
# no condition applied to this task, Ansible sets the value of x to foo
- name: Print a variable
ansible.builtin.debug:
var: x
# no condition applied to this task, Ansible prints the debug statement
By using include_tasks instead of import_tasks, both tasks from other_tasks.yml will be executed as expected. For more information on the differences between include v import see Re-using Ansible artifacts. Conditionals with roles There are three ways to apply conditions to roles: Add the same condition or conditions to all tasks in the role by placing your when statement under the roles keyword. See the example in this section. Add the same condition or conditions to all tasks in the role by placing your when statement on a static import_role in your playbook. Add a condition or conditions to individual tasks or blocks within the role itself. This is the only approach that allows you to select or skip some tasks within the role based on your when statement. To select or skip tasks within the role, you must have conditions set on individual tasks or blocks, use the dynamic include_role in your playbook, and add the condition or conditions to the include. When you use this approach, Ansible applies the condition to the include itself plus any tasks in the role that also have that when statement. When you incorporate a role in your playbook statically with the roles keyword, Ansible adds the conditions you define to all the tasks in the role. For example: - hosts: webservers
roles:
- role: debian_stock_config
when: ansible_facts['os_family'] == 'Debian'
Selecting variables, files, or templates based on facts Sometimes the facts about a host determine the values you want to use for certain variables or even the file or template you want to select for that host. For example, the names of packages are different on CentOS and on Debian. The configuration files for common services are also different on different OS flavors and versions. To load different variables file, templates, or other files based on a fact about the hosts: name your vars files, templates, or files to match the Ansible fact that differentiates them select the correct vars file, template, or file for each host with a variable based on that Ansible fact Ansible separates variables from tasks, keeping your playbooks from turning into arbitrary code with nested conditionals. This approach results in more streamlined and auditable configuration rules because there are fewer decision points to track. Selecting variables files based on facts You can create a playbook that works on multiple platforms and OS versions with a minimum of syntax by placing your variable values in vars files and conditionally importing them. If you want to install Apache on some CentOS and some Debian servers, create variables files with YAML keys and values. For example: ---
# for vars/RedHat.yml
apache: httpd
somethingelse: 42
Then import those variables files based on the facts you gather on the hosts in your playbook: ---
- hosts: webservers
remote_user: root
vars_files:
- "vars/common.yml"
- [ "vars/{{ ansible_facts['os_family'] }}.yml", "vars/os_defaults.yml" ]
tasks:
- name: Make sure apache is started
ansible.builtin.service:
name: '{{ apache }}'
state: started
Ansible gathers facts on the hosts in the webservers group, then interpolates the variable “ansible_facts[‘os_family’]” into a list of filenames. If you have hosts with Red Hat operating systems (CentOS, for example), Ansible looks for ‘vars/RedHat.yml’. If that file does not exist, Ansible attempts to load ‘vars/os_defaults.yml’. For Debian hosts, Ansible first looks for ‘vars/Debian.yml’, before falling back on ‘vars/os_defaults.yml’. If no files in the list are found, Ansible raises an error. Selecting files and templates based on facts You can use the same approach when different OS flavors or versions require different configuration files or templates. Select the appropriate file or template based on the variables assigned to each host. This approach is often much cleaner than putting a lot of conditionals into a single template to cover multiple OS or package versions. For example, you can template out a configuration file that is very different between, say, CentOS and Debian: - name: Template a file
ansible.builtin.template:
src: "{{ item }}"
dest: /etc/myapp/foo.conf
loop: "{{ query('first_found', { 'files': myfiles, 'paths': mypaths}) }}"
vars:
myfiles:
- "{{ ansible_facts['distribution'] }}.conf"
- default.conf
mypaths: ['search_location_one/somedir/', '/opt/other_location/somedir/']
Commonly-used facts The following Ansible facts are frequently used in conditionals. ansible_facts[‘distribution’] Possible values (sample, not complete list): Alpine
Altlinux
Amazon
Archlinux
ClearLinux
Coreos
CentOS
Debian
Fedora
Gentoo
Mandriva
NA
OpenWrt
OracleLinux
RedHat
Slackware
SLES
SMGL
SUSE
Ubuntu
VMwareESX
ansible_facts[‘distribution_major_version’] The major version of the operating system. For example, the value is 16 for Ubuntu 16.04. ansible_facts[‘os_family’] Possible values (sample, not complete list): AIX
Alpine
Altlinux
Archlinux
Darwin
Debian
FreeBSD
Gentoo
HP-UX
Mandrake
RedHat
SGML
Slackware
Solaris
Suse
Windows
See also Working with playbooks
An introduction to playbooks Roles
Playbook organization by roles Tips and tricks
Tips and tricks for playbooks Using Variables
All about variables User Mailing List
Have a question? Stop by the google group! irc.freenode.net
#ansible IRC chat channel
© 2012–2018 Michael DeHaan
|
RotationAnimation QML Type Animates changes in rotation values More...
Import Statement:
import QtQuick 2.7
Inherits:
PropertyAnimation
List of all members, including inherited members Properties
direction : enumeration
from : real
to : real Detailed Description RotationAnimation is a specialized PropertyAnimation that gives control over the direction of rotation during an animation. By default, it rotates in the direction of the numerical change; a rotation from 0 to 240 will rotate 240 degrees clockwise, while a rotation from 240 to 0 will rotate 240 degrees counterclockwise. The direction property can be set to specify the direction in which the rotation should occur. In the following example we use RotationAnimation to animate the rotation between states via the shortest path: import QtQuick 2.0
Item {
width: 300; height: 300
Rectangle {
id: rect
width: 150; height: 100; anchors.centerIn: parent
color: "red"
antialiasing: true
states: State {
name: "rotated"
PropertyChanges { target: rect; rotation: 180 }
}
transitions: Transition {
RotationAnimation { duration: 1000; direction: RotationAnimation.Counterclockwise }
}
}
MouseArea { anchors.fill: parent; onClicked: rect.state = "rotated" }
} Notice the RotationAnimation did not need to set a target value. As a convenience, when used in a transition, RotationAnimation will rotate all properties named "rotation" or "angle". You can override this by providing your own properties via properties or property. Also, note the Rectangle will be rotated around its default transformOrigin (which is Item.Center). To use a different transform origin, set the origin in the PropertyChanges object and apply the change at the start of the animation using PropertyAction. See the PropertyAction documentation for more details. Like any other animation type, a RotationAnimation can be applied in a number of ways, including transitions, behaviors and property value sources. The Animation and Transitions in Qt Quick documentation shows a variety of methods for creating animations. See also Animation and Transitions in Qt Quick and Qt Quick Examples - Animation. Property Documentation direction : enumeration
This property holds the direction of the rotation. Possible values are:
RotationAnimation.Numerical (default) - Rotate by linearly interpolating between the two numbers. A rotation from 10 to 350 will rotate 340 degrees clockwise.
RotationAnimation.Clockwise - Rotate clockwise between the two values
RotationAnimation.Counterclockwise - Rotate counterclockwise between the two values
RotationAnimation.Shortest - Rotate in the direction that produces the shortest animation path. A rotation from 10 to 350 will rotate 20 degrees counterclockwise. from : real
This property holds the starting value for the animation. For example, the following animation is not applied until the angle value has reached 100: Item {
states: [
// ...
]
transition: Transition {
RotationAnimation { properties: "angle"; from: 100; duration: 2000 }
}
} If the RotationAnimation is defined within a Transition or Behavior, this value defaults to the value defined in the starting state of the Transition, or the current value of the property at the moment the Behavior is triggered. See also Animation and Transitions in Qt Quick. to : real
This property holds the end value for the animation.. If the RotationAnimation is defined within a Transition or Behavior, this value defaults to the value defined in the end state of the Transition, or the value of the property change that triggered the Behavior. See also Animation and Transitions in Qt Quick.
|
Illuminate\Foundation\Exceptions Classes Handler WhoopsHandler
|
GtkCellRendererProgress
GtkCellRendererProgress — Renders numbers as progress bars Functions GtkCellRenderer * gtk_cell_renderer_progress_new () Properties gboolean inverted Read / Write gint pulse Read / Write gchar * text Read / Write gfloat text-xalign Read / Write gfloat text-yalign Read / Write gint value Read / Write Types and Values struct GtkCellRendererProgress Object Hierarchy GObject
╰── GInitiallyUnowned
╰── GtkCellRenderer
╰── GtkCellRendererProgress
Implemented Interfaces GtkCellRendererProgress implements GtkOrientable. Includes #include <gtk/gtk.h>
Description GtkCellRendererProgress renders a numeric value as a progress par in a cell. Additionally, it can display a text on top of the progress bar. The GtkCellRendererProgress cell renderer was added in GTK+ 2.6. Functions gtk_cell_renderer_progress_new () GtkCellRenderer *
gtk_cell_renderer_progress_new (void); Creates a new GtkCellRendererProgress. Returns the new cell renderer Since: 2.6 Types and Values struct GtkCellRendererProgress struct GtkCellRendererProgress; Property Details The “inverted” property “inverted” gboolean Invert the direction in which the progress bar grows. Flags: Read / Write Default value: FALSE The “pulse” property “pulse” gint Setting this to a non-negative value causes the cell renderer to enter "activity mode", where a block bounces back and forth to indicate that some progress is made, without specifying exactly how much. Each increment of the property causes the block to move by a little bit. To indicate that the activity has not started yet, set the property to zero. To indicate completion, set the property to G_MAXINT. Flags: Read / Write Allowed values: >= -1 Default value: -1 Since: 2.12 The “text” property “text” gchar * The "text" property determines the label which will be drawn over the progress bar. Setting this property to NULL causes the default label to be displayed. Setting this property to an empty string causes no label to be displayed. Flags: Read / Write Default value: NULL Since: 2.6 The “text-xalign” property “text-xalign” gfloat The "text-xalign" property controls the horizontal alignment of the text in the progress bar. Valid values range from 0 (left) to 1 (right). Reserved for RTL layouts. Flags: Read / Write Allowed values: [0,1] Default value: 0.5 Since: 2.12 The “text-yalign” property “text-yalign” gfloat The "text-yalign" property controls the vertical alignment of the text in the progress bar. Valid values range from 0 (top) to 1 (bottom). Flags: Read / Write Allowed values: [0,1] Default value: 0.5 Since: 2.12 The “value” property “value” gint The "value" property determines the percentage to which the progress bar will be "filled in". Flags: Read / Write Allowed values: [0,100] Default value: 0 Since: 2.6
|
statsmodels.stats.stattools.robust_skewness
statsmodels.stats.stattools.robust_skewness(y, axis=0) [source]
Calculates the four skewness measures in Kim & White
Parameters:
y (array-like) –
axis (int or None, optional) – Axis along which the skewness measures are computed. If None, the entire array is used.
Returns:
sk1 (ndarray) – The standard skewness estimator.
sk2 (ndarray) – Skewness estimator based on quartiles.
sk3 (ndarray) – Skewness estimator based on mean-median difference, standardized by absolute deviation.
sk4 (ndarray) – Skewness estimator based on mean-median difference, standardized by standard deviation. Notes The robust skewness measures are defined \[SK_{2}=\frac{\left(q_{.75}-q_{.5}\right) -\left(q_{.5}-q_{.25}\right)}{q_{.75}-q_{.25}}\] \[SK_{3}=\frac{\mu-\hat{q}_{0.5}} {\hat{E}\left[\left|y-\hat{\mu}\right|\right]}\] \[SK_{4}=\frac{\mu-\hat{q}_{0.5}}{\hat{\sigma}}\]
[*]
Tae-Hwan Kim and Halbert White, “On more robust estimation of skewness and kurtosis,” Finance Research Letters, vol. 1, pp. 56-73, March 2004.
© 2009–2012 Statsmodels Developers© 2006–2008 Scipy Developers
|
WebView QML Type A component for displaying web content More...
Import Statement:
import QtWebView 1.1
List of all members, including inherited members Properties
canGoBack : bool
canGoForward : bool
loadProgress : int
loading : bool
title : string
url : url Signals
loadingChanged(WebViewLoadRequest loadRequest) Methods void goBack() void goForward() void loadHtml(string html, url baseUrl) void reload() void runJavaScript(string script, variant callback) void stop() Detailed Description WebView is a component for displaying web content which is implemented using native APIs on the platforms where this is available, thus it does not necessarily require including a full web browser stack as part of the application. To make the Qt WebView module function correctly across all platforms, it is necessary to call QtWebView8b7c:f320:99b9:690f:4595:cd17:293a:c069initialize() right after creating the QGuiApplication instance. Note: Due to platform limitations overlapping the WebView and other QML components is not supported. Property Documentation [read-only] canGoBack : bool
Holds true if it's currently possible to navigate back in the web history. [read-only] canGoForward : bool
Holds true if it's currently possible to navigate forward in the web history. [read-only] loadProgress : int
The current load progress of the web content, represented as an integer between 0 and 100. [read-only] loading : bool
Holds true if the WebView is currently in the process of loading new content, false otherwise. See also loadingChanged(). [read-only] title : string
The title of the currently loaded web page. url : url
The URL of currently loaded web page. Changing this will trigger loading new content. The URL is used as-is. URLs that originate from user input should be parsed with QUrl8b7c:f320:99b9:690f:4595:cd17:293a:c069romUserInput(). Note: The WebView does not support loading content through the Qt Resource system. Signal Documentation loadingChanged(WebViewLoadRequest loadRequest)
This signal is emitted when the state of loading the web content changes. By handling this signal it's possible, for example, to react to page load errors. The loadRequest parameter holds the url and status of the request, as well as an errorString containing an error message for a failed request. See also WebViewLoadRequest. Method Documentation void goBack()
Navigates back in the web history. void goForward()
Navigates forward in the web history. void loadHtml(string html, url baseUrl)
Loads the specified html content to the web view. This method offers a lower-level alternative to the url property, which references HTML pages via URL. External objects such as stylesheets or images referenced in the HTML document should be located relative to baseUrl. For example, if html is retrieved from http://www.example.com/documents/overview.html, which is the base URL, then an image referenced with the relative url, diagram.png, should be at http://www.example.com/documents/diagram.png. Note: The WebView does not support loading content through the Qt Resource system.
See also url. void reload()
Reloads the current url. void runJavaScript(string script, variant callback)
Runs the specified JavaScript. In case a callback function is provided, it will be invoked after the script finished running. runJavaScript("document.title", function(result) { console.log(result); }); void stop()
Stops loading the current url.
|
QQmlEngine Class The QQmlEngine class provides an environment for instantiating QML components. More...
Header:
#include <QQmlEngine>
qmake:
QT += qml
Since:
Qt 5.0
Inherits:
QJSEngine
Inherited By:
QQmlApplicationEngine
List of all members, including inherited members Public Types
enum
ObjectOwnership { CppOwnership, JavaScriptOwnership }
Properties
offlineStoragePath : QString 1 property inherited from QObject
Public Functions
QQmlEngine(QObject *parent = Q_NULLPTR)
virtual
~QQmlEngine()
void
addImageProvider(const QString &providerId, QQmlImageProviderBase *provider)
void
addImportPath(const QString &path)
void
addPluginPath(const QString &path)
QUrl
baseUrl() const
void
clearComponentCache()
QQmlImageProviderBase *
imageProvider(const QString &providerId) const
QStringList
importPathList() const
bool
importPlugin(const QString &filePath, const QString &uri, QList<QQmlError> *errors)
QQmlIncubationController *
incubationController() const
QNetworkAccessManager *
networkAccessManager() const
QQmlNetworkAccessManagerFactory *
networkAccessManagerFactory() const
QString
offlineStorageDatabaseFilePath(const QString &databaseName) const
QString
offlineStoragePath() const
bool
outputWarningsToStandardError() const
QStringList
pluginPathList() const
void
removeImageProvider(const QString &providerId)
QQmlContext *
rootContext() const
void
setBaseUrl(const QUrl &url)
void
setImportPathList(const QStringList &paths)
void
setIncubationController(QQmlIncubationController *controller)
void
setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)
void
setOfflineStoragePath(const QString &dir)
void
setOutputWarningsToStandardError(bool enabled)
void
setPluginPathList(const QStringList &paths)
void
trimComponentCache()
11 public functions inherited from QJSEngine
32 public functions inherited from QObject
Signals
void
exit(int retCode)
void
quit()
void
warnings(const QList<QQmlError> &warnings)
2 signals inherited from QObject
Static Public Members
QQmlContext *
contextForObject(const QObject *object)
ObjectOwnership
objectOwnership(QObject *object)
void
setContextForObject(QObject *object, QQmlContext *context)
void
setObjectOwnership(QObject *object, ObjectOwnership ownership)
11 static public members inherited from QObject
Reimplemented Protected Functions
virtual bool
event(QEvent *e) override
9 protected functions inherited from QObject
Related Non-Members
QObject *
qmlAttachedPropertiesObject(const QObject *attachee, bool create = true)
void
qmlClearTypeRegistrations()
QQmlContext *
qmlContext(const QObject *object)
QQmlInfo
qmlDebug(const QObject *object)
QQmlEngine *
qmlEngine(const QObject *object)
QQmlInfo
qmlInfo(const QObject *object)
bool
qmlProtectModule(const char *uri, int majVersion)
int
qmlRegisterExtendedType(const char *uri, int versionMajor, int versionMinor, const char *qmlName)
int
qmlRegisterExtendedUncreatableType(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &reason)
int
qmlRegisterInterface(const char *typeName)
void
qmlRegisterModule(const char *uri, int versionMajor, int versionMinor)
int
qmlRegisterRevision(const char *uri, int versionMajor, int versionMinor)
int
qmlRegisterSingletonType(const char *uri, int versionMajor, int versionMinor, const char *typeName, QJSValue(* ) ( QQmlEngine *, QJSEngine * ) callback)
int
qmlRegisterSingletonType(const char *uri, int versionMajor, int versionMinor, const char *typeName, QObject *(* ) ( QQmlEngine *, QJSEngine * ) callback)
int
qmlRegisterSingletonType(const QUrl &url, const char *uri, int versionMajor, int versionMinor, const char *qmlName)
int
qmlRegisterType()
int
qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName)
int
qmlRegisterType(const QUrl &url, const char *uri, int versionMajor, int versionMinor, const char *qmlName)
int
qmlRegisterTypeNotAvailable(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &message)
int
qmlRegisterUncreatableMetaObject(const QMetaObject &staticMetaObject, const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &reason)
int
qmlRegisterUncreatableType(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &message)
QQmlInfo
qmlWarning(const QObject *object)
Macros
QML_DECLARE_TYPE()
QML_DECLARE_TYPEINFO(Type, Flags)
Additional Inherited Members 1 public slot inherited from QObject
9 protected functions inherited from QObject
Detailed Description The QQmlEngine class provides an environment for instantiating QML components. Each QML component is instantiated in a QQmlContext. QQmlContext's are essential for passing data to QML components. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QQmlEngine. Prior to creating any QML components, an application must have created a QQmlEngine to gain access to a QML context. The following example shows how to create a simple Text item. QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: \"Hello world!\" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());
//add item to view, etc
... In this case, the Text item will be created in the engine's root context. Note that the Qt Quick 1 version is called QDeclarativeEngine. See also QQmlComponent, QQmlContext, and QML Global Object. Member Type Documentation
enum QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069ObjectOwnership
ObjectOwnership controls whether or not QML automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine. The two ownership options are:
Constant
Value
Description
QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069CppOwnership
0
The object is owned by C++ code and QML will never delete it. The JavaScript destroy() method cannot be used on these objects. This option is similar to QScriptEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069QtOwnership.
QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069JavaScriptOwnership
1
The object is owned by JavaScript. When the object is returned to QML as the return value of a method call, QML will track it and delete it if there are no remaining JavaScript references to it and it has no QObject8b7c:f320:99b9:690f:4595:cd17:293a:c069parent(). An object tracked by one QQmlEngine will be deleted during that QQmlEngine's destructor. Thus, JavaScript references between objects with JavaScriptOwnership from two different engines will not be valid if one of these engines is deleted. This option is similar to QScriptEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069ScriptOwnership.
Generally an application doesn't need to set an object's ownership explicitly. QML uses a heuristic to set the default ownership. By default, an object that is created by QML has JavaScriptOwnership. The exception to this are the root objects created by calling QQmlComponent8b7c:f320:99b9:690f:4595:cd17:293a:c069reate() or QQmlComponent8b7c:f320:99b9:690f:4595:cd17:293a:c069ginCreate(), which have CppOwnership by default. The ownership of these root-level objects is considered to have been transferred to the C++ caller. Objects not-created by QML have CppOwnership by default. The exception to this are objects returned from C++ method calls; their ownership will be set to JavaScriptOwnership. This applies only to explicit invocations of Q_INVOKABLE methods or slots, but not to property getter invocations. Calling setObjectOwnership() overrides the default ownership heuristic used by QML. Property Documentation
offlineStoragePath : QString
This property holds the directory for storing offline user data Returns the directory where SQL and other offline storage is placed. The SQL databases created with openDatabase() are stored here. The default is QML/OfflineStorage in the platform-standard user application data directory. Note that the path may not currently exist on the filesystem, so callers wanting to create new files at this location should create it first - see QDir8b7c:f320:99b9:690f:4595:cd17:293a:c069mkpath(). Access functions:
QString
offlineStoragePath() const
void
setOfflineStoragePath(const QString &dir)
Member Function Documentation
QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069QQmlEngine(QObject *parent = Q_NULLPTR) Create a new QQmlEngine with the given parent.
[virtual] QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069~QQmlEngine() Destroys the QQmlEngine. Any QQmlContext's created on this engine will be invalidated, but not destroyed (unless they are parented to the QQmlEngine object). See QJSEngine docs for details on cleaning up the JS engine.
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069addImageProvider(const QString &providerId, QQmlImageProviderBase *provider) Sets the provider to use for images requested via the image: url scheme, with host providerId. The QQmlEngine takes ownership of provider. Image providers enable support for pixmap and threaded image requests. See the QQuickImageProvider documentation for details on implementing and using image providers. All required image providers should be added to the engine before any QML sources files are loaded. See also removeImageProvider(), QQuickImageProvider, and QQmlImageProviderBase.
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069addImportPath(const QString &path) Adds path as a directory where the engine searches for installed modules in a URL-based directory structure. The path may be a local filesystem directory, a Qt Resource path (:/imports), a Qt Resource url (qrc:/imports) or a URL. The path will be converted into canonical form before it is added to the import path list. The newly added path will be first in the importPathList(). See also setImportPathList() and QML Modules.
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069addPluginPath(const QString &path) Adds path as a directory where the engine searches for native plugins for imported modules (referenced in the qmldir file). By default, the list contains only ., i.e. the engine searches in the directory of the qmldir file itself. The newly added path will be first in the pluginPathList(). See also setPluginPathList().
QUrl QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069baseUrl() const Return the base URL for this engine. The base URL is only used to resolve components when a relative URL is passed to the QQmlComponent constructor. If a base URL has not been explicitly set, this method returns the application's current working directory. See also setBaseUrl().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069clearComponentCache() Clears the engine's internal component cache. This function causes the property metadata of all components previously loaded by the engine to be destroyed. All previously loaded components and the property bindings for all extant objects created from those components will cease to function. This function returns the engine to a state where it does not contain any loaded component data. This may be useful in order to reload a smaller subset of the previous component set, or to load a new version of a previously loaded component. Once the component cache has been cleared, components must be loaded before any new objects can be created. See also trimComponentCache().
[static] QQmlContext *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069contextForObject(const QObject *object) Returns the QQmlContext for the object, or 0 if no context has been set. When the QQmlEngine instantiates a QObject, the context is set automatically. See also setContextForObject(), qmlContext(), and qmlEngine().
[override virtual protected] bool QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069event(QEvent *e) Reimplemented from QObject8b7c:f320:99b9:690f:4595:cd17:293a:c069vent().
[signal] void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069exit(int retCode) This signal is emitted when the QML loaded by the engine would like to exit from the event loop with the specified return code retCode. This function was introduced in Qt 5.8. See also quit().
QQmlImageProviderBase *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069imageProvider(const QString &providerId) const Returns the image provider set for providerId. Returns the provider if it was found; otherwise returns 0. See also QQuickImageProvider.
QStringList QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069importPathList() const Returns the list of directories where the engine searches for installed modules in a URL-based directory structure. For example, if /opt/MyApp/lib/imports is in the path, then QML that imports com.mycompany.Feature will cause the QQmlEngine to look in /opt/MyApp/lib/imports/com/mycompany/Feature/ for the components provided by that module. A qmldir file is required for defining the type version mapping and possibly QML extensions plugins. By default, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo. See also addImportPath() and setImportPathList().
bool QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069importPlugin(const QString &filePath, const QString &uri, QList<QQmlError> *errors) Imports the plugin named filePath with the uri provided. Returns true if the plugin was successfully imported; otherwise returns false. On failure and if non-null, the errors list will have any errors which occurred prepended to it. The plugin has to be a Qt plugin which implements the QQmlExtensionPlugin interface.
QQmlIncubationController *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069incubationController() const Returns the currently set incubation controller, or 0 if no controller has been set. See also setIncubationController().
QNetworkAccessManager *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069networkAccessManager() const Returns a common QNetworkAccessManager which can be used by any QML type instantiated by this engine. If a QQmlNetworkAccessManagerFactory has been set and a QNetworkAccessManager has not yet been created, the QQmlNetworkAccessManagerFactory will be used to create the QNetworkAccessManager; otherwise the returned QNetworkAccessManager will have no proxy or cache set. See also setNetworkAccessManagerFactory().
QQmlNetworkAccessManagerFactory *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069networkAccessManagerFactory() const Returns the current QQmlNetworkAccessManagerFactory. See also setNetworkAccessManagerFactory().
[static] ObjectOwnership QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069objectOwnership(QObject *object) Returns the ownership of object. See also setObjectOwnership().
QString QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069offlineStorageDatabaseFilePath(const QString &databaseName) const Returns the file path where a Local Storage database with the identifier databaseName is (or would be) located. This function was introduced in Qt 5.9. See also LocalStorage.openDatabaseSync().
bool QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069outputWarningsToStandardError() const Returns true if warning messages will be output to stderr in addition to being emitted by the warnings() signal, otherwise false. The default value is true. See also setOutputWarningsToStandardError().
QStringList QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069pluginPathList() const Returns the list of directories where the engine searches for native plugins for imported modules (referenced in the qmldir file). By default, the list contains only ., i.e. the engine searches in the directory of the qmldir file itself. See also addPluginPath() and setPluginPathList().
[signal] void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069quit() This signal is emitted when the QML loaded by the engine would like to quit. See also exit().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069removeImageProvider(const QString &providerId) Removes the image provider for providerId. See also addImageProvider() and QQuickImageProvider.
QQmlContext *QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069rootContext() const Returns the engine's root context. The root context is automatically created by the QQmlEngine. Data that should be available to all QML component instances instantiated by the engine should be put in the root context. Additional data that should only be available to a subset of component instances should be added to sub-contexts parented to the root context.
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setBaseUrl(const QUrl &url) Set the base URL for this engine to url. See also baseUrl().
[static] void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setContextForObject(QObject *object, QQmlContext *context) Sets the QQmlContext for the object to context. If the object already has a context, a warning is output, but the context is not changed. When the QQmlEngine instantiates a QObject, the context is set automatically. See also contextForObject().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setImportPathList(const QStringList &paths) Sets paths as the list of directories where the engine searches for installed modules in a URL-based directory structure. By default, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo. See also importPathList() and addImportPath().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setIncubationController(QQmlIncubationController *controller) Sets the engine's incubation controller. The engine can only have one active controller and it does not take ownership of it. See also incubationController().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory) Sets the factory to use for creating QNetworkAccessManager(s). QNetworkAccessManager is used for all network access by QML. By implementing a factory it is possible to create custom QNetworkAccessManager with specialized caching, proxy and cookie support. The factory must be set before executing the engine. See also networkAccessManagerFactory().
[static] void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setObjectOwnership(QObject *object, ObjectOwnership ownership) Sets the ownership of object. See also objectOwnership().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setOutputWarningsToStandardError(bool enabled) Set whether warning messages will be output to stderr to enabled. If enabled is true, any warning messages generated by QML will be output to stderr and emitted by the warnings() signal. If enabled is false, only the warnings() signal will be emitted. This allows applications to handle warning output themselves. The default value is true. See also outputWarningsToStandardError().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069setPluginPathList(const QStringList &paths) Sets the list of directories where the engine searches for native plugins for imported modules (referenced in the qmldir file) to paths. By default, the list contains only ., i.e. the engine searches in the directory of the qmldir file itself. See also pluginPathList() and addPluginPath().
void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069trimComponentCache() Trims the engine's internal component cache. This function causes the property metadata of any loaded components which are not currently in use to be destroyed. A component is considered to be in use if there are any extant instances of the component itself, any instances of other components that use the component, or any objects instantiated by any of those components. See also clearComponentCache().
[signal] void QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069warnings(const QList<QQmlError> &warnings) This signal is emitted when warnings messages are generated by QML. Related Non-Members
QObject *qmlAttachedPropertiesObject(const QObject *attachee, bool create = true) The form of this template function is: template<typename T> QObject *qmlAttachedPropertiesObject(const QObject *attachee, bool create = true) This returns the attached object instance that has been attached to the specified attachee by the attaching type T. If create is true and type T is a valid attaching type, this creates and returns a new attached object instance. Returns 0 if type T is not a valid attaching type, or if create is false and no attachment object instance has previously been created for attachee. See also Providing Attached Properties.
void qmlClearTypeRegistrations() Clears all stored type registrations, such as those produced with qmlRegisterType(). Do not call this function while a QQmlEngine exists or behavior will be undefined. Any existing QQmlEngines must be deleted before calling this function. This function only affects the application global cache. Delete the QQmlEngine to clear all cached data relating to that engine.
QQmlContext *qmlContext(const QObject *object) Returns the QQmlContext associated with object, if any. This is equivalent to QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069contextForObject(object). Note: Add #include <QtQml> to use this function.
See also contextForObject() and qmlEngine().
QQmlInfo QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlDebug(const QObject *object) Prints debug messages that include the file and line number for the specified QML object. When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated. To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead. For example, qmlDebug(object) << "Internal state: 42"; prints QML MyCustomType (unknown location): Internal state: 42 This function was introduced in Qt 5.9. See also QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlInfo and QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlWarning.
QQmlEngine *qmlEngine(const QObject *object) Returns the QQmlEngine associated with object, if any. This is equivalent to QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069contextForObject(object)->engine(), but more efficient. Note: Add #include <QtQml> to use this function.
See also contextForObject() and qmlContext().
QQmlInfo QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlInfo(const QObject *object) Prints informational messages that include the file and line number for the specified QML object. When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated. To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead. For example, qmlInfo(object) << tr("component property is a write-once property"); prints QML MyCustomType (unknown location): component property is a write-once property Note: In versions prior to Qt 5.9, qmlInfo reported messages using a warning QtMsgType. For Qt 5.9 and above, qmlInfo uses an info QtMsgType. To send warnings, use qmlWarning.
See also QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlDebug and QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlWarning.
bool qmlProtectModule(const char *uri, int majVersion) This function protects a module from having types registered into it. This can be used to prevent other plugins from injecting types into your module. It can also be a performance improvement, as it allows the engine to skip checking for the possibility of new types or plugins when this import is reached. The performance benefit is primarily seen when registering application specific types from within the application instead of through a plugin. Using qmlProtectModule allows the engine to skip checking for a plugin when that uri is imported, which can be noticeable with slow file systems. After this function is called, any attempt to register C++ types into this uri, major version combination will lead to a runtime error. Call this after you have registered all of your types with the engine. Returns true if the module with uri as a module identifier and majVersion as a major version number was found and locked, otherwise returns false. The module must contain exported types in order to be found.
int qmlRegisterExtendedType(const char *uri, int versionMajor, int versionMinor, const char *qmlName) This template function registers the C++ type and its extension object in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor. Properties not available in the main type will be searched for in the extension object. Returns the QML type id. See also qmlRegisterType() and Registering Extension Objects.
int qmlRegisterExtendedUncreatableType(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &reason) This template function registers the C++ type and its extension in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor. While the type has a name and a type, it cannot be created. An error message with the given reason is printed if the user attempts to create an instance of this type. This is useful where the type is only intended for providing attached properties, enum values or an abstract base class with its extension. Returns the QML type id. See also qmlRegisterUncreatableType().
int qmlRegisterInterface(const char *typeName) This template function registers the C++ type in the QML system under the name typeName. Returns the QML type id.
void qmlRegisterModule(const char *uri, int versionMajor, int versionMinor) This function registers a module in a particular uri with a version specified in versionMajor and versionMinor. This can be used to make a certain module version available, even if no types are registered for that version. This is particularly useful for keeping the versions of related modules in sync. This function was introduced in Qt 5.9.
int qmlRegisterRevision(const char *uri, int versionMajor, int versionMinor) This template function registers the specified revision of a C++ type in the QML system with the library imported from uri having the version number composed from versionMajor and versionMinor. Returns the QML type id. template<typename T, int metaObjectRevision>
int qmlRegisterRevision(const char *uri, int versionMajor, int versionMinor); This function is typically used to register the revision of a base class to use for the specified version of the type (see Type Revisions and Versions).
int qmlRegisterSingletonType(const char *uri, int versionMajor, int versionMinor, const char *typeName, QJSValue(* ) ( QQmlEngine *, QJSEngine * ) callback) This function may be used to register a singleton type provider callback in a particular uri and typeName with a version specified in versionMajor and versionMinor. Installing a singleton type allows developers to provide arbitrary functionality (methods and properties) to a client without requiring individual instances of the type to be instantiated by the client. A singleton type may be either a QObject or a QJSValue. This function should be used to register a singleton type provider function which returns a QJSValue as a singleton type. NOTE: QJSValue singleton type properties will not trigger binding re-evaluation if changed. Usage: // First, define the singleton type provider function (callback).
static QJSValue example_qjsvalue_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
static int seedValue = 5;
QJSValue example = scriptEngine->newObject();
example.setProperty("someProperty", seedValue++);
return example;
}
// Second, register the singleton type provider with QML by calling this function in an initialization function.
qmlRegisterSingletonType("Qt.example.qjsvalueApi", 1, 0, "MyApi", example_qjsvalue_singletontype_provider); Alternatively, you can use a C++11 lambda: qmlRegisterSingletonType("Qt.example.qjsvalueApi", 1, 0, "MyApi", [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QJSValue {
Q_UNUSED(engine)
static int seedValue = 5;
QJSValue example = scriptEngine->newObject();
example.setProperty("someProperty", seedValue++);
return example;
}); In order to use the registered singleton type in QML, you must import the singleton type. import QtQuick 2.0
import Qt.example.qjsvalueApi 1.0 as ExampleApi
Item {
id: root
property int someValue: ExampleApi.MyApi.someProperty
}
int qmlRegisterSingletonType(const char *uri, int versionMajor, int versionMinor, const char *typeName, QObject *(* ) ( QQmlEngine *, QJSEngine * ) callback) This function may be used to register a singleton type provider callback in a particular uri and typeName with a version specified in versionMajor and versionMinor. Installing a singleton type into a uri allows developers to provide arbitrary functionality (methods and properties) to clients without requiring individual instances ot the type to be instantiated by the client. A singleton type may be either a QObject or a QJSValue. This function should be used to register a singleton type provider function which returns a QObject of the given type T as a singleton type. A QObject singleton type may be referenced via the type name with which it was registered, and this typename may be used as the target in a Connections type or otherwise used as any other type id would. One exception to this is that a QObject singleton type property may not be aliased (because the singleton type name does not identify an object within the same component as any other item). NOTE: A QObject singleton type instance returned from a singleton type provider is owned by the QML engine unless the object has explicit QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069CppOwnership flag set. Usage: // First, define your QObject which provides the functionality.
class SingletonTypeExample : public QObject
{
Q_OBJECT
Q_PROPERTY (int someProperty READ someProperty WRITE setSomeProperty NOTIFY somePropertyChanged)
public:
SingletonTypeExample(QObject* parent = 0)
: QObject(parent), m_someProperty(0)
{
}
~SingletonTypeExample() {}
Q_INVOKABLE int doSomething() { setSomeProperty(5); return m_someProperty; }
int someProperty() const { return m_someProperty; }
void setSomeProperty(int val) { m_someProperty = val; emit somePropertyChanged(val); }
signals:
void somePropertyChanged(int newValue);
private:
int m_someProperty;
};
// Second, define the singleton type provider function (callback).
static QObject *example_qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
SingletonTypeExample *example = new SingletonTypeExample();
return example;
}
// Third, register the singleton type provider with QML by calling this function in an initialization function.
qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qobjectSingleton", 1, 0, "MyApi", example_qobject_singletontype_provider); Alternatively, you can use a C++11 lambda: qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qjsvalueApi", 1, 0, "MyApi", [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
SingletonTypeExample *example = new SingletonTypeExample();
return example;
}); In order to use the registered singleton type in QML, you must import the singleton type. import QtQuick 2.0
import Qt.example.qobjectSingleton 1.0
Item {
id: root
property int someValue: MyApi.someProperty
Component.onCompleted: {
someValue = MyApi.doSomething()
}
} Since singleton types do not have an associated QQmlContext object, then within the functions of a QObject-derived type that is registered as a singleton type implementation the QML context and engine information is not available. The QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069contextForObject() function returns NULL when supplied with a pointer to an QObject that implements a singleton type. Extending the above example: class SingletonTypeExample : public QObject
{
...
Q_INVOKABLE void doSomethingElse()
{
// QML Engine/Context information is not accessible here:
Q_ASSERT(QQmlEngin8b7c:f320:99b9:690f:4595:cd17:293a:c069contextForObject(this) == 0);
Q_ASSERT(qmlContext(this) == 0);
Q_ASSERT(qmlEngine(this) == 0);
}
...
}
int qmlRegisterSingletonType(const QUrl &url, const char *uri, int versionMajor, int versionMinor, const char *qmlName) This function may be used to register a singleton type with the name qmlName, in the library imported from uri having the version number composed from versionMajor and versionMinor. The type is defined by the QML file [email protected]. The url must be an absolute URL, i.e. url.isRelative() == false. In addition the type's QML file must have pragma Singleton statement among its import statements. A singleton type may be referenced via the type name with which it was registered, and this typename may be used as the target in a Connections type or otherwise used as any other type id would. One exception to this is that a singleton type property may not be aliased (because the singleton type name does not identify an object within the same component as any other item). Usage: // First, define your QML singleton type which provides the functionality.
pragma Singleton
import QtQuick 2.0
Item {
property int testProp1: 125
} // Second, register the QML singleton type by calling this function in an initialization function.
qmlRegisterSingletonType(QUrl("file:///absolute/path/SingletonType.qml"), "Qt.example.qobjectSingleton", 1, 0, "RegisteredSingleton"); In order to use the registered singleton type in QML, you must import the singleton type. import QtQuick 2.0
import Qt.example.qobjectSingleton 1.0
Item {
id: root
property int someValue: RegisteredSingleton.testProp1
} It is also possible to have QML singleton types registered without using the qmlRegisterSingletonType function. That can be done by adding a pragma Singleton statement among the imports of the type's QML file. In addition the type must be defined in a qmldir file with a singleton keyword and the qmldir must be imported by the QML files using the singleton.
int qmlRegisterType() This is an overloaded function. This template function registers the C++ type in the QML system. Instances of this type cannot be created from the QML system. Returns the QML type id.
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName) This template function registers the C++ type in the QML system with the name qmlName, in the library imported from uri having the version number composed from versionMajor and versionMinor. Returns the QML type id. There are two forms of this template function: template<typename T>
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName);
template<typename T, int metaObjectRevision>
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName); The former is the standard form which registers the type T as a new type. The latter allows a particular revision of a class to be registered in a specified version (see Type Revisions and Versions). For example, this registers a C++ class MySliderItem as a QML type named Slider for version 1.0 of a type namespace called "com.mycompany.qmlcomponents": qmlRegisterType<MySliderItem>("com.mycompany.qmlcomponents", 1, 0, "Slider"); Once this is registered, the type can be used in QML by importing the specified type namespace and version number: import com.mycompany.qmlcomponents 1.0
Slider {
// ...
} Note that it's perfectly reasonable for a library to register types to older versions than the actual version of the library. Indeed, it is normal for the new library to allow QML written to previous versions to continue to work, even if more advanced versions of some of its types are available.
int qmlRegisterType(const QUrl &url, const char *uri, int versionMajor, int versionMinor, const char *qmlName) This function registers a type in the QML system with the name qmlName, in the library imported from uri having the version number composed from versionMajor and versionMinor. The type is defined by the QML file [email protected]. The url must be an absolute URL, i.e. url.isRelative() == false. Normally QML files can be loaded as types directly from other QML files, or using a qmldir file. This function allows registration of files to types from C++ code, such as when the type mapping needs to be procedurally [email protected]. Returns -1 if the registration was not successful.
int qmlRegisterTypeNotAvailable(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &message) This function registers a type in the QML system with the name qmlName, in the type namespace imported from uri having the version number composed from versionMajor and versionMinor, but any attempt to instantiate the type will produce the given error message. Normally, the types exported by a plugin should be fixed. However, if a C++ type is not available, you should at least "reserve" the QML type name, and give the user of the unavailable type a meaningful error message. Returns the QML type id. Example: #ifdef NO_GAMES_ALLOWED
qmlRegisterTypeNotAvailable("MinehuntCore", 0, 1, "Game", "Get back to work, slacker!");
#else
qmlRegisterType<MinehuntGame>("MinehuntCore", 0, 1, "Game");
#endif This will cause any QML which imports the "MinehuntCore" type namespace and attempts to use the type to produce an error message: fun.qml: Get back to work, slacker!
Game {
^ Without this, a generic "Game is not a type" message would be given. See also qmlRegisterUncreatableType().
int qmlRegisterUncreatableMetaObject(const QMetaObject &staticMetaObject, const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &reason) This function registers the staticMetaObject and its extension in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor. An instance of the meta object cannot be created. An error message with the given reason is printed if the user attempts to create it. This function is useful for registering Q_NAMESPACE namespaces. Returns the QML type id. For example: namespace MyNamespace {
Q_NAMESPACE
enum MyEnum {
Key1,
Key2,
};
Q_ENUMS(MyEnum)
}
//...
qmlRegisterUncreatableMetaObject(MyNamesp8b7c:f320:99b9:690f:4595:cd17:293a:c069staticMetaObject, "io.qt", 1, 0, "MyNamespace", "Access to enums & flags only"); On the QML side, you can now use the registered enums: Component.onCompleted: console.log(MyNamespace.Key2) This function was introduced in Qt 5.8.
int qmlRegisterUncreatableType(const char *uri, int versionMajor, int versionMinor, const char *qmlName, const QString &message) This template function registers the C++ type in the QML system with the name qmlName, in the library imported from uri having the version number composed from versionMajor and versionMinor. While the type has a name and a type, it cannot be created, and the given error message will result if creation is attempted. This is useful where the type is only intended for providing attached properties or enum values. Returns the QML type id. See also qmlRegisterTypeNotAvailable().
QQmlInfo QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlWarning(const QObject *object) Prints warning messages that include the file and line number for the specified QML object. When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated. To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead. For example, qmlInfo(object) << tr("property cannot be set to 0"); prints QML MyCustomType (unknown location): property cannot be set to 0 This function was introduced in Qt 5.9. See also QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlDebug and QtQml8b7c:f320:99b9:690f:4595:cd17:293a:c069qmlInfo. Macro Documentation
QML_DECLARE_TYPE() Equivalent to Q_DECLARE_METATYPE(TYPE *) and Q_DECLARE_METATYPE(QQmlListProperty<TYPE>)
QML_DECLARE_TYPEINFO(Type, Flags) Declares additional properties of the given Type as described by the specified Flags. Current the only supported type info is QML_HAS_ATTACHED_PROPERTIES which declares that the Type supports attached properties.
|
wp_get_nav_menus( array $args = array() ): WP_Term[] Returns all navigation menu objects. Parameters $args array Optional Array of arguments passed on to get_terms() . More Arguments from get_terms( ... $args ) Array or query string of term query parameters.
taxonomystring|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
object_idsint|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
orderbystringField(s) to order terms by. Accepts:
Term fields ('name', 'slug', 'term_group', 'term_id', 'id', 'description', 'parent', 'term_order'). Unless $object_ids is not empty, 'term_order' is treated the same as 'term_id'.
'count' to use the number of objects associated with the term.
'include' to match the 'order' of the $include param.
'slug__in' to match the 'order' of the $slug param. 'meta_value'
'meta_value_num'. The value of $meta_key. The array keys of $meta_query.
'none' to omit the ORDER BY clause.
Default 'name'.
orderstringWhether to order terms in ascending or descending order. Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'.
hide_emptybool|intWhether to hide terms not assigned to any posts. Accepts 1|true or 0|false. Default 1|true.
includeint[]|stringArray or comma/space-separated string of term IDs to include. Default empty array.
excludeint[]|stringArray or comma/space-separated string of term IDs to exclude. If $include is non-empty, $exclude is ignored. Default empty array.
exclude_treeint[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If $include is non-empty, $exclude_tree is ignored. Default empty array.
numberint|stringMaximum number of terms to return. Accepts ''|0 (all) or any positive number. Default ''|0 (all). Note that $number may not return accurate results when coupled with $object_ids. See #41796 for details.
offsetintThe number by which to offset the terms query.
fieldsstringTerm fields to query for. Accepts:
'all' Returns an array of complete term objects (WP_Term[]).
'all_with_object_id' Returns an array of term objects with the 'object_id' param (WP_Term[]). Works only when the $object_ids parameter is populated.
'ids' Returns an array of term IDs (int[]).
'tt_ids' Returns an array of term taxonomy IDs (int[]).
'names' Returns an array of term names (string[]).
'slugs' Returns an array of term slugs (string[]).
'count' Returns the number of matching terms (int).
'id=>parent' Returns an associative array of parent term IDs, keyed by term ID (int[]).
'id=>name' Returns an associative array of term names, keyed by term ID (string[]).
'id=>slug' Returns an associative array of term slugs, keyed by term ID (string[]).
Default 'all'.
countboolWhether to return a term count. If true, will take precedence over $fields. Default false.
namestring|string[]Name or array of names to return term(s) for.
slugstring|string[]Slug or array of slugs to return term(s) for.
term_taxonomy_idint|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
hierarchicalboolWhether to include terms that have non-empty descendants (even if $hide_empty is set to true). Default true.
searchstringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
name__likestringRetrieve terms with criteria by which a term is LIKE $name__like.
description__likestringRetrieve terms where the description is LIKE $description__like.
pad_countsboolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
getstringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts 'all' or '' (disabled). Default ''.
child_ofintTerm ID to retrieve child terms of. If multiple taxonomies are passed, $child_of is ignored. Default 0.
parentintParent term ID to retrieve direct-child terms of.
childlessboolTrue to limit results to terms that have no children. This parameter has no effect on non-hierarchical taxonomies. Default false.
cache_domainstringUnique cache key to be produced when this query is stored in an object cache. Default 'core'.
update_term_meta_cacheboolWhether to prime meta caches for matched terms. Default true.
meta_keystring|string[]Meta key or keys to filter by.
meta_valuestring|string[]Meta value or values to filter by.
meta_comparestringMySQL operator used for comparing the meta value. See WP_Meta_Query8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() for accepted values and default value.
meta_compare_keystringMySQL operator used for comparing the meta key. See WP_Meta_Query8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() for accepted values and default value.
meta_typestringMySQL data type that the meta_value column will be CAST to for comparisons. See WP_Meta_Query8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() for accepted values and default value.
meta_type_keystringMySQL data type that the meta_key column will be CAST to for comparisons. See WP_Meta_Query8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() for accepted values and default value.
meta_queryarrayAn associative array of WP_Meta_Query arguments. See WP_Meta_Query8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct() for accepted values.
Default: array() Return WP_Term[] An array of menu objects. Source File: wp-includes/nav-menu.php. View all references function wp_get_nav_menus( $args = array() ) {
$defaults = array(
'taxonomy' => 'nav_menu',
'hide_empty' => false,
'orderby' => 'name',
);
$args = wp_parse_args( $args, $defaults );
/**
* Filters the navigation menu objects being returned.
*
* @since 3.0.0
*
* @see get_terms()
*
* @param WP_Term[] $menus An array of menu objects.
* @param array $args An array of arguments used to retrieve menu objects.
*/
return apply_filters( 'wp_get_nav_menus', get_terms( $args ), $args );
}
Hooks apply_filters( 'wp_get_nav_menus', WP_Term[] $menus, array $args )
Filters the navigation menu objects being returned. Related Uses Uses Description get_terms() wp-includes/taxonomy.php Retrieves the terms in a given taxonomy or list of taxonomies. wp_parse_args() wp-includes/functions.php Merges user defined arguments into defaults array. apply_filters() wp-includes/plugin.php Calls the callback functions that have been added to a filter hook.
Used By Used By Description WP_Customize_Nav_Menus8b7c:f320:99b9:690f:4595:cd17:293a:c069nqueue_scripts() wp-includes/class-wp-customize-nav-menus.php Enqueues scripts and styles for Customizer pane. WP_Customize_Nav_Menus8b7c:f320:99b9:690f:4595:cd17:293a:c069ustomize_register() wp-includes/class-wp-customize-nav-menus.php Adds the customizer settings and controls. wxr_nav_menu_terms() wp-admin/includes/export.php Outputs all navigation menu terms. wp_nav_menu_update_menu_items() wp-admin/includes/nav-menu.php Saves nav menu items WP_Nav_Menu_Widget8b7c:f320:99b9:690f:4595:cd17:293a:c069orm() wp-includes/widgets/class-wp-nav-menu-widget.php Outputs the settings form for the Navigation Menu widget. wp_nav_menu() wp-includes/nav-menu-template.php Displays a navigation menu.
Changelog Version Description 4.1.0 Default value of the 'orderby' argument was changed from 'none' to 'name'. 3.0.0 Introduced.
|
Microsoft Hyper-V Creates a Boot2Docker virtual machine locally on your Windows machine using Hyper-V. Hyper-V must be enabled on your desktop system. Docker Desktop for Windows automatically enables it upon install. See this article on the Microsoft developer network for instructions on how to manually enable Hyper-V. Notes: You must use an Administrator level account to create and manage Hyper-V machines. You need an existing virtual switch to use the driver. Hyper-V can share an external network interface (also known as bridging). See this blog to learn more. If you would like to use NAT, create an internal network, and use Internet Connection Sharing. This reference page includes an example showing you how to use an elevated (Administrator-level) PowerShell and create and use an external network switch. Usage $ docker-machine create --driver hyperv vm
Options
--hyperv-boot2docker-url: The URL of the boot2docker ISO.
--hyperv-virtual-switch: Name of the virtual switch to use.
--hyperv-disk-size: Size of disk for the host in MB.
--hyperv-memory: Size of memory for the host in MB.
--hyperv-cpu-count: Number of CPUs for the host.
--hyperv-static-macaddress: Hyper-V network adapter’s static MAC address.
--hyperv-vlan-id: Hyper-V network adapter’s VLAN ID if any.
--hyperv-disable-dynamic-memory: Disable dynamic memory management. Environment variables and default values CLI option Environment variable Default --hyperv-boot2docker-url HYPERV_BOOT2DOCKER_URL Latest boot2docker url --hyperv-cpu-count HYPERV_CPU_COUNT 1 --hyperv-disk-size HYPERV_DISK_SIZE 20000 --hyperv-memory HYPERV_MEMORY 1024 --hyperv-static-macaddress HYPERV_STATIC_MACADDRESS undefined --hyperv-virtual-switch HYPERV_VIRTUAL_SWITCH first found --hyperv-vlan-id HYPERV_VLAN_ID undefined --hyperv-disable-dynamic-memory HYPERV_DISABLE_DYNAMIC_MEMORY false Example: 1. Make sure Hyper-V is enabled. Hyper-V is automatically enabled on a Docker Desktop for Windows installation. To enable it manually, see instructions on how to manually enable Hyper-V on the Microsoft developer network. 2. Set up a new external network switch (Optional) Note: If you already have an external network switch, skip this setup and use that one instead. Make sure you have Ethernet connectivity while you are doing this. Open the Hyper-V Manager. (On Windows 10, search for the Hyper-V Manager in the lower left search field.) Select the Virtual Switch Manager on the right-hand Actions panel. Set up a new external network switch to use instead of DockerNAT network switch (for Moby), which is set up by default when you install Docker Desktop for Windows. If you already have another network switch set up, use that one instead but make sure it is an external switch.) For this example, we created a virtual switch called Primary Virtual Switch. 3. Reboot See this issue on virtualbox: Hangs on Waiting for VM to start #986. Reboot your desktop system to clear out any routing table problems. Without a reboot first, docker-machine create ... might get hung up on Waiting for host to start.... If you are still hung on “Waiting for host to start...” after you reboot, make sure you selected the correct network in the Virtual Switch Manager. 4. Create the nodes with Docker Machine and the Microsoft Hyper-V driver Start an “elevated” PowerShell with administrator privileges. To do this, search for PowerShell, then right click and choose Run as administrator. Run the docker-machine create commands to create machines. For example, if you follow along with the Swarm mode tutorial which asks you to create three networked host machines, you can create these swarm nodes: manager1, worker1, worker2. Use the Microsoft Hyper-V driver and reference the new virtual switch you created. docker-machine create -d hyperv --hyperv-virtual-switch <NameOfVirtualSwitch> <nameOfNode>
Here is an example of creating a manager1 node: PS C:\WINDOWS\system32> docker-machine create -d hyperv --hyperv-virtual-switch "Primary Virtual Switch" manager1
Running pre-create checks...
Creating machine...
(manager1) Copying C:\Users\<your_username>\.docker\machine\cache\boot2docker.iso to C:\Users\<your_username>\.docker\machine\machines\manag
er1\boot2docker.iso...
(manager1) Creating SSH key...
(manager1) Creating VM...
(manager1) Using switch "Primary Virtual Switch"
(manager1) Creating VHD
(manager1) Starting VM...
(manager1) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Doc
ker\Docker\Resources\bin\docker-machine.exe env manager1
PS C:\WINDOWS\system32>
Use the same process, driver, and network switch to create the other nodes. For our example, the commands are: docker-machine create -d hyperv --hyperv-virtual-switch "Primary Virtual Switch" worker1
docker-machine create -d hyperv --hyperv-virtual-switch "Primary Virtual Switch" worker2
Where to go next As a point of interest, the virtual machines you create with docker-machine create show up in the Hyper-V Manager under “Virtual Machines”, but you need to manage them with docker-machine commands and not through the Hyper-V Manager. To get started using docker-machine commands, see these topics: Run containers and experiment with Machine commands and the introductory topics that follow Docker Machine commmand line reference
machine, Microsoft Hyper-V, driver
|
World
A world is an object that contains all bodies and joints. Constructors love.physics.newWorld Creates a new World.
Functions Object:release Immediately destroys the object's Lua reference. 11.0
Object:type Gets the type of the object as a string.
Object:typeOf Checks whether an object is of a certain type.
World:destroy Destroys the world. 0.8.0
World:getAllowSleeping Returns the sleep behaviour of the world. 0.8.0 0.9.0
World:getBodies Returns a table with all bodies. 11.0
World:getBodyCount Returns the number of bodies in the world.
World:getBodyList Returns a table with all bodies. 0.8.0 11.0
World:getCallbacks Returns functions for the callbacks during the world update.
World:getContactCount Returns the number of contacts in the world. 0.8.0
World:getContactFilter Returns the function for collision filtering. 0.8.0
World:getContactList Returns a table with all contacts. 0.8.0 11.0
World:getContacts Returns a table with all Contacts. 11.0
World:getGravity Get the gravity of the world.
World:getJointCount Returns the number of joints in the world.
World:getJointList Returns a table with all joints. 0.8.0 11.0
World:getJoints Returns a table with all joints. 11.0
World:isAllowSleep Get the sleep behaviour of the world. 0.8.0
World:isDestroyed Gets whether the World is destroyed. 0.9.2
World:isLocked Returns if the world is updating its state. 0.8.0
World:isSleepingAllowed Gets the sleep behaviour of the world. 0.9.0
World:queryBoundingBox Calls a function for each fixture inside the specified area. 0.8.0
World:rayCast Casts a ray and calls a function with the fixtures that intersect it. 0.8.0
World:setAllowSleep Set the sleep behaviour of the world. 0.8.0
World:setAllowSleeping Sets the sleep behaviour of the world. 0.8.0 0.9.0
World:setCallbacks Sets functions to be called when shapes collide. 0.8.0
World:setContactFilter Sets a function for collision filtering. 0.8.0
World:setGravity Set the gravity of the world.
World:setMeter Set the scale of the world. 0.8.0
World:setSleepingAllowed Sets the sleep behaviour of the world. 0.9.0
World:translateOrigin Translates the World's origin. 0.9.0
World:update Update the state of the world.
Supertypes Object
See Also love.physics
|
dart:svg createSvgRect method @JSName('createSVGRect') Rect createSvgRect() @JSName('createSVGRect') Implementation @JSName('createSVGRect')
Rect createSvgRect() native;
|
CSSStyleSheet.removeRule()
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 obsolete CSSStyleSheet method removeRule() removes a rule from the stylesheet object. It is functionally identical to the standard, preferred method deleteRule(). Note: This is a legacy method which has been replaced by the standard method deleteRule(). You should use that instead.
Syntax
removeRule(index)
Parameters
index The index into the stylesheet's CSSRuleList indicating the rule to be removed.
Return value
undefined
Examples
This example removes the first rule from the stylesheet myStyles. myStyles.removeRule(0);
You can rewrite this to use the standard deleteRule() method very easily: myStyles.deleteRule(0);
Specifications
Specification
CSS Object Model (CSSOM) # dom-cssstylesheet-removerule
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
removeRule
1
12
68
9
15
3
1
18
68
14
1
1.0
See also
CSS Object Model Using dynamic styling information insertRule()
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 18, 2022, by MDN contributors
|
abstract class UserCacheContextBase Base class for user-based cache contexts. Subclasses need to implement either \Drupal\Core\Cache\Context\CacheContextInterface or \Drupal\Core\Cache\Context\CalculatedCacheContextInterface. Hierarchy
class \Drupal\Core\Cache\Context\UserCacheContextBase
File
core/lib/Drupal/Core/Cache/Context/UserCacheContextBase.php, line 14 Namespace Drupal\Core\Cache\Context Members Name Modifiers Type Description UserCacheContextBas8b7c:f320:99b9:690f:4595:cd17:293a:c069$user protected property The account object. UserCacheContextBas8b7c:f320:99b9:690f:4595:cd17:293a:c069__construct public function Constructs a new UserCacheContextBase class.
|
dart:html
scrollTo method void scrollTo([options_OR_x, y, Map scrollOptions ]) Source void scrollTo([options_OR_x, y, Map scrollOptions]) {
if (options_OR_x == null && y == null && scrollOptions == null) {
_blink.BlinkWindow.instance.scrollTo_Callback_0_(this);
return;
}
if ((options_OR_x is Map) && y == null && scrollOptions == null) {
_blink.BlinkWindow.instance.scrollTo_Callback_1_(this, options_OR_x);
return;
}
if ((y is num) && (options_OR_x is num) && scrollOptions == null) {
_blink.BlinkWindow.instance.scrollTo_Callback_2_(this, options_OR_x, y);
return;
}
if ((y is int) && (options_OR_x is int) && scrollOptions == null) {
_blink.BlinkWindow.instance.scrollTo_Callback_2_(this, options_OR_x, y);
return;
}
if ((scrollOptions is Map) && (y is int) && (options_OR_x is int)) {
_blink.BlinkWindow.instance.scrollTo_Callback_3_(
this, options_OR_x, y, convertDartToNative_Dictionary(scrollOptions));
return;
}
throw new ArgumentError("Incorrect number or type of arguments");
}
|
dart:math log2e top-level constant double const log2e Base-2 logarithm of e. Implementation const double log2e = 1.4426950408889634;
|
fortios_dlp_fp_doc_source – Create a DLP fingerprint database by allowing the FortiGate to access a file server containing files from which to create fingerprints in Fortinet’s FortiOS and FortiGate New in version 2.8. 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 dlp feature and fp_doc_source 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 dlp_fp_doc_source dictionary Default:null Create a DLP fingerprint database by allowing the FortiGate to access a file server containing files from which to create fingerprints. date integer Day of the month on which to scan the server (1 - 31). file_path string Path on the server to the fingerprint files (max 119 characters). file_pattern string Files matching this pattern on the server are fingerprinted. Optionally use the * and ? wildcards. keep_modified string
Choices: enable disable Enable so that when a file is changed on the server the FortiGate keeps the old fingerprint and adds a new fingerprint to the database. name string / required Name of the DLP fingerprint database. password string Password required to log into the file server. period string
Choices: none daily weekly monthly Frequency for which the FortiGate checks the server for new or changed files. remove_deleted string
Choices: enable disable Enable to keep the fingerprint database up to date when a file is deleted from the server. scan_on_creation string
Choices: enable disable Enable to keep the fingerprint database up to date when a file is added or changed on the server. scan_subdirectories string
Choices: enable disable Enable/disable scanning subdirectories to find files to create fingerprints from. sensitivity string Select a sensitivity or threat level for matches with this fingerprint database. Add sensitivities using fp-sensitivity. Source dlp .fp-sensitivity.name. server string IPv4 or IPv6 address of the server. server_type string
Choices: samba Protocol used to communicate with the file server. Currently only Samba (SMB) servers are supported. state string
Choices: present absent Deprecated Starting with Ansible 2.9 we recommend using the top-level 'state' parameter. Indicates whether to create or remove the object. tod_hour integer Hour of the day on which to scan the server (0 - 23). tod_min integer Minute of the hour on which to scan the server (0 - 59). username string User name required to log into the file server. vdom string
Choices: mgmt current Select the VDOM that can communicate with the file server. weekday string
Choices: sunday monday tuesday wednesday thursday friday saturday Day of the week on which to scan the server. 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 added in 2.9
Choices: no
yes ← Ensures FortiGate certificate must be verified by a proper CA. state string added in 2.9
Choices: present absent Indicates whether to create or remove the object. This attribute was present already in previous version in a deeper level. It has been moved out to this outer level. 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. Notes Note Requires fortiosapi library developed by Fortinet Run as a local_action in your playbook Examples - hosts: localhost
vars:
host: "941-981-3904"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Create a DLP fingerprint database by allowing the FortiGate to access a file server containing files from which to create fingerprints.
fortios_dlp_fp_doc_source:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
dlp_fp_doc_source:
date: "3"
file_path: "<your_own_value>"
file_pattern: "<your_own_value>"
keep_modified: "enable"
name: "default_name_7"
password: "<your_own_value>"
period: "none"
remove_deleted: "enable"
scan_on_creation: "enable"
scan_subdirectories: "enable"
sensitivity: "<your_own_value> (source dlp.fp-sensitivity.name)"
server: "941-981-3904"
server_type: "samba"
tod_hour: "16"
tod_min: "17"
username: "<your_own_value>"
vdom: "mgmt"
weekday: "sunday"
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.832-48-32948 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
|
function system_send_email_action_submit system_send_email_action_submit($form, $form_state) Process system_send_email_action form submissions. File
modules/system/system.module, line 3203 Configuration system that lets administrators modify the workings of the site. Code function system_send_email_action_submit($form, $form_state) {
$form_values = $form_state['values'];
// Process the HTML form to store configuration. The keyed array that
// we return will be serialized to the database.
$params = array(
'recipient' => $form_values['recipient'],
'subject' => $form_values['subject'],
'message' => $form_values['message'],
);
return $params;
}
|
st8b7c:f320:99b9:690f:4595:cd17:293a:c069prev_permutation Defined in header <algorithm> (1) template< class BidirIt >
bool prev_permutation( BidirIt first, BidirIt last );
(until C++20) template< class BidirIt >
constexpr bool prev_permutation( BidirIt first, BidirIt last );
(since C++20) (2) template< class BidirIt, class Compare >
bool prev_permutation( BidirIt first, BidirIt last, Compare comp );
(until C++20) template< class BidirIt, class Compare >
constexpr bool prev_permutation( BidirIt first, BidirIt last, Compare comp );
(since C++20) Transforms the range [first, last) into the previous permutation from the set of all permutations that are lexicographically ordered with respect to operator< or comp. Returns true if such permutation exists, otherwise transforms the range into the last permutation (as if by st8b7c:f320:99b9:690f:4595:cd17:293a:c069sort(first, last); st8b7c:f320:99b9:690f:4595:cd17:293a:c069reverse(first, last);) and returns false.
Parameters first, last - the range of elements to permute
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following:
bool cmp(const Type1 &a, const Type2 &b);
While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy (since C++11)). The types Type1 and Type2 must be such that an object of type BidirIt can be dereferenced and then implicitly converted to both of them.
Type requirements
-BidirIt must meet the requirements of ValueSwappable and LegacyBidirectionalIterator.
Return value true if the new permutation precedes the old in lexicographical order. false if the first permutation was reached and the range was reset to the last permutation.
Exceptions Any exceptions thrown from iterator operations or the element swap.
Complexity At most (last-first)/2 swaps. Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call.
Notes Implementations (e.g. MSVC STL) may enable vectorization when the iterator type satisfies LegacyContiguousIterator and swapping its value type calls neither non-trivial special member function nor ADL-found swap.
Possible implementation template<class BidirIt>
bool prev_permutation(BidirIt first, BidirIt last)
{
if (first == last) return false;
BidirIt i = last;
if (first == --i) return false;
while (1) {
BidirIt i1, i2;
i1 = i;
if (*i1 < *--i) {
i2 = last;
while (!(*--i2 < *i))
;
st8b7c:f320:99b9:690f:4595:cd17:293a:c069iter_swap(i, i2);
st8b7c:f320:99b9:690f:4595:cd17:293a:c069reverse(i1, last);
return true;
}
if (i == first) {
st8b7c:f320:99b9:690f:4595:cd17:293a:c069reverse(first, last);
return false;
}
}
}
Example
The following code prints all six permutations of the string "abc" in reverse order.
#include <algorithm>
#include <string>
#include <iostream>
#include <functional>
int main()
{
st8b7c:f320:99b9:690f:4595:cd17:293a:c069string s="abc";
st8b7c:f320:99b9:690f:4595:cd17:293a:c069sort(s.begin(), s.end(), st8b7c:f320:99b9:690f:4595:cd17:293a:c069greater<char>());
do {
st8b7c:f320:99b9:690f:4595:cd17:293a:c069cout << s << ' ';
} while(st8b7c:f320:99b9:690f:4595:cd17:293a:c069prev_permutation(s.begin(), s.end()));
st8b7c:f320:99b9:690f:4595:cd17:293a:c069cout << '\n';
} Output:
cba cab bca bac acb abc See also is_permutation
(C++11) determines if a sequence is a permutation of another sequence (function template)
next_permutation generates the next greater lexicographic permutation of a range of elements (function template)
ranges8b7c:f320:99b9:690f:4595:cd17:293a:c069prev_permutation
(C++20) generates the next smaller lexicographic permutation of a range of elements (niebloid)
|
Deno.Permissions
class Permissions {
query(desc: PermissionDescriptor): Promise<PermissionStatus>;
request(desc: PermissionDescriptor): Promise<PermissionStatus>;
revoke(desc: PermissionDescriptor): Promise<PermissionStatus>;
}
Methods
query(desc: PermissionDescriptor): Promise<PermissionStatus>
Resolves to the current status of a permission. const status = await Deno.permissions.query({ name: "read", path: "/etc" });
console.log(status.state);
request(desc: PermissionDescriptor): Promise<PermissionStatus>
Requests the permission, and resolves to the state of the permission. const status = await Deno.permissions.request({ name: "env" });
if (status.state === "granted") {
console.log("'env' permission is granted.");
} else {
console.log("'env' permission is denied.");
}
revoke(desc: PermissionDescriptor): Promise<PermissionStatus>
Revokes a permission, and resolves to the state of the permission. import { assert } from "https://deno.land/std/testing/asserts.ts";
const status = await Deno.permissions.revoke({ name: "run" });
assert(status.state !== "granted")
|
function path_form_node_form_alter path_form_node_form_alter(&$form, FormStateInterface $form_state) Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm. File
core/modules/path/path.module, line 43 Enables users to rename URLs. Code function path_form_node_form_alter(&$form, FormStateInterface $form_state) {
$node = $form_state->getFormObject()->getEntity();
$form['path_settings'] = array(
'#type' => 'details',
'#title' => t('URL path settings'),
'#open' => !empty($form['path']['widget'][0]['alias']['#value']),
'#group' => 'advanced',
'#access' => !empty($form['path']['#access']) && $node->hasField('path') && $node->get('path')->access('edit'),
'#attributes' => array(
'class' => array('path-form'),
),
'#attached' => array(
'library' => array('path/drupal.path'),
),
'#weight' => 30,
);
$form['path']['#group'] = 'path_settings';
}
|
Class CspMiddleware Content Security Policy Middleware Namespace: Cake\Http\Middleware Property Summary $csp protected ParagonIE\CSPBuilder\CSPBuilder CSP Builder Method Summary __construct() public Constructor process() public Serve assets if the path matches one. Method Detail __construct() public __construct(ParagonIE\CSPBuilder\CSPBuilder|array $csp) Constructor Parameters ParagonIE\CSPBuilder\CSPBuilder|array $csp CSP object or config array Throws RuntimeException process() public process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface Serve assets if the path matches one. Processes an incoming server request in order to produce a response. If unable to produce the response itself, it may delegate to the provided request handler to do so. Parameters ServerRequestInterface $request The request. RequestHandlerInterface $handler The request handler. Returns Psr\Http\Message\ResponseInterface Property Detail $csp protected CSP Builder Type ParagonIE\CSPBuilder\CSPBuilder
|
mpl_toolkits.axisartist.axis_artist.Ticks
class mpl_toolkits.axisartist.axis_artist.Ticks(ticksize, tick_out=False, *, axis=None, **kwargs) [source]
Bases: matplotlib.lines.Line2D, mpl_toolkits.axisartist.axis_artist.AttributeCopier Ticks are derived from Line2D, and note that ticks themselves are markers. Thus, you should use set_mec, set_mew, etc. To change the tick size (length), you need to use set_ticksize. To change the direction of the ticks (ticks are in opposite direction of ticklabels by default), use set_tick_out(False).
draw(self, renderer) [source]
Draw the Artist using the given renderer. This method will be overridden in the Artist subclasses. Typically, it is implemented to not have any effect if the Artist is not visible (Artist.get_visible is False).
Parameters:
renderer : RendererBase subclass.
get_color(self) [source]
Return the line color. See also set_color.
get_markeredgecolor(self) [source]
Return the marker edge color. See also set_markeredgecolor.
get_markeredgewidth(self) [source]
Return the marker edge width in points. See also set_markeredgewidth.
get_ref_artist(self) [source]
get_tick_out(self) [source]
Return True if the tick will be rotated by 180 degree.
get_ticksize(self) [source]
Return length of the ticks in points.
set_locs_angles(self, locs_angles) [source]
set_tick_out(self, b) [source]
set True if tick need to be rotated by 180 degree.
set_ticksize(self, ticksize) [source]
set length of the ticks in points.
|
[Groovy] Class HistoryCommand
org.apache.groovy.groovysh.commands.HistoryCommand
class HistoryCommand
extends ComplexCommandSupport The 'history' command. Field Summary
Fields
Modifiers Name Description
static String COMMAND_NAME
Inherited fields
Fields inherited from class Fields class ComplexCommandSupport defaultFunction, functions class CommandSupport NEWLINE, io, log, messages, registry, shell Properties Summary
Properties
Type Name and description
Object
do_clear
Object
do_flush
Object
do_recallhistory show shows a list of indexes and past commands. recall serves to rerun one of those by their index.
Object
do_show
Constructor Summary
Constructors
Constructor and description HistoryCommand(Groovysh shell)
Methods Summary
Methods
Type Params Return Type Name and description protected List
createCompleters()
Object
execute(List<String> args)
Inherited Methods Summary
Inherited Methods
Methods inherited from class Name class ComplexCommandSupport createCompleters, execute, executeFunction, loadFunction class CommandSupport alias, assertNoArguments, createCompleters, fail, fail, getAliases, getBinding, getBuffer, getBuffers, getClassLoader, getCompleter, getDescription, getHelp, getHidden, getHistory, getImports, getName, getShortcut, getUsage, getVariables Field Detail public static final String COMMAND_NAME
Property Detail
Object do_clear
Object do_flush
Object do_recall
history show shows a list of indexes and past commands. recall serves to rerun one of those by their index. There is is moving window of indexes, so the first valid index will usually be greater than zero.
Object do_show
Constructor Detail
HistoryCommand(Groovysh shell) Method Detail @Override protected List createCompleters() @Override Object execute(List<String> args)
|
Symfony\Bridge\Twig\Form Classes TwigRenderer TwigRendererEngine Interfaces TwigRendererEngineInterface TwigRendererInterface
|
GPUCompilationMessageType
type GPUCompilationMessageType = "error" | "warning" | "info";
Type
"error" | "warning" | "info"
|
community.windows.win_wait_for_process – Waits for a process to exist or not exist before continuing. Note This plugin is part of the community.windows collection (version 1.2.0). To install it use: ansible-galaxy collection install community.windows. To use it in a playbook, specify: community.windows.win_wait_for_process. Synopsis Parameters See Also Examples Return Values Synopsis Waiting for a process to start or stop. This is useful when Windows services behave poorly and do not enumerate external dependencies in their manifest. Parameters Parameter Choices/Defaults Comments owner string The owner of the process. Requires PowerShell version 4.0 or newer. pid integer The PID of the process. post_wait_delay integer Default:0 Seconds to wait after checking for processes. pre_wait_delay integer Default:0 Seconds to wait before checking processes. process_min_count integer Default:1 Minimum number of process matching the supplied pattern to satisfy present condition. Only applies to present. process_name_exact list / elements=string The name of the process(es) for which to wait. The name of the process(es) should not include the file extension suffix. process_name_pattern string RegEx pattern matching desired process(es). sleep integer Default:1 Number of seconds to sleep between checks. Only applies when waiting for a process to start. Waiting for a process to start does not have a native non-polling mechanism. Waiting for a stop uses native PowerShell and does not require polling. state string
Choices: absent
present ← When checking for a running process present will block execution until the process exists, or until the timeout has been reached. absent will block execution until the process no longer exists, or until the timeout has been reached. When waiting for present, the module will return changed only if the process was not present on the initial check but became present on subsequent checks. If, while waiting for absent, new processes matching the supplied pattern are started, these new processes will not be included in the action. timeout integer Default:300 The maximum number of seconds to wait for a for a process to start or stop before erroring out. See Also See also ansible.builtin.wait_for
The official documentation on the ansible.builtin.wait_for module. ansible.windows.win_wait_for
The official documentation on the ansible.windows.win_wait_for module. Examples - name: Wait 300 seconds for all Oracle VirtualBox processes to stop. (VBoxHeadless, VirtualBox, VBoxSVC)
community.windows.win_wait_for_process:
process_name_pattern: 'v(irtual)?box(headless|svc)?'
state: absent
timeout: 500
- name: Wait 300 seconds for 3 instances of cmd to start, waiting 5 seconds between each check
community.windows.win_wait_for_process:
process_name_exact: cmd
state: present
timeout: 500
sleep: 5
process_min_count: 3
Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description elapsed float always The elapsed seconds between the start of poll and the end of the module. Sample: 3.14159265 matched_processes complex always List of matched processes (either stopped or started). name string always The name of the matched process. Sample: svchost owner string when supported by PowerShell The owner of the matched process. Sample: NT AUTHORITY\SYSTEM pid integer always The PID of the matched process. Sample: 7908 Authors Charles Crossan (@crossan007)
© 2012–2018 Michael DeHaan
|
Class AgentLoadException
java.lang.Object
java.lang.Throwable
java.lang.Exception com.sun.tools.attach.AgentLoadException All Implemented Interfaces: Serializable public class AgentLoadException extends Exception The exception thrown when an agent cannot be loaded into the target Java virtual machine. This exception is thrown by VirtualMachine.loadAgent or VirtualMachine.loadAgentLibrary, loadAgentPath methods if the agent, or agent library, cannot be loaded.
See Also: Serialized Form Constructor Summary
Constructor
Description
AgentLoadException()
Constructs an AgentLoadException with no detail message.
AgentLoadException(String s)
Constructs an AgentLoadException with the specified detail message.
Method Summary Methods declared in class java.lang.Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods declared in class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Constructor Details AgentLoadException public AgentLoadException() Constructs an AgentLoadException with no detail message. AgentLoadException public AgentLoadException(String s) Constructs an AgentLoadException with the specified detail message. Parameters:
s - the detail message.
|
Selecting Windows In each frame, at any time, exactly one Emacs window is designated as selected within the frame. For the selected frame, that window is called the selected window—the one in which most editing takes place, and in which the cursor for selected windows appears (see Cursor Parameters). Keyboard input that inserts or deletes text is also normally directed to this window. The selected window’s buffer is usually also the current buffer, except when set-buffer has been used (see Current Buffer). As for non-selected frames, the window selected within the frame becomes the selected window if the frame is ever selected. Function: selected-window
This function returns the selected window (which is always a live window).
The following function explicitly selects a window and its frame. Function: select-window window &optional norecord
This function makes window the selected window and the window selected within its frame, and selects that frame. It also makes window’s buffer (see Buffers and Windows) current and sets that buffer’s value of point to the value of window-point (see Window Point) in window. window must be a live window. The return value is window. By default, this function also moves window’s buffer to the front of the buffer list (see Buffer List) and makes window the most recently selected window. If the optional argument norecord is non-nil, these additional actions are omitted. In addition, this function by default also tells the display engine to update the display of window when its frame gets redisplayed the next time. If norecord is non-nil, such updates are usually not performed. If, however, norecord equals the special symbol mark-for-redisplay, the additional actions mentioned above are omitted but window’s display will be nevertheless updated. Note that sometimes selecting a window is not enough to show it, or make its frame the top-most frame on display: you may also need to raise the frame or make sure input focus is directed to that frame. See Input Focus.
For historical reasons, Emacs does not run a separate hook whenever a window gets selected. Applications and internal routines often temporarily select a window to perform a few actions on it. They do that either to simplify coding—because many functions by default operate on the selected window when no window argument is specified—or because some functions did not (and still do not) take a window as argument and always operate(d) on the selected window instead. Running a hook every time a window gets selected for a short time and once more when the previously selected window gets restored is not useful. However, when its norecord argument is nil, select-window updates the buffer list and thus indirectly runs the normal hook buffer-list-update-hook (see Buffer List). Consequently, that hook provides one way to run a function whenever a window gets selected more “permanently”. Since buffer-list-update-hook is also run by functions that are not related to window management, it will usually make sense to save the value of the selected window somewhere and compare it with the value of selected-window while running that hook. Also, to avoid false positives when using buffer-list-update-hook, it is good practice that every select-window call supposed to select a window only temporarily passes a non-nil norecord argument. If possible, the macro with-selected-window (see below) should be used in such cases. Emacs also runs the hook window-selection-change-functions whenever the redisplay routine detects that another window has been selected since last redisplay. See Window Hooks, for a detailed explanation. window-state-change-functions (described in the same section) is another abnormal hook run after a different window has been selected but is triggered by other window changes as well. The sequence of calls to select-window with a non-nil norecord argument determines an ordering of windows by their selection or use time, see below. The function get-lru-window, for example, can then be used to retrieve the least recently selected window (see Cyclic Window Ordering). Function: frame-selected-window &optional frame
This function returns the window on frame that is selected within that frame. frame should be a live frame; if omitted or nil, it defaults to the selected frame.
Function: set-frame-selected-window frame window &optional norecord
This function makes window the window selected within the frame frame. frame should be a live frame; if nil, it defaults to the selected frame. window should be a live window; if nil, it defaults to the selected window. If frame is the selected frame, this makes window the selected window. If the optional argument norecord is non-nil, this function does not alter the ordering of the most recently selected windows, nor the buffer list.
The following macros are useful to temporarily select a window without affecting the ordering of recently selected windows or the buffer list. Macro: save-selected-window forms…
This macro records the selected frame, as well as the selected window of each frame, executes forms in sequence, then restores the earlier selected frame and windows. It also saves and restores the current buffer. It returns the value of the last form in forms. This macro does not save or restore anything about the sizes, arrangement or contents of windows; therefore, if forms change them, the change persists. If the previously selected window of some frame is no longer live at the time of exit from forms, that frame’s selected window is left alone. If the previously selected window is no longer live, then whatever window is selected at the end of forms remains selected. The current buffer is restored if and only if it is still live when exiting forms. This macro changes neither the ordering of recently selected windows nor the buffer list.
Macro: with-selected-window window forms…
This macro selects window, executes forms in sequence, then restores the previously selected window and current buffer. The ordering of recently selected windows and the buffer list remain unchanged unless you deliberately change them within forms; for example, by calling select-window with argument norecord nil. Hence, this macro is the preferred way to temporarily work with window as the selected window without needlessly running buffer-list-update-hook.
Macro: with-selected-frame frame forms…
This macro executes forms with frame as the selected frame. The value returned is the value of the last form in forms. This macro saves and restores the selected frame, and changes the order of neither the recently selected windows nor the buffers in the buffer list.
Function: window-use-time &optional window
This function returns the use time of window window. window must be a live window and defaults to the selected one. The use time of a window is not really a time value, but an integer that does increase monotonically with each call of select-window with a nil norecord argument. The window with the lowest use time is usually called the least recently used window while the window with the highest use time is called the most recently used one (see Cyclic Window Ordering).
Function: window-bump-use-time &optional window
This function marks window as being the most recently used one. This can be useful when writing certain pop-to-buffer scenarios (see Switching Buffers). window must be a live window and defaults to the selected one.
Sometimes several windows collectively and cooperatively display a buffer, for example, under the management of Follow Mode (see (emacs)Follow Mode), where the windows together display a bigger portion of the buffer than one window could alone. It is often useful to consider such a window group as a single entity. Several functions such as window-group-start (see Window Start and End) allow you to do this by supplying, as an argument, one of the windows as a stand-in for the whole group. Function: selected-window-group
When the selected window is a member of a group of windows, this function returns a list of the windows in the group, ordered such that the first window in the list is displaying the earliest part of the buffer, and so on. Otherwise the function returns a list containing just the selected window. The selected window is considered part of a group when the buffer local variable selected-window-group-function is set to a function. In this case, selected-window-group calls it with no arguments and returns its result (which should be the list of windows in the group).
Copyright
|
function locale_js_settings_alter locale_js_settings_alter(&$settings, AttachedAssetsInterface $assets) Implements hook_js_settings_alter(). Generates the values for the altered core/jquery.ui.datepicker library. File
core/modules/locale/locale.module, line 612 Enables the translation of the user interface to languages other than English. Code function locale_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
if (isset($settings['jquery']['ui']['datepicker'])) {
$language_interface = \Drupal8b7c:f320:99b9:690f:4595:cd17:293a:c069languageManager()->getCurrentLanguage();
$settings['jquery']['ui']['datepicker']['isRTL'] = $language_interface->getDirection() == LanguageInter8b7c:f320:99b9:690f:4595:cd17:293a:c069DIRECTION_RTL;
$settings['jquery']['ui']['datepicker']['firstDay'] = \Drupal8b7c:f320:99b9:690f:4595:cd17:293a:c069onfig('system.date')->get('first_day');
}
}
|
[Java] Class ObjectGraphBuilder.DefaultChildPropertySetter
groovy.util.ObjectGraphBuilder.DefaultChildPropertySetter
All Implemented Interfaces and Traits: ObjectGraphBuilder.ChildPropertySetter public static class ObjectGraphBuilder.DefaultChildPropertySetter Default impl that calls parent.propertyName = child If parent.propertyName is a Collection it will try to add child to the collection. Methods Summary
Methods
Type Params Return Type Name and description public void
setChild(Object parent, Object child, String parentName, String propertyName)
Inherited Methods Summary
Inherited Methods
Methods inherited from class Name class Object wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll Method Detail @Override public void setChild(Object parent, Object child, String parentName, String propertyName)
|
TICKscript Language Reference Kapacitor uses a DSL named TICKscript. The DSL is used to define the pipelines for processing data in Kapacitor. The TICKscript language is an invocation chaining language. Each script has a flat scope and each variable in the scope defines methods that can be called on it. These methods come in two flavors. Property methods – Modifies the node they are called on and returns a reference to the same node. Chaining methods – Creates a new node as a child of the node they are called on and returns a reference to the new node. The reference documentation lists each node’s Property and Chaining methods along with examples and descriptions. Every TICKscript will have either a stream or batch variable defined depending on the type of task you want to run. The stream and batch variables are an instance of a StreamNode or BatchNode respectively. Pipelines Kapacitor uses TICKscripts to define data processing pipelines. A pipeline is set of nodes that process data and edges that connect the nodes. Pipelines in Kapacitor are directed acyclic graphs (DAGs) meaning each edge has a direction that data flows and there cannot be any cycles in the pipeline. Each edge has a type, one of the following: StreamEdge – an edge that transfers data a single data point at a time. BatchEdge – an edge that transfers data in chunks instead of one point at a time. When connecting nodes the TICKscript language will not prevent you from connecting edges of the wrong type but rather the check will be [email protected]. So just be aware that a syntactically correct script may define a pipeline that is invalid. Example stream
|from()
.measurement('app')
|eval(lambda: "errors" / "total")
.as('error_percent')
// Write the transformed data to InfluxDB
|influxDBOut()
.database('mydb')
.retentionPolicy('myrp')
.measurement('errors')
.tag('kapacitor', 'true')
.tag('version', '0.2')
|
GlobalEventHandlers.oncanplay
The oncanplay property of the GlobalEventHandlers mixin is the event handler for processing canplay events. The canplay event is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
Syntax
element.oncanplay = handlerFunction;
var handlerFunction = element.oncanplay;
handlerFunction is either null or a JavaScript function specifying the handler for the event.
Specifications
Specification
HTML Standard # handler-oncanplay
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
oncanplay
32
12
9
9
19
≤12.1-15
9
4.4.3
32
9
19
≤12.1-14
9
2.0
See also
DOM event handlers
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 14, 2021, by MDN contributors
|
tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069ops8b7c:f320:99b9:690f:4595:cd17:293a:c069pplyFtrlV2 #include <training_ops.h> Update '*var' according to the Ftrl-proximal scheme. Summary grad_with_shrinkage = grad + 2 * l2_shrinkage * var accum_new = accum + grad * grad linear += grad_with_shrinkage - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 accum = accum_new Arguments:
scope: A Scope object var: Should be from a Variable(). accum: Should be from a Variable(). linear: Should be from a Variable(). grad: The gradient. lr: Scaling factor. Must be a scalar. l1: L1 regularization. Must be a scalar. l2: L2 shrinkage regularization. Must be a scalar. lr_power: Scaling factor. Must be a scalar. Optional attributes (see Attrs):
use_locking: If True, updating of the var and accum tensors will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. Returns:
Output: Same as "var". Constructors and Destructors ApplyFtrlV2(const 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Scope & scope, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input var, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input accum, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input linear, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input grad, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l1, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2_shrinkage, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr_power) ApplyFtrlV2(const 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Scope & scope, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input var, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input accum, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input linear, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input grad, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l1, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2_shrinkage, 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr_power, const ApplyFtrlV8b7c:f320:99b9:690f:4595:cd17:293a:c069Attrs & attrs) Public attributes operation Operation out 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Output Public functions node() const 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Node * operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input() const operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Output() const Public static functions MultiplyLinearByLr(bool x) Attrs UseLocking(bool x) Attrs Structs tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069ops8b7c:f320:99b9:690f:4595:cd17:293a:c069pplyFtrlV8b7c:f320:99b9:690f:4595:cd17:293a:c069Attrs Optional attribute setters for ApplyFtrlV2. Public attributes operation Operation operation out 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Output out Public functions ApplyFtrlV2 ApplyFtrlV2(
const 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Scope & scope,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input var,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input accum,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input linear,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input grad,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l1,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2_shrinkage,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr_power
) ApplyFtrlV2 ApplyFtrlV2(
const 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Scope & scope,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input var,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input accum,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input linear,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input grad,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l1,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input l2_shrinkage,
8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input lr_power,
const ApplyFtrlV8b7c:f320:99b9:690f:4595:cd17:293a:c069Attrs & attrs
) node 8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Node * node() const operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Input() const operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Output operator8b7c:f320:99b9:690f:4595:cd17:293a:c069tensorflow8b7c:f320:99b9:690f:4595:cd17:293a:c069Output() const Public static functions MultiplyLinearByLr Attrs MultiplyLinearByLr(
bool x
) UseLocking Attrs UseLocking(
bool x
)
|
matplotlib.pyplot.sca matplotlib.pyplot.sca(ax)[source]
Set the current Axes to ax and the current Figure to the parent of ax.
|
The TypeScript Handbook
About this Handbook Over 20 years after its introduction to the programming community, JavaScript is now one of the most widespread cross-platform languages ever created. Starting as a small scripting language for adding trivial interactivity to webpages, JavaScript has grown to be a language of choice for both frontend and backend applications of every size. While the size, scope, and complexity of programs written in JavaScript has grown exponentially, the ability of the JavaScript language to express the relationships between different units of code has not. Combined with JavaScript’s rather peculiar runtime semantics, this mismatch between language and program complexity has made JavaScript development a difficult task to [email protected]. The most common kinds of errors that programmers write can be described as type errors: a certain kind of value was used where a different kind of value was expected. This could be due to simple typos, a failure to understand the API surface of a library, incorrect assumptions about runtime behavior, or other errors. The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked). If you are coming to TypeScript without a JavaScript background, with the intention of TypeScript being your first language, we recommend you first start reading the documentation on either the Microsoft Learn JavaScript tutorial or read JavaScript at the Mozilla Web Docs. If you have experience in other languages, you should be able to pick up JavaScript syntax quite quickly by reading the handbook. How is this Handbook Structured The handbook is split into two sections: The Handbook The TypeScript Handbook is intended to be a comprehensive document that explains TypeScript to everyday programmers. You can read the handbook by going from top to bottom in the left-hand navigation. You should expect each chapter or page to provide you with a strong understanding of the given concepts. The TypeScript Handbook is not a complete language specification, but it is intended to be a comprehensive guide to all of the language’s features and behaviors. A reader who completes the walkthrough should be able to: Read and understand commonly-used TypeScript syntax and patterns Explain the effects of important compiler options Correctly predict type system behavior in most cases In the interests of clarity and brevity, the main content of the Handbook will not explore every edge case or minutiae of the features being covered. You can find more details on particular concepts in the reference articles. Reference Files The reference section below the handbook in the navigation is built to provide a richer understanding of how a particular part of TypeScript works. You can read it top-to-bottom, but each section aims to provide a deeper explanation of a single concept - meaning there is no aim for continuity. Non-Goals The Handbook is also intended to be a concise document that can be comfortably read in a few hours. Certain topics won’t be covered in order to keep things short. Specifically, the Handbook does not fully introduce core JavaScript basics like functions, classes, and closures. Where appropriate, we’ll include links to background reading that you can use to read up on those concepts. The Handbook also isn’t intended to be a replacement for a language specification. In some cases, edge cases or formal descriptions of behavior will be skipped in favor of high-level, easier-to-understand explanations. Instead, there are separate reference pages that more precisely and formally describe many aspects of TypeScript’s behavior. The reference pages are not intended for readers unfamiliar with TypeScript, so they may use advanced terminology or reference topics you haven’t read about yet. Finally, the Handbook won’t cover how TypeScript interacts with other tools, except where necessary. Topics like how to configure TypeScript with webpack, rollup, parcel, react, babel, closure, lerna, rush, bazel, preact, vue, angular, svelte, jquery, yarn, or npm are out of scope - you can find these resources elsewhere on the web. Get Started Before getting started with The Basics, we recommend reading one of the following introductory pages. These introductions are intended to highlight key similarities and differences between TypeScript and your favored programming language, and clear up common misconceptions specific to those languages. TypeScript for New Programmers TypeScript for JavaScript Programmers TypeScript for OOP Programmers TypeScript for Functional Programmers Otherwise, jump to The Basics or grab a copy in Epub or PDF form.
|
LocalTime
package java.time implements Serializable, Comparable<LocalTime>, TemporalAdjuster, Temporal
Available on java
Static variables
staticfinalread onlyMAX:LocalTime
staticfinalread onlyMIDNIGHT:LocalTime
staticfinalread onlyMIN:LocalTime
staticfinalread onlyNOON:LocalTime
Static methods
staticfrom(param1:TemporalAccessor):LocalTime
staticnow(param1:Clock):LocalTime
staticnow():LocalTime
staticnow(param1:ZoneId):LocalTime
staticof(param1:Int, param2:Int, param3:Int, param4:Int):LocalTime
staticof(param1:Int, param2:Int):LocalTime
staticof(param1:Int, param2:Int, param3:Int):LocalTime
staticofNanoOfDay(param1:Int64):LocalTime
staticofSecondOfDay(param1:Int64):LocalTime
staticparse(param1:CharSequence, param2:DateTimeFormatter):LocalTime
staticparse(param1:CharSequence):LocalTime
Methods
adjustInto(param1:Temporal):Temporal
atDate(param1:LocalDate):LocalDateTime
atOffset(param1:ZoneOffset):OffsetTime
compareTo(param1:Dynamic):Int
compareTo(param1:LocalTime):Int
equals(param1:Dynamic):Bool
format(param1:DateTimeFormatter):String
get(param1:TemporalField):Int
getHour():Int
getLong(param1:TemporalField):Int64
getMinute():Int
getNano():Int
getSecond():Int
hashCode():Int
isAfter(param1:LocalTime):Bool
isBefore(param1:LocalTime):Bool
isSupported(param1:TemporalUnit):Bool
isSupported(param1:TemporalField):Bool
minus(param1:TemporalAmount):LocalTime
minus(param1:Int64, param2:TemporalUnit):LocalTime
minusHours(param1:Int64):LocalTime
minusMinutes(param1:Int64):LocalTime
minusNanos(param1:Int64):LocalTime
minusSeconds(param1:Int64):LocalTime
plus(param1:TemporalAmount):LocalTime
plus(param1:Int64, param2:TemporalUnit):LocalTime
plusHours(param1:Int64):LocalTime
plusMinutes(param1:Int64):LocalTime
plusNanos(param1:Int64):LocalTime
plusSeconds(param1:Int64):LocalTime
query<R>(param1:TemporalQuery<R>):R
range(param1:TemporalField):ValueRange
toNanoOfDay():Int64
toSecondOfDay():Int
toString():String
truncatedTo(param1:TemporalUnit):LocalTime
until(param1:Temporal, param2:TemporalUnit):Int64
with(param1:TemporalAdjuster):LocalTime
with(param1:TemporalField, param2:Int64):LocalTime
withHour(param1:Int):LocalTime
withMinute(param1:Int):LocalTime
withNano(param1:Int):LocalTime
withSecond(param1:Int):LocalTime
|
numpy.random.philox.Philox.jumped method
Philox.jumped(jumps=1)
Returns a new bit generator with the state jumped The state of the returned big generator is jumped as-if 2**(128 * jumps) random numbers have been generated.
Parameters:
jumps : integer, positive
Number of times to jump the state of the bit generator returned
Returns:
bit_generator : Philox
New instance of generator jumped iter times
|
class WP_REST_Terms_Controller {} Core class used to managed terms associated with a taxonomy via the REST API. Description See also WP_REST_Controller Methods
__construct — Constructor.
check_is_taxonomy_allowed — Checks that the taxonomy is valid.
check_read_terms_permission_for_post — Checks if the terms for a post can be read.
create_item — Creates a single term in a taxonomy.
create_item_permissions_check — Checks if a request has access to create a term.
delete_item — Deletes a single term from a taxonomy.
delete_item_permissions_check — Checks if a request has access to delete the specified term.
get_collection_params — Retrieves the query params for collections.
get_item — Gets a single term from a taxonomy.
get_item_permissions_check — Checks if a request has access to read or edit the specified term.
get_item_schema — Retrieves the term's schema, conforming to JSON Schema.
get_items — Retrieves terms associated with a taxonomy.
get_items_permissions_check — Checks if a request has access to read terms in the specified taxonomy.
get_term — Get the term, if the ID is valid.
prepare_item_for_database — Prepares a single term for create or update.
prepare_item_for_response — Prepares a single term output for response.
prepare_links — Prepares links for the request.
register_routes — Registers the routes for terms.
update_item — Updates a single term from a taxonomy.
update_item_permissions_check — Checks if a request has access to update the specified term. Source File: wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php. View all references class WP_REST_Terms_Controller extends WP_REST_Controller {
/**
* Taxonomy key.
*
* @since 4.7.0
* @var string
*/
protected $taxonomy;
/**
* Instance of a term meta fields object.
*
* @since 4.7.0
* @var WP_REST_Term_Meta_Fields
*/
protected $meta;
/**
* Column to have the terms be sorted by.
*
* @since 4.7.0
* @var string
*/
protected $sort_column;
/**
* Number of terms that were found.
*
* @since 4.7.0
* @var int
*/
protected $total_terms;
/**
* Whether the controller supports batching.
*
* @since 5.9.0
* @var array
*/
protected $allow_batch = array( 'v1' => true );
/**
* Constructor.
*
* @since 4.7.0
*
* @param string $taxonomy Taxonomy key.
*/
public function __construct( $taxonomy ) {
$this->taxonomy = $taxonomy;
$tax_obj = get_taxonomy( $taxonomy );
$this->rest_base = ! empty( $tax_obj->rest_base ) ? $tax_obj->rest_base : $tax_obj->name;
$this->namespace = ! empty( $tax_obj->rest_namespace ) ? $tax_obj->rest_namespace : 'wp/v2';
$this->meta = new WP_REST_Term_Meta_Fields( $taxonomy );
}
/**
* Registers the routes for terms.
*
* @since 4.7.0
*
* @see register_rest_route()
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069REATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069REATABLE ),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\d]+)',
array(
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the term.' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
array(
'methods' => WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069ITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069ITABLE ),
),
array(
'methods' => WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069LETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'type' => 'boolean',
'default' => false,
'description' => __( 'Required to be true, as terms do not support trashing.' ),
),
),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
/**
* Checks if the terms for a post can be read.
*
* @since 6.0.3
*
* @param WP_Post $post Post object.
* @param WP_REST_Request $request Full details about the request.
* @return bool Whether the terms for the post can be read.
*/
public function check_read_terms_permission_for_post( $post, $request ) {
// If the requested post isn't associated with this taxonomy, deny access.
if ( ! is_object_in_taxonomy( $post->post_type, $this->taxonomy ) ) {
return false;
}
// Grant access if the post is publicly viewable.
if ( is_post_publicly_viewable( $post ) ) {
return true;
}
// Otherwise grant access if the post is readable by the logged in user.
if ( current_user_can( 'read_post', $post->ID ) ) {
return true;
}
// Otherwise, deny access.
return false;
}
/**
* Checks if a request has access to read terms in the specified taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has read access, otherwise false or WP_Error object.
*/
public function get_items_permissions_check( $request ) {
$tax_obj = get_taxonomy( $this->taxonomy );
if ( ! $tax_obj || ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return false;
}
if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->edit_terms ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ! empty( $request['post'] ) ) {
$post = get_post( $request['post'] );
if ( ! $post ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post ID.' ),
array(
'status' => 400,
)
);
}
if ( ! $this->check_read_terms_permission_for_post( $post, $request ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to view terms for this post.' ),
array(
'status' => rest_authorization_required_code(),
)
);
}
}
return true;
}
/**
* Retrieves terms associated with a taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function get_items( $request ) {
// Retrieve the list of registered collection query parameters.
$registered = $this->get_collection_params();
/*
* This array defines mappings between public API query parameters whose
* values are accepted as-passed, and their internal WP_Query parameter
* name equivalents (some are the same). Only values which are also
* present in $registered will be set.
*/
$parameter_mappings = array(
'exclude' => 'exclude',
'include' => 'include',
'order' => 'order',
'orderby' => 'orderby',
'post' => 'post',
'hide_empty' => 'hide_empty',
'per_page' => 'number',
'search' => 'search',
'slug' => 'slug',
);
$prepared_args = array( 'taxonomy' => $this->taxonomy );
/*
* For each known parameter which is both registered and present in the request,
* set the parameter's value on the query $prepared_args.
*/
foreach ( $parameter_mappings as $api_param => $wp_param ) {
if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
$prepared_args[ $wp_param ] = $request[ $api_param ];
}
}
if ( isset( $prepared_args['orderby'] ) && isset( $request['orderby'] ) ) {
$orderby_mappings = array(
'include_slugs' => 'slug__in',
);
if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
$prepared_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
}
}
if ( isset( $registered['offset'] ) && ! empty( $request['offset'] ) ) {
$prepared_args['offset'] = $request['offset'];
} else {
$prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
}
$taxonomy_obj = get_taxonomy( $this->taxonomy );
if ( $taxonomy_obj->hierarchical && isset( $registered['parent'], $request['parent'] ) ) {
if ( 0 === $request['parent'] ) {
// Only query top-level terms.
$prepared_args['parent'] = 0;
} else {
if ( $request['parent'] ) {
$prepared_args['parent'] = $request['parent'];
}
}
}
/**
* Filters get_terms() arguments when querying terms via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_category_query`
* - `rest_post_tag_query`
*
* Enables adding extra arguments or setting defaults for a terms
* collection request.
*
* @since 4.7.0
*
* @link https://developer.wordpress.org/reference/functions/get_terms/
*
* @param array $prepared_args Array of arguments for get_terms().
* @param WP_REST_Request $request The REST API request.
*/
$prepared_args = apply_filters( "rest_{$this->taxonomy}_query", $prepared_args, $request );
if ( ! empty( $prepared_args['post'] ) ) {
$query_result = wp_get_object_terms( $prepared_args['post'], $this->taxonomy, $prepared_args );
// Used when calling wp_count_terms() below.
$prepared_args['object_ids'] = $prepared_args['post'];
} else {
$query_result = get_terms( $prepared_args );
}
$count_args = $prepared_args;
unset( $count_args['number'], $count_args['offset'] );
$total_terms = wp_count_terms( $count_args );
// wp_count_terms() can return a falsey value when the term has no children.
if ( ! $total_terms ) {
$total_terms = 0;
}
$response = array();
foreach ( $query_result as $term ) {
$data = $this->prepare_item_for_response( $term, $request );
$response[] = $this->prepare_response_for_collection( $data );
}
$response = rest_ensure_response( $response );
// Store pagination values for headers.
$per_page = (int) $prepared_args['number'];
$page = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
$response->header( 'X-WP-Total', (int) $total_terms );
$max_pages = ceil( $total_terms / $per_page );
$response->header( 'X-WP-TotalPages', (int) $max_pages );
$request_params = $request->get_query_params();
$collection_url = rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) );
$base = add_query_arg( urlencode_deep( $request_params ), $collection_url );
if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}
return $response;
}
/**
* Get the term, if the ID is valid.
*
* @since 4.7.2
*
* @param int $id Supplied ID.
* @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise.
*/
protected function get_term( $id ) {
$error = new WP_Error(
'rest_term_invalid',
__( 'Term does not exist.' ),
array( 'status' => 404 )
);
if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return $error;
}
if ( (int) $id <= 0 ) {
return $error;
}
$term = get_term( (int) $id, $this->taxonomy );
if ( empty( $term ) || $term->taxonomy !== $this->taxonomy ) {
return $error;
}
return $term;
}
/**
* Checks if a request has access to read or edit the specified term.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has read access for the item, otherwise false or WP_Error object.
*/
public function get_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( 'edit' === $request['context'] && ! current_user_can( 'edit_term', $term->term_id ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Gets a single term from a taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function get_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
$response = $this->prepare_item_for_response( $term, $request );
return rest_ensure_response( $response );
}
/**
* Checks if a request has access to create a term.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has access to create items, false or WP_Error object otherwise.
*/
public function create_item_permissions_check( $request ) {
if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return false;
}
$taxonomy_obj = get_taxonomy( $this->taxonomy );
if ( ( is_taxonomy_hierarchical( $this->taxonomy )
&& ! current_user_can( $taxonomy_obj->cap->edit_terms ) )
|| ( ! is_taxonomy_hierarchical( $this->taxonomy )
&& ! current_user_can( $taxonomy_obj->cap->assign_terms ) ) ) {
return new WP_Error(
'rest_cannot_create',
__( 'Sorry, you are not allowed to create terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Creates a single term in a taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function create_item( $request ) {
if ( isset( $request['parent'] ) ) {
if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
return new WP_Error(
'rest_taxonomy_not_hierarchical',
__( 'Cannot set parent term, taxonomy is not hierarchical.' ),
array( 'status' => 400 )
);
}
$parent = get_term( (int) $request['parent'], $this->taxonomy );
if ( ! $parent ) {
return new WP_Error(
'rest_term_invalid',
__( 'Parent term does not exist.' ),
array( 'status' => 400 )
);
}
}
$prepared_term = $this->prepare_item_for_database( $request );
$term = wp_insert_term( wp_slash( $prepared_term->name ), $this->taxonomy, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $term ) ) {
/*
* If we're going to inform the client that the term already exists,
* give them the identifier for future use.
*/
$term_id = $term->get_error_data( 'term_exists' );
if ( $term_id ) {
$existing_term = get_term( $term_id, $this->taxonomy );
$term->add_data( $existing_term->term_id, 'term_exists' );
$term->add_data(
array(
'status' => 400,
'term_id' => $term_id,
)
);
}
return $term;
}
$term = get_term( $term['term_id'], $this->taxonomy );
/**
* Fires after a single term is created or updated via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_insert_category`
* - `rest_insert_post_tag`
*
* @since 4.7.0
*
* @param WP_Term $term Inserted or updated term object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a term, false when updating.
*/
do_action( "rest_insert_{$this->taxonomy}", $term, $request, true );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'edit' );
/**
* Fires after a single term is completely created or updated via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_after_insert_category`
* - `rest_after_insert_post_tag`
*
* @since 5.0.0
*
* @param WP_Term $term Inserted or updated term object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a term, false when updating.
*/
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, true );
$response = $this->prepare_item_for_response( $term, $request );
$response = rest_ensure_response( $response );
$response->set_status( 201 );
$response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) );
return $response;
}
/**
* Checks if a request has access to update the specified term.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has access to update the item, false or WP_Error object otherwise.
*/
public function update_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
return new WP_Error(
'rest_cannot_update',
__( 'Sorry, you are not allowed to edit this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Updates a single term from a taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function update_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( isset( $request['parent'] ) ) {
if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
return new WP_Error(
'rest_taxonomy_not_hierarchical',
__( 'Cannot set parent term, taxonomy is not hierarchical.' ),
array( 'status' => 400 )
);
}
$parent = get_term( (int) $request['parent'], $this->taxonomy );
if ( ! $parent ) {
return new WP_Error(
'rest_term_invalid',
__( 'Parent term does not exist.' ),
array( 'status' => 400 )
);
}
}
$prepared_term = $this->prepare_item_for_database( $request );
// Only update the term if we have something to update.
if ( ! empty( $prepared_term ) ) {
$update = wp_update_term( $term->term_id, $term->taxonomy, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $update ) ) {
return $update;
}
}
$term = get_term( $term->term_id, $this->taxonomy );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_insert_{$this->taxonomy}", $term, $request, false );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'edit' );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, false );
$response = $this->prepare_item_for_response( $term, $request );
return rest_ensure_response( $response );
}
/**
* Checks if a request has access to delete the specified term.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has access to delete the item, otherwise false or WP_Error object.
*/
public function delete_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! current_user_can( 'delete_term', $term->term_id ) ) {
return new WP_Error(
'rest_cannot_delete',
__( 'Sorry, you are not allowed to delete this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Deletes a single term from a taxonomy.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function delete_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
$force = isset( $request['force'] ) ? (bool) $request['force'] : false;
// We don't support trashing for terms.
if ( ! $force ) {
return new WP_Error(
'rest_trash_not_supported',
/* translators: %s: force=true */
sprintf( __( "Terms do not support trashing. Set '%s' to delete." ), 'force=true' ),
array( 'status' => 501 )
);
}
$request->set_param( 'context', 'view' );
$previous = $this->prepare_item_for_response( $term, $request );
$retval = wp_delete_term( $term->term_id, $term->taxonomy );
if ( ! $retval ) {
return new WP_Error(
'rest_cannot_delete',
__( 'The term cannot be deleted.' ),
array( 'status' => 500 )
);
}
$response = new WP_REST_Response();
$response->set_data(
array(
'deleted' => true,
'previous' => $previous->get_data(),
)
);
/**
* Fires after a single term is deleted via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_delete_category`
* - `rest_delete_post_tag`
*
* @since 4.7.0
*
* @param WP_Term $term The deleted term.
* @param WP_REST_Response $response The response data.
* @param WP_REST_Request $request The request sent to the API.
*/
do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request );
return $response;
}
/**
* Prepares a single term for create or update.
*
* @since 4.7.0
*
* @param WP_REST_Request $request Request object.
* @return object Term object.
*/
public function prepare_item_for_database( $request ) {
$prepared_term = new stdClass;
$schema = $this->get_item_schema();
if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
$prepared_term->name = $request['name'];
}
if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
$prepared_term->slug = $request['slug'];
}
if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
$prepared_term->taxonomy = $request['taxonomy'];
}
if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
$prepared_term->description = $request['description'];
}
if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
$parent_term_id = 0;
$requested_parent = (int) $request['parent'];
if ( $requested_parent ) {
$parent_term = get_term( $requested_parent, $this->taxonomy );
if ( $parent_term instanceof WP_Term ) {
$parent_term_id = $parent_term->term_id;
}
}
$prepared_term->parent = $parent_term_id;
}
/**
* Filters term data before inserting term via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_pre_insert_category`
* - `rest_pre_insert_post_tag`
*
* @since 4.7.0
*
* @param object $prepared_term Term object.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
}
/**
* Prepares a single term output for response.
*
* @since 4.7.0
*
* @param WP_Term $item Term object.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response Response object.
*/
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( in_array( 'id', $fields, true ) ) {
$data['id'] = (int) $item->term_id;
}
if ( in_array( 'count', $fields, true ) ) {
$data['count'] = (int) $item->count;
}
if ( in_array( 'description', $fields, true ) ) {
$data['description'] = $item->description;
}
if ( in_array( 'link', $fields, true ) ) {
$data['link'] = get_term_link( $item );
}
if ( in_array( 'name', $fields, true ) ) {
$data['name'] = $item->name;
}
if ( in_array( 'slug', $fields, true ) ) {
$data['slug'] = $item->slug;
}
if ( in_array( 'taxonomy', $fields, true ) ) {
$data['taxonomy'] = $item->taxonomy;
}
if ( in_array( 'parent', $fields, true ) ) {
$data['parent'] = (int) $item->parent;
}
if ( in_array( 'meta', $fields, true ) ) {
$data['meta'] = $this->meta->get_value( $item->term_id, $request );
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $item ) );
}
/**
* Filters the term data for a REST API response.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_prepare_category`
* - `rest_prepare_post_tag`
*
* Allows modification of the term data right before it is returned.
*
* @since 4.7.0
*
* @param WP_REST_Response $response The response object.
* @param WP_Term $item The original term object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $item, $request );
}
/**
* Prepares links for the request.
*
* @since 4.7.0
*
* @param WP_Term $term Term object.
* @return array Links for the given term.
*/
protected function prepare_links( $term ) {
$links = array(
'self' => array(
'href' => rest_url( rest_get_route_for_term( $term ) ),
),
'collection' => array(
'href' => rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) ),
),
'about' => array(
'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $this->taxonomy ) ),
),
);
if ( $term->parent ) {
$parent_term = get_term( (int) $term->parent, $term->taxonomy );
if ( $parent_term ) {
$links['up'] = array(
'href' => rest_url( rest_get_route_for_term( $parent_term ) ),
'embeddable' => true,
);
}
}
$taxonomy_obj = get_taxonomy( $term->taxonomy );
if ( empty( $taxonomy_obj->object_type ) ) {
return $links;
}
$post_type_links = array();
foreach ( $taxonomy_obj->object_type as $type ) {
$rest_path = rest_get_route_for_post_type_items( $type );
if ( empty( $rest_path ) ) {
continue;
}
$post_type_links[] = array(
'href' => add_query_arg( $this->rest_base, $term->term_id, rest_url( $rest_path ) ),
);
}
if ( ! empty( $post_type_links ) ) {
$links['https://api.w.org/post_type'] = $post_type_links;
}
return $links;
}
/**
* Retrieves the term's schema, conforming to JSON Schema.
*
* @since 4.7.0
*
* @return array Item schema data.
*/
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Unique identifier for the term.' ),
'type' => 'integer',
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
'count' => array(
'description' => __( 'Number of published posts for the term.' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'HTML description of the term.' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'link' => array(
'description' => __( 'URL of the term.' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'HTML title for the term.' ),
'type' => 'string',
'context' => array( 'view', 'embed', 'edit' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
'required' => true,
),
'slug' => array(
'description' => __( 'An alphanumeric identifier for the term unique to its type.' ),
'type' => 'string',
'context' => array( 'view', 'embed', 'edit' ),
'arg_options' => array(
'sanitize_callback' => array( $this, 'sanitize_slug' ),
),
),
'taxonomy' => array(
'description' => __( 'Type attribution for the term.' ),
'type' => 'string',
'enum' => array( $this->taxonomy ),
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
),
);
$taxonomy = get_taxonomy( $this->taxonomy );
if ( $taxonomy->hierarchical ) {
$schema['properties']['parent'] = array(
'description' => __( 'The parent term ID.' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
);
}
$schema['properties']['meta'] = $this->meta->get_field_schema();
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
/**
* Retrieves the query params for collections.
*
* @since 4.7.0
*
* @return array Collection parameters.
*/
public function get_collection_params() {
$query_params = parent8b7c:f320:99b9:690f:4595:cd17:293a:c069get_collection_params();
$taxonomy = get_taxonomy( $this->taxonomy );
$query_params['context']['default'] = 'view';
$query_params['exclude'] = array(
'description' => __( 'Ensure result set excludes specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
$query_params['include'] = array(
'description' => __( 'Limit result set to specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
if ( ! $taxonomy->hierarchical ) {
$query_params['offset'] = array(
'description' => __( 'Offset the result set by a specific number of items.' ),
'type' => 'integer',
);
}
$query_params['order'] = array(
'description' => __( 'Order sort attribute ascending or descending.' ),
'type' => 'string',
'default' => 'asc',
'enum' => array(
'asc',
'desc',
),
);
$query_params['orderby'] = array(
'description' => __( 'Sort collection by term attribute.' ),
'type' => 'string',
'default' => 'name',
'enum' => array(
'id',
'include',
'name',
'slug',
'include_slugs',
'term_group',
'description',
'count',
),
);
$query_params['hide_empty'] = array(
'description' => __( 'Whether to hide terms not assigned to any posts.' ),
'type' => 'boolean',
'default' => false,
);
if ( $taxonomy->hierarchical ) {
$query_params['parent'] = array(
'description' => __( 'Limit result set to terms assigned to a specific parent.' ),
'type' => 'integer',
);
}
$query_params['post'] = array(
'description' => __( 'Limit result set to terms assigned to a specific post.' ),
'type' => 'integer',
'default' => null,
);
$query_params['slug'] = array(
'description' => __( 'Limit result set to terms with one or more specific slugs.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
);
/**
* Filters collection parameters for the terms controller.
*
* The dynamic part of the filter `$this->taxonomy` refers to the taxonomy
* slug for the controller.
*
* This filter registers the collection parameter, but does not map the
* collection parameter to an internal WP_Term_Query parameter. Use the
* `rest_{$this->taxonomy}_query` filter to set WP_Term_Query parameters.
*
* @since 4.7.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
* @param WP_Taxonomy $taxonomy Taxonomy object.
*/
return apply_filters( "rest_{$this->taxonomy}_collection_params", $query_params, $taxonomy );
}
/**
* Checks that the taxonomy is valid.
*
* @since 4.7.0
*
* @param string $taxonomy Taxonomy to check.
* @return bool Whether the taxonomy is allowed for REST management.
*/
protected function check_is_taxonomy_allowed( $taxonomy ) {
$taxonomy_obj = get_taxonomy( $taxonomy );
if ( $taxonomy_obj && ! empty( $taxonomy_obj->show_in_rest ) ) {
return true;
}
return false;
}
}
Related Uses Uses Description WP_REST_Controller wp-includes/rest-api/endpoints/class-wp-rest-controller.php Core base controller for managing and interacting with REST API items.
Used By Used By Description WP_REST_Menus_Controller wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php Core class used to managed menu terms associated via the REST API.
Changelog Version Description 4.7.0 Introduced.
|
PARENT_DIRECTORY Source directory that added current subdirectory. This read-only property specifies the source directory that added the current source directory as a subdirectory of the build. In the top-level directory the value is the empty-string.
|
CSRF Protection Introduction Excluding URIs X-CSRF-Token X-XSRF-Token Introduction Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user. Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field: <form method="POST" action="/profile">
@csrf
...
</form> The VerifyCsrfToken middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session. CSRF Tokens & JavaScript When building JavaScript driven applications, it is convenient to have your JavaScript HTTP library automatically attach the CSRF token to every outgoing request. By default, the Axios HTTP library provided in the resources/js/bootstrap.js file automatically sends an X-XSRF-TOKEN header using the value of the encrypted XSRF-TOKEN cookie. If you are not using this library, you will need to manually configure this behavior for your application. Excluding URIs From CSRF Protection Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes. Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware: <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
} The CSRF middleware is automatically disabled when running tests. X-CSRF-TOKEN In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in an HTML meta tag: <meta name="csrf-token" content="{{ csrf_token() }}"> Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications: $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}); X-XSRF-TOKEN Laravel stores the current CSRF token in an encrypted XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header. This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header on same-origin requests. By default, the resources/js/bootstrap.js file includes the Axios HTTP library which will automatically send this for you.
|
nxos_ospf_vrf – Manages a VRF for an OSPF router Synopsis Parameters Notes Examples Return Values Status Synopsis Manages a VRF for an OSPF router. Parameters Parameter Choices/Defaults Comments auto_cost - Specifies the reference bandwidth used to assign OSPF cost. Valid values are an integer, in Mbps, or the keyword 'default'. bfd string added in 2.9
Choices: enable disable Enables BFD on all OSPF interfaces. Dependency: 'feature bfd' default_metric - Specify the default Metric value. Valid values are an integer or the keyword 'default'. log_adjacency -
Choices: log detail default Controls the level of log messages generated whenever a neighbor changes state. Valid values are 'log', 'detail', and 'default'. ospf - / required Name of the OSPF instance. passive_interface boolean added in 2.4
Choices: no yes Setting to yes will suppress routing update on interface. provider dictionary Deprecated Starting with Ansible 2.5 we recommend using connection: network_cli. This option is only required if you are using NX-API. For more information please see the NXOS Platform Options guide. A dict object containing connection details. auth_pass string added in 2.5.3 Specifies the password to use if required to enter privileged mode on the remote device. If authorize is false, then this argument does nothing. If the value is not specified in the task, the value of environment variable ANSIBLE_NET_AUTH_PASS will be used instead. authorize boolean added in 2.5.3
Choices:
no ← yes Instructs the module to enter privileged mode on the remote device before sending any commands. If not specified, the device will attempt to execute all commands in non-privileged mode. If the value is not specified in the task, the value of environment variable ANSIBLE_NET_AUTHORIZE will be used instead. host string / required Specifies the DNS host name or address for connecting to the remote device over the specified transport. The value of host is used as the destination address for the transport. password string Specifies the password to use to authenticate the connection to the remote device. This is a common argument used for either cli or nxapi transports. If the value is not specified in the task, the value of environment variable ANSIBLE_NET_PASSWORD will be used instead. port integer Default:"0 (use common port)" Specifies the port to use when building the connection to the remote device. This value applies to either cli or nxapi. The port value will default to the appropriate transport common port if none is provided in the task. (cli=22, http=80, https=443). ssh_keyfile string Specifies the SSH key to use to authenticate the connection to the remote device. This argument is only used for the cli transport. If the value is not specified in the task, the value of environment variable ANSIBLE_NET_SSH_KEYFILE will be used instead. timeout integer Default:10 Specifies the timeout in seconds for communicating with the network device for either connecting or sending commands. If the timeout is exceeded before the operation is completed, the module will error. NX-API can be slow to return on long-running commands (sh mac, sh bgp, etc). transport string / required
Choices:
cli ← nxapi Configures the transport connection to use when connecting to the remote device. The transport argument supports connectivity to the device over cli (ssh) or nxapi. use_proxy boolean added in 2.5
Choices: no
yes ← If no, the environment variables http_proxy and https_proxy will be ignored. use_ssl boolean
Choices:
no ← yes Configures the transport to use SSL if set to yes only when the transport=nxapi, otherwise this value is ignored. username string Configures the username to use to authenticate the connection to the remote device. This value is used to authenticate either the CLI login or the nxapi authentication depending on which transport is used. If the value is not specified in the task, the value of environment variable ANSIBLE_NET_USERNAME will be used instead. validate_certs boolean
Choices: no
yes ← If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. If the transport argument is not nxapi, this value is ignored. router_id - Router Identifier (ID) of the OSPF router VRF instance. state -
Choices:
present ← absent State of ospf vrf configuration. timer_throttle_lsa_hold - Specify the hold interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'. timer_throttle_lsa_max - Specify the max interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'. timer_throttle_lsa_start - Specify the start interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'. timer_throttle_spf_hold - Specify minimum hold time between Shortest Path First (SPF) calculations. Valid values are an integer, in milliseconds, or the keyword 'default'. timer_throttle_spf_max - Specify the maximum wait time between Shortest Path First (SPF) calculations. Valid values are an integer, in milliseconds, or the keyword 'default'. timer_throttle_spf_start - Specify initial Shortest Path First (SPF) schedule delay. Valid values are an integer, in milliseconds, or the keyword 'default'. vrf - Default:"default" Name of the resource instance. Valid value is a string. The name 'default' is a valid VRF representing the global OSPF. Notes Note Tested against NXOSv 7.3.(0)D1(1) on VIRL Value default restores params default value, if any. Otherwise it removes the existing param configuration. For information on using CLI and NX-API see the NXOS Platform Options guide
For more information on using Ansible to manage network devices see the Ansible Network Guide
For more information on using Ansible to manage Cisco devices see the Cisco integration page. Examples - nxos_ospf_vrf:
ospf: 1
timer_throttle_spf_start: 50
timer_throttle_spf_hold: 1000
timer_throttle_spf_max: 2000
timer_throttle_lsa_start: 60
timer_throttle_lsa_hold: 1100
timer_throttle_lsa_max: 3000
vrf: test
bfd: enable
state: present
Return Values Common return values are documented here, the following are the fields unique to this module: Key Returned Description commands list always commands sent to the device Sample: ['router ospf 1', 'vrf test', 'bfd', 'timers throttle lsa 60 1100 3000'] Status This module is not guaranteed to have a backwards compatible interface. [preview]
This module is maintained by the Ansible Network Team. [network]
Red Hat Support More information about Red Hat’s support of this module is available from this Red Hat Knowledge Base article. Authors Gabriele Gerbino (@GGabriele) Hint If you notice any issues in this documentation, you can edit this document to improve it.
© 2012–2018 Michael DeHaan
|
Builder class Builder (View source) Traits BuildsQueries ForwardsCalls Macroable Properties static protected array $macros The registered string macros. from Macroable ConnectionInterface $connection The database connection instance. Grammar $grammar The database query grammar instance. Processor $processor The database query post processor instance. array $bindings The current query value bindings. array $aggregate An aggregate function and column to be run. array $columns The columns that should be returned. bool|array $distinct Indicates if the query returns distinct results. string $from The table which the query is targeting. array $joins The table joins for the query. array $wheres The where constraints for the query. array $groups The groupings for the query. array $havings The having constraints for the query. array $orders The orderings for the query. int $limit The maximum number of records to return. int $offset The number of records to skip. array $unions The query union statements. int $unionLimit The maximum number of union records to return. int $unionOffset The number of union records to skip. array $unionOrders The orderings for the union query. string|bool $lock Indicates whether row locking is being used. array $operators All of the available clause operators. bool $useWritePdo Whether use write pdo for select. Methods bool chunk(int $count, callable $callback) Chunk the results of the query. from BuildsQueries bool each(callable $callback, int $count = 1000) Execute a callback over each item while chunking. from BuildsQueries bool chunkById(int $count, callable $callback, string|null $column = null, string|null $alias = null) Chunk the results of a query by comparing IDs. from BuildsQueries bool eachById(callable $callback, int $count = 1000, string|null $column = null, string|null $alias = null) Execute a callback over each item while chunking by id. from BuildsQueries Model|object|BuildsQueries|null first(array|string $columns = ['*']) Execute the query and get the first result. from BuildsQueries mixed|$this when(mixed $value, callable $callback, callable|null $default = null) Apply the callback's query changes if the given "value" is true. from BuildsQueries $this tap(callable $callback) Pass the query to a given callback. from BuildsQueries mixed|$this unless(mixed $value, callable $callback, callable|null $default = null) Apply the callback's query changes if the given "value" is false. from BuildsQueries LengthAwarePaginator paginator(Collection $items, int $total, int $perPage, int $currentPage, array $options) Create a new length-aware paginator instance. from BuildsQueries Paginator simplePaginator(Collection $items, int $perPage, int $currentPage, array $options) Create a new simple paginator instance. from BuildsQueries mixed forwardCallTo(mixed $object, string $method, array $parameters) Forward a method call to the given object. from ForwardsCalls static void throwBadMethodCallException(string $method) Throw a bad method call exception for the given method. from ForwardsCalls static void macro(string $name, object|callable $macro) Register a custom macro. from Macroable static void mixin(object $mixin, bool $replace = true) Mix another object into the class. from Macroable static bool hasMacro(string $name) Checks if macro is registered. from Macroable static mixed __callStatic(string $method, array $parameters) Dynamically handle calls to the class. from Macroable mixed __call(string $method, array $parameters) Handle dynamic method calls into the method. void __construct(ConnectionInterface $connection, Grammar $grammar = null, Processor $processor = null) Create a new query builder instance. $this select(array|mixed $columns = ['*']) Set the columns to be selected. Builder|Builder selectSub(Closure|$this|string $query, string $as) Add a subselect expression to the query. Builder|Builder selectRaw(string $expression, array $bindings = []) Add a new "raw" select expression to the query. Builder|Builder fromSub(Closure|Builder|string $query, string $as) Makes "from" fetch from a subquery. Builder|Builder fromRaw(string $expression, mixed $bindings = []) Add a raw from clause to the query. array createSub(Closure|Builder|string $query) Creates a subquery and parse it. array parseSub(mixed $query) Parse the subquery into SQL and bindings. $this addSelect(array|mixed $column) Add a new select column to the query. $this distinct() Force the query to only return distinct results. $this from(Closure|Builder|string $table, string|null $as = null) Set the table which the query is targeting. $this join(string $table, Closure|string $first, string|null $operator = null, string|null $second = null, string $type = 'inner', bool $where = false) Add a join clause to the query. Builder|Builder joinWhere(string $table, Closure|string $first, string $operator, string $second, string $type = 'inner') Add a "join where" clause to the query. Builder|Builder joinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null, string $type = 'inner', bool $where = false) Add a subquery join clause to the query. Builder|Builder leftJoin(string $table, Closure|string $first, string|null $operator = null, string|null $second = null) Add a left join to the query. Builder|Builder leftJoinWhere(string $table, Closure|string $first, string $operator, string $second) Add a "join where" clause to the query. Builder|Builder leftJoinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null) Add a subquery left join to the query. Builder|Builder rightJoin(string $table, Closure|string $first, string|null $operator = null, string|null $second = null) Add a right join to the query. Builder|Builder rightJoinWhere(string $table, Closure|string $first, string $operator, string $second) Add a "right join where" clause to the query. Builder|Builder rightJoinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null) Add a subquery right join to the query. Builder|Builder crossJoin(string $table, Closure|string|null $first = null, string|null $operator = null, string|null $second = null) Add a "cross join" clause to the query. JoinClause newJoinClause(Builder $parentQuery, string $type, string $table) Get a new join clause. void mergeWheres(array $wheres, array $bindings) Merge an array of where clauses and bindings. $this where(Closure|string|array $column, mixed $operator = null, mixed $value = null, string $boolean = 'and') Add a basic where clause to the query. $this addArrayOfWheres(array $column, string $boolean, string $method = 'where') Add an array of where clauses to the query. array prepareValueAndOperator(string $value, string $operator, bool $useDefault = false) Prepare the value and operator for a where clause. bool invalidOperatorAndValue(string $operator, mixed $value) Determine if the given operator and value combination is legal. bool invalidOperator(string $operator) Determine if the given operator is supported. Builder|Builder orWhere(Closure|string|array $column, mixed $operator = null, mixed $value = null) Add an "or where" clause to the query. Builder|Builder whereColumn(string|array $first, string|null $operator = null, string|null $second = null, string|null $boolean = 'and') Add a "where" clause comparing two columns to the query. Builder|Builder orWhereColumn(string|array $first, string|null $operator = null, string|null $second = null) Add an "or where" clause comparing two columns to the query. $this whereRaw(string $sql, mixed $bindings = [], string $boolean = 'and') Add a raw where clause to the query. Builder|Builder orWhereRaw(string $sql, mixed $bindings = []) Add a raw or where clause to the query. $this whereIn(string $column, mixed $values, string $boolean = 'and', bool $not = false) Add a "where in" clause to the query. Builder|Builder orWhereIn(string $column, mixed $values) Add an "or where in" clause to the query. Builder|Builder whereNotIn(string $column, mixed $values, string $boolean = 'and') Add a "where not in" clause to the query. Builder|Builder orWhereNotIn(string $column, mixed $values) Add an "or where not in" clause to the query. $this whereIntegerInRaw(string $column, Arrayable|array $values, string $boolean = 'and', bool $not = false) Add a "where in raw" clause for integer values to the query. $this whereIntegerNotInRaw(string $column, Arrayable|array $values, string $boolean = 'and') Add a "where not in raw" clause for integer values to the query. $this whereNull(string|array $columns, string $boolean = 'and', bool $not = false) Add a "where null" clause to the query. Builder|Builder orWhereNull(string $column) Add an "or where null" clause to the query. Builder|Builder whereNotNull(string|array $columns, string $boolean = 'and') Add a "where not null" clause to the query. $this whereBetween(string $column, array $values, string $boolean = 'and', bool $not = false) Add a where between statement to the query. Builder|Builder orWhereBetween(string $column, array $values) Add an or where between statement to the query. Builder|Builder whereNotBetween(string $column, array $values, string $boolean = 'and') Add a where not between statement to the query. Builder|Builder orWhereNotBetween(string $column, array $values) Add an or where not between statement to the query. Builder|Builder orWhereNotNull(string $column) Add an "or where not null" clause to the query. Builder|Builder whereDate(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and') Add a "where date" statement to the query. Builder|Builder orWhereDate(string $column, string $operator, DateTimeInterface|string|null $value = null) Add an "or where date" statement to the query. Builder|Builder whereTime(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and') Add a "where time" statement to the query. Builder|Builder orWhereTime(string $column, string $operator, DateTimeInterface|string|null $value = null) Add an "or where time" statement to the query. Builder|Builder whereDay(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and') Add a "where day" statement to the query. Builder|Builder orWhereDay(string $column, string $operator, DateTimeInterface|string|null $value = null) Add an "or where day" statement to the query. Builder|Builder whereMonth(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and') Add a "where month" statement to the query. Builder|Builder orWhereMonth(string $column, string $operator, DateTimeInterface|string|null $value = null) Add an "or where month" statement to the query. Builder|Builder whereYear(string $column, string $operator, DateTimeInterface|string|int|null $value = null, string $boolean = 'and') Add a "where year" statement to the query. Builder|Builder orWhereYear(string $column, string $operator, DateTimeInterface|string|int|null $value = null) Add an "or where year" statement to the query. $this addDateBasedWhere(string $type, string $column, string $operator, mixed $value, string $boolean = 'and') Add a date based (year, month, day, time) statement to the query. Builder|Builder whereNested(Closure $callback, string $boolean = 'and') Add a nested where statement to the query. Builder forNestedWhere() Create a new query instance for nested where condition. $this addNestedWhereQuery(Builder|Builder $query, string $boolean = 'and') Add another query builder as a nested where to the query builder. $this whereSub(string $column, string $operator, Closure $callback, string $boolean) Add a full sub-select to the query. $this whereExists(Closure $callback, string $boolean = 'and', bool $not = false) Add an exists clause to the query. Builder|Builder orWhereExists(Closure $callback, bool $not = false) Add an or exists clause to the query. Builder|Builder whereNotExists(Closure $callback, string $boolean = 'and') Add a where not exists clause to the query. Builder|Builder orWhereNotExists(Closure $callback) Add a where not exists clause to the query. $this addWhereExistsQuery(Builder $query, string $boolean = 'and', bool $not = false) Add an exists clause to the query. $this whereRowValues(array $columns, string $operator, array $values, string $boolean = 'and') Adds a where condition using row values. $this orWhereRowValues(array $columns, string $operator, array $values) Adds a or where condition using row values. $this whereJsonContains(string $column, mixed $value, string $boolean = 'and', bool $not = false) Add a "where JSON contains" clause to the query. $this orWhereJsonContains(string $column, mixed $value) Add a "or where JSON contains" clause to the query. $this whereJsonDoesntContain(string $column, mixed $value, string $boolean = 'and') Add a "where JSON not contains" clause to the query. $this orWhereJsonDoesntContain(string $column, mixed $value) Add a "or where JSON not contains" clause to the query. $this whereJsonLength(string $column, mixed $operator, mixed $value = null, string $boolean = 'and') Add a "where JSON length" clause to the query. $this orWhereJsonLength(string $column, mixed $operator, mixed $value = null) Add a "or where JSON length" clause to the query. $this dynamicWhere(string $method, array $parameters) Handles dynamic "where" clauses to the query. void addDynamic(string $segment, string $connector, array $parameters, int $index) Add a single dynamic where clause statement to the query. $this groupBy(array|string ...$groups) Add a "group by" clause to the query. $this groupByRaw(string $sql, array $bindings = []) Add a raw groupBy clause to the query. $this having(string $column, string|null $operator = null, string|null $value = null, string $boolean = 'and') Add a "having" clause to the query. Builder|Builder orHaving(string $column, string|null $operator = null, string|null $value = null) Add a "or having" clause to the query. Builder|Builder havingBetween(string $column, array $values, string $boolean = 'and', bool $not = false) Add a "having between " clause to the query. $this havingRaw(string $sql, array $bindings = [], string $boolean = 'and') Add a raw having clause to the query. Builder|Builder orHavingRaw(string $sql, array $bindings = []) Add a raw or having clause to the query. $this orderBy(Closure|Builder|Expression|string $column, string $direction = 'asc') Add an "order by" clause to the query. $this orderByDesc(string $column) Add a descending "order by" clause to the query. Builder|Builder latest(string $column = 'created_at') Add an "order by" clause for a timestamp to the query. Builder|Builder oldest(string $column = 'created_at') Add an "order by" clause for a timestamp to the query. $this inRandomOrder(string $seed = '') Put the query's results in random order. $this orderByRaw(string $sql, array $bindings = []) Add a raw "order by" clause to the query. Builder|Builder skip(int $value) Alias to set the "offset" value of the query. $this offset(int $value) Set the "offset" value of the query. Builder|Builder take(int $value) Alias to set the "limit" value of the query. $this limit(int $value) Set the "limit" value of the query. Builder|Builder forPage(int $page, int $perPage = 15) Set the limit and offset for a given page. Builder|Builder forPageBeforeId(int $perPage = 15, int|null $lastId = 0, string $column = 'id') Constrain the query to the previous "page" of results before a given ID. Builder|Builder forPageAfterId(int $perPage = 15, int|null $lastId = 0, string $column = 'id') Constrain the query to the next "page" of results after a given ID. array removeExistingOrdersFor(string $column) Get an array with all orders with a given column removed. Builder|Builder union(Builder|Closure $query, bool $all = false) Add a union statement to the query. Builder|Builder unionAll(Builder|Closure $query) Add a union all statement to the query. $this lock(string|bool $value = true) Lock the selected rows in the table. Builder lockForUpdate() Lock the selected rows in the table for updating. Builder sharedLock() Share lock the selected rows in the table. string toSql() Get the SQL representation of the query. mixed|Builder find(int|string $id, array $columns = ['*']) Execute a query for a single record by ID. mixed value(string $column) Get a single column's value from the first result of a query. Collection get(array|string $columns = ['*']) Execute the query as a "select" statement. array runSelect() Run the query as a "select" statement against the connection. LengthAwarePaginator paginate(int $perPage = 15, array $columns = ['*'], string $pageName = 'page', int|null $page = null) Paginate the given query into a simple paginator. Paginator simplePaginate(int $perPage = 15, array $columns = ['*'], string $pageName = 'page', int|null $page = null) Get a paginator only supporting simple next and previous links. int getCountForPagination(array $columns = ['*']) Get the count of the total records for the paginator. array runPaginationCountQuery(array $columns = ['*']) Run a pagination count query. array withoutSelectAliases(array $columns) Remove the column aliases since they will break count queries. LazyCollection cursor() Get a lazy collection for the given query. void enforceOrderBy() Throw an exception if the query doesn't have an orderBy clause. Collection pluck(string $column, string|null $key = null) Get an array with the values of a given column. string|null stripTableForPluck(string $column) Strip off the table name or alias from a column identifier. Collection pluckFromObjectColumn(array $queryResult, string $column, string $key) Retrieve column values from rows represented as objects. Collection pluckFromArrayColumn(array $queryResult, string $column, string $key) Retrieve column values from rows represented as arrays. string implode(string $column, string $glue = '') Concatenate values of a given column as a string. bool exists() Determine if any rows exist for the current query. bool doesntExist() Determine if no rows exist for the current query. mixed existsOr(Closure $callback) Execute the given callback if no rows exist for the current query. mixed doesntExistOr(Closure $callback) Execute the given callback if rows exist for the current query. int count(string $columns = '*') Retrieve the "count" result of the query. mixed min(string $column) Retrieve the minimum value of a given column. mixed max(string $column) Retrieve the maximum value of a given column. mixed sum(string $column) Retrieve the sum of the values of a given column. mixed avg(string $column) Retrieve the average of the values of a given column. mixed average(string $column) Alias for the "avg" method. mixed aggregate(string $function, array $columns = ['*']) Execute an aggregate function on the database. float|int numericAggregate(string $function, array $columns = ['*']) Execute a numeric aggregate function on the database. $this setAggregate(string $function, array $columns) Set the aggregate property without running the query. mixed onceWithColumns(array $columns, callable $callback) Execute the given callback while selecting the given columns. bool insert(array $values) Insert a new record into the database. int insertOrIgnore(array $values) Insert a new record into the database while ignoring errors. int insertGetId(array $values, string|null $sequence = null) Insert a new record and get the value of the primary key. int insertUsing(array $columns, Closure|Builder|string $query) Insert new records into the table using a subquery. int update(array $values) Update a record in the database. bool updateOrInsert(array $attributes, array $values = []) Insert or update a record matching the attributes, and fill it with values. int increment(string $column, float|int $amount = 1, array $extra = []) Increment a column's value by a given amount. int decrement(string $column, float|int $amount = 1, array $extra = []) Decrement a column's value by a given amount. int delete(mixed $id = null) Delete a record from the database. void truncate() Run a truncate statement on the table. Builder newQuery() Get a new instance of the query builder. Builder forSubQuery() Create a new query instance for a sub-query. Expression raw(mixed $value) Create a raw database expression. array getBindings() Get the current query value bindings in a flattened array. array getRawBindings() Get the raw array of bindings. $this setBindings(array $bindings, string $type = 'where') Set the bindings on the query builder. $this addBinding(mixed $value, string $type = 'where') Add a binding to the query. $this mergeBindings(Builder $query) Merge an array of bindings into our bindings. array cleanBindings(array $bindings) Remove all of the expressions from a list of bindings. string defaultKeyName() Get the default key name of the table. ConnectionInterface getConnection() Get the database connection instance. Processor getProcessor() Get the database query processor instance. Grammar getGrammar() Get the query grammar instance. $this useWritePdo() Use the write pdo for query. bool isQueryable(mixed $value) Determine if the value is a query builder instance or a Closure. Builder cloneWithout(array $properties) Clone the query without the given properties. Builder cloneWithoutBindings(array $except) Clone the query without the given bindings. $this dump() Dump the current SQL and bindings. void dd() Die and dump the current SQL and bindings. Details bool
chunk(int $count, callable $callback)
Chunk the results of the query. Parameters int $count callable $callback Return Value bool bool
each(callable $callback, int $count = 1000)
Execute a callback over each item while chunking. Parameters callable $callback int $count Return Value bool bool
chunkById(int $count, callable $callback, string|null $column = null, string|null $alias = null)
Chunk the results of a query by comparing IDs. Parameters int $count callable $callback string|null $column string|null $alias Return Value bool bool
eachById(callable $callback, int $count = 1000, string|null $column = null, string|null $alias = null)
Execute a callback over each item while chunking by id. Parameters callable $callback int $count string|null $column string|null $alias Return Value bool Model|object|BuildsQueries|null
first(array|string $columns = ['*'])
Execute the query and get the first result. Parameters array|string $columns Return Value
Model|object|BuildsQueries|null mixed|$this
when(mixed $value, callable $callback, callable|null $default = null)
Apply the callback's query changes if the given "value" is true. Parameters mixed $value callable $callback callable|null $default Return Value mixed|$this $this
tap(callable $callback)
Pass the query to a given callback. Parameters callable $callback Return Value $this mixed|$this
unless(mixed $value, callable $callback, callable|null $default = null)
Apply the callback's query changes if the given "value" is false. Parameters mixed $value callable $callback callable|null $default Return Value mixed|$this protected LengthAwarePaginator
paginator(Collection $items, int $total, int $perPage, int $currentPage, array $options)
Create a new length-aware paginator instance. Parameters Collection $items int $total int $perPage int $currentPage array $options Return Value LengthAwarePaginator protected Paginator
simplePaginator(Collection $items, int $perPage, int $currentPage, array $options)
Create a new simple paginator instance. Parameters Collection $items int $perPage int $currentPage array $options Return Value Paginator protected mixed
forwardCallTo(mixed $object, string $method, array $parameters)
Forward a method call to the given object. Parameters mixed $object string $method array $parameters Return Value mixed Exceptions BadMethodCallException static protected void
throwBadMethodCallException(string $method)
Throw a bad method call exception for the given method. Parameters string $method Return Value void Exceptions BadMethodCallException static void
macro(string $name, object|callable $macro)
Register a custom macro. Parameters string $name object|callable $macro Return Value void static void
mixin(object $mixin, bool $replace = true)
Mix another object into the class. Parameters object $mixin bool $replace Return Value void Exceptions ReflectionException static bool
hasMacro(string $name)
Checks if macro is registered. Parameters string $name Return Value bool static mixed
__callStatic(string $method, array $parameters)
Dynamically handle calls to the class. Parameters string $method array $parameters Return Value mixed Exceptions BadMethodCallException mixed
__call(string $method, array $parameters)
Handle dynamic method calls into the method. Parameters string $method array $parameters Return Value mixed Exceptions BadMethodCallException void
__construct(ConnectionInterface $connection, Grammar $grammar = null, Processor $processor = null)
Create a new query builder instance. Parameters ConnectionInterface $connection Grammar $grammar Processor $processor Return Value void $this
select(array|mixed $columns = ['*'])
Set the columns to be selected. Parameters array|mixed $columns Return Value $this Builder|Builder
selectSub(Closure|$this|string $query, string $as)
Add a subselect expression to the query. Parameters
Closure|$this|string $query string $as Return Value
Builder|Builder
Exceptions InvalidArgumentException Builder|Builder
selectRaw(string $expression, array $bindings = [])
Add a new "raw" select expression to the query. Parameters string $expression array $bindings Return Value
Builder|Builder
Builder|Builder
fromSub(Closure|Builder|string $query, string $as)
Makes "from" fetch from a subquery. Parameters
Closure|Builder|string $query string $as Return Value
Builder|Builder
Exceptions InvalidArgumentException Builder|Builder
fromRaw(string $expression, mixed $bindings = [])
Add a raw from clause to the query. Parameters string $expression mixed $bindings Return Value
Builder|Builder
protected array
createSub(Closure|Builder|string $query)
Creates a subquery and parse it. Parameters
Closure|Builder|string $query Return Value array protected array
parseSub(mixed $query)
Parse the subquery into SQL and bindings. Parameters mixed $query Return Value array Exceptions InvalidArgumentException $this
addSelect(array|mixed $column)
Add a new select column to the query. Parameters array|mixed $column Return Value $this $this
distinct()
Force the query to only return distinct results. Return Value $this $this
from(Closure|Builder|string $table, string|null $as = null)
Set the table which the query is targeting. Parameters
Closure|Builder|string $table string|null $as Return Value $this $this
join(string $table, Closure|string $first, string|null $operator = null, string|null $second = null, string $type = 'inner', bool $where = false)
Add a join clause to the query. Parameters string $table
Closure|string $first string|null $operator string|null $second string $type bool $where Return Value $this Builder|Builder
joinWhere(string $table, Closure|string $first, string $operator, string $second, string $type = 'inner')
Add a "join where" clause to the query. Parameters string $table
Closure|string $first string $operator string $second string $type Return Value
Builder|Builder
Builder|Builder
joinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null, string $type = 'inner', bool $where = false)
Add a subquery join clause to the query. Parameters
Closure|Builder|string $query string $as
Closure|string $first string|null $operator string|null $second string $type bool $where Return Value
Builder|Builder
Exceptions InvalidArgumentException Builder|Builder
leftJoin(string $table, Closure|string $first, string|null $operator = null, string|null $second = null)
Add a left join to the query. Parameters string $table
Closure|string $first string|null $operator string|null $second Return Value
Builder|Builder
Builder|Builder
leftJoinWhere(string $table, Closure|string $first, string $operator, string $second)
Add a "join where" clause to the query. Parameters string $table
Closure|string $first string $operator string $second Return Value
Builder|Builder
Builder|Builder
leftJoinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null)
Add a subquery left join to the query. Parameters
Closure|Builder|string $query string $as
Closure|string $first string|null $operator string|null $second Return Value
Builder|Builder
Builder|Builder
rightJoin(string $table, Closure|string $first, string|null $operator = null, string|null $second = null)
Add a right join to the query. Parameters string $table
Closure|string $first string|null $operator string|null $second Return Value
Builder|Builder
Builder|Builder
rightJoinWhere(string $table, Closure|string $first, string $operator, string $second)
Add a "right join where" clause to the query. Parameters string $table
Closure|string $first string $operator string $second Return Value
Builder|Builder
Builder|Builder
rightJoinSub(Closure|Builder|string $query, string $as, Closure|string $first, string|null $operator = null, string|null $second = null)
Add a subquery right join to the query. Parameters
Closure|Builder|string $query string $as
Closure|string $first string|null $operator string|null $second Return Value
Builder|Builder
Builder|Builder
crossJoin(string $table, Closure|string|null $first = null, string|null $operator = null, string|null $second = null)
Add a "cross join" clause to the query. Parameters string $table
Closure|string|null $first string|null $operator string|null $second Return Value
Builder|Builder
protected JoinClause
newJoinClause(Builder $parentQuery, string $type, string $table)
Get a new join clause. Parameters Builder $parentQuery string $type string $table Return Value JoinClause void
mergeWheres(array $wheres, array $bindings)
Merge an array of where clauses and bindings. Parameters array $wheres array $bindings Return Value void $this
where(Closure|string|array $column, mixed $operator = null, mixed $value = null, string $boolean = 'and')
Add a basic where clause to the query. Parameters
Closure|string|array $column mixed $operator mixed $value string $boolean Return Value $this protected $this
addArrayOfWheres(array $column, string $boolean, string $method = 'where')
Add an array of where clauses to the query. Parameters array $column string $boolean string $method Return Value $this array
prepareValueAndOperator(string $value, string $operator, bool $useDefault = false)
Prepare the value and operator for a where clause. Parameters string $value string $operator bool $useDefault Return Value array Exceptions InvalidArgumentException protected bool
invalidOperatorAndValue(string $operator, mixed $value)
Determine if the given operator and value combination is legal. Prevents using Null values with invalid operators. Parameters string $operator mixed $value Return Value bool protected bool
invalidOperator(string $operator)
Determine if the given operator is supported. Parameters string $operator Return Value bool Builder|Builder
orWhere(Closure|string|array $column, mixed $operator = null, mixed $value = null)
Add an "or where" clause to the query. Parameters
Closure|string|array $column mixed $operator mixed $value Return Value
Builder|Builder
Builder|Builder
whereColumn(string|array $first, string|null $operator = null, string|null $second = null, string|null $boolean = 'and')
Add a "where" clause comparing two columns to the query. Parameters string|array $first string|null $operator string|null $second string|null $boolean Return Value
Builder|Builder
Builder|Builder
orWhereColumn(string|array $first, string|null $operator = null, string|null $second = null)
Add an "or where" clause comparing two columns to the query. Parameters string|array $first string|null $operator string|null $second Return Value
Builder|Builder
$this
whereRaw(string $sql, mixed $bindings = [], string $boolean = 'and')
Add a raw where clause to the query. Parameters string $sql mixed $bindings string $boolean Return Value $this Builder|Builder
orWhereRaw(string $sql, mixed $bindings = [])
Add a raw or where clause to the query. Parameters string $sql mixed $bindings Return Value
Builder|Builder
$this
whereIn(string $column, mixed $values, string $boolean = 'and', bool $not = false)
Add a "where in" clause to the query. Parameters string $column mixed $values string $boolean bool $not Return Value $this Builder|Builder
orWhereIn(string $column, mixed $values)
Add an "or where in" clause to the query. Parameters string $column mixed $values Return Value
Builder|Builder
Builder|Builder
whereNotIn(string $column, mixed $values, string $boolean = 'and')
Add a "where not in" clause to the query. Parameters string $column mixed $values string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereNotIn(string $column, mixed $values)
Add an "or where not in" clause to the query. Parameters string $column mixed $values Return Value
Builder|Builder
$this
whereIntegerInRaw(string $column, Arrayable|array $values, string $boolean = 'and', bool $not = false)
Add a "where in raw" clause for integer values to the query. Parameters string $column
Arrayable|array $values string $boolean bool $not Return Value $this $this
whereIntegerNotInRaw(string $column, Arrayable|array $values, string $boolean = 'and')
Add a "where not in raw" clause for integer values to the query. Parameters string $column
Arrayable|array $values string $boolean Return Value $this $this
whereNull(string|array $columns, string $boolean = 'and', bool $not = false)
Add a "where null" clause to the query. Parameters string|array $columns string $boolean bool $not Return Value $this Builder|Builder
orWhereNull(string $column)
Add an "or where null" clause to the query. Parameters string $column Return Value
Builder|Builder
Builder|Builder
whereNotNull(string|array $columns, string $boolean = 'and')
Add a "where not null" clause to the query. Parameters string|array $columns string $boolean Return Value
Builder|Builder
$this
whereBetween(string $column, array $values, string $boolean = 'and', bool $not = false)
Add a where between statement to the query. Parameters string $column array $values string $boolean bool $not Return Value $this Builder|Builder
orWhereBetween(string $column, array $values)
Add an or where between statement to the query. Parameters string $column array $values Return Value
Builder|Builder
Builder|Builder
whereNotBetween(string $column, array $values, string $boolean = 'and')
Add a where not between statement to the query. Parameters string $column array $values string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereNotBetween(string $column, array $values)
Add an or where not between statement to the query. Parameters string $column array $values Return Value
Builder|Builder
Builder|Builder
orWhereNotNull(string $column)
Add an "or where not null" clause to the query. Parameters string $column Return Value
Builder|Builder
Builder|Builder
whereDate(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and')
Add a "where date" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereDate(string $column, string $operator, DateTimeInterface|string|null $value = null)
Add an "or where date" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value Return Value
Builder|Builder
Builder|Builder
whereTime(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and')
Add a "where time" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereTime(string $column, string $operator, DateTimeInterface|string|null $value = null)
Add an "or where time" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value Return Value
Builder|Builder
Builder|Builder
whereDay(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and')
Add a "where day" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereDay(string $column, string $operator, DateTimeInterface|string|null $value = null)
Add an "or where day" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value Return Value
Builder|Builder
Builder|Builder
whereMonth(string $column, string $operator, DateTimeInterface|string|null $value = null, string $boolean = 'and')
Add a "where month" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereMonth(string $column, string $operator, DateTimeInterface|string|null $value = null)
Add an "or where month" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|null $value Return Value
Builder|Builder
Builder|Builder
whereYear(string $column, string $operator, DateTimeInterface|string|int|null $value = null, string $boolean = 'and')
Add a "where year" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|int|null $value string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereYear(string $column, string $operator, DateTimeInterface|string|int|null $value = null)
Add an "or where year" statement to the query. Parameters string $column string $operator
DateTimeInterface|string|int|null $value Return Value
Builder|Builder
protected $this
addDateBasedWhere(string $type, string $column, string $operator, mixed $value, string $boolean = 'and')
Add a date based (year, month, day, time) statement to the query. Parameters string $type string $column string $operator mixed $value string $boolean Return Value $this Builder|Builder
whereNested(Closure $callback, string $boolean = 'and')
Add a nested where statement to the query. Parameters Closure $callback string $boolean Return Value
Builder|Builder
Builder
forNestedWhere()
Create a new query instance for nested where condition. Return Value Builder $this
addNestedWhereQuery(Builder|Builder $query, string $boolean = 'and')
Add another query builder as a nested where to the query builder. Parameters
Builder|Builder
$query string $boolean Return Value $this protected $this
whereSub(string $column, string $operator, Closure $callback, string $boolean)
Add a full sub-select to the query. Parameters string $column string $operator Closure $callback string $boolean Return Value $this $this
whereExists(Closure $callback, string $boolean = 'and', bool $not = false)
Add an exists clause to the query. Parameters Closure $callback string $boolean bool $not Return Value $this Builder|Builder
orWhereExists(Closure $callback, bool $not = false)
Add an or exists clause to the query. Parameters Closure $callback bool $not Return Value
Builder|Builder
Builder|Builder
whereNotExists(Closure $callback, string $boolean = 'and')
Add a where not exists clause to the query. Parameters Closure $callback string $boolean Return Value
Builder|Builder
Builder|Builder
orWhereNotExists(Closure $callback)
Add a where not exists clause to the query. Parameters Closure $callback Return Value
Builder|Builder
$this
addWhereExistsQuery(Builder $query, string $boolean = 'and', bool $not = false)
Add an exists clause to the query. Parameters Builder $query string $boolean bool $not Return Value $this $this
whereRowValues(array $columns, string $operator, array $values, string $boolean = 'and')
Adds a where condition using row values. Parameters array $columns string $operator array $values string $boolean Return Value $this Exceptions InvalidArgumentException $this
orWhereRowValues(array $columns, string $operator, array $values)
Adds a or where condition using row values. Parameters array $columns string $operator array $values Return Value $this $this
whereJsonContains(string $column, mixed $value, string $boolean = 'and', bool $not = false)
Add a "where JSON contains" clause to the query. Parameters string $column mixed $value string $boolean bool $not Return Value $this $this
orWhereJsonContains(string $column, mixed $value)
Add a "or where JSON contains" clause to the query. Parameters string $column mixed $value Return Value $this $this
whereJsonDoesntContain(string $column, mixed $value, string $boolean = 'and')
Add a "where JSON not contains" clause to the query. Parameters string $column mixed $value string $boolean Return Value $this $this
orWhereJsonDoesntContain(string $column, mixed $value)
Add a "or where JSON not contains" clause to the query. Parameters string $column mixed $value Return Value $this $this
whereJsonLength(string $column, mixed $operator, mixed $value = null, string $boolean = 'and')
Add a "where JSON length" clause to the query. Parameters string $column mixed $operator mixed $value string $boolean Return Value $this $this
orWhereJsonLength(string $column, mixed $operator, mixed $value = null)
Add a "or where JSON length" clause to the query. Parameters string $column mixed $operator mixed $value Return Value $this $this
dynamicWhere(string $method, array $parameters)
Handles dynamic "where" clauses to the query. Parameters string $method array $parameters Return Value $this protected void
addDynamic(string $segment, string $connector, array $parameters, int $index)
Add a single dynamic where clause statement to the query. Parameters string $segment string $connector array $parameters int $index Return Value void $this
groupBy(array|string ...$groups)
Add a "group by" clause to the query. Parameters array|string ...$groups Return Value $this $this
groupByRaw(string $sql, array $bindings = [])
Add a raw groupBy clause to the query. Parameters string $sql array $bindings Return Value $this $this
having(string $column, string|null $operator = null, string|null $value = null, string $boolean = 'and')
Add a "having" clause to the query. Parameters string $column string|null $operator string|null $value string $boolean Return Value $this Builder|Builder
orHaving(string $column, string|null $operator = null, string|null $value = null)
Add a "or having" clause to the query. Parameters string $column string|null $operator string|null $value Return Value
Builder|Builder
Builder|Builder
havingBetween(string $column, array $values, string $boolean = 'and', bool $not = false)
Add a "having between " clause to the query. Parameters string $column array $values string $boolean bool $not Return Value
Builder|Builder
$this
havingRaw(string $sql, array $bindings = [], string $boolean = 'and')
Add a raw having clause to the query. Parameters string $sql array $bindings string $boolean Return Value $this Builder|Builder
orHavingRaw(string $sql, array $bindings = [])
Add a raw or having clause to the query. Parameters string $sql array $bindings Return Value
Builder|Builder
$this
orderBy(Closure|Builder|Expression|string $column, string $direction = 'asc')
Add an "order by" clause to the query. Parameters
Closure|Builder|Expression|string $column string $direction Return Value $this Exceptions InvalidArgumentException $this
orderByDesc(string $column)
Add a descending "order by" clause to the query. Parameters string $column Return Value $this Builder|Builder
latest(string $column = 'created_at')
Add an "order by" clause for a timestamp to the query. Parameters string $column Return Value
Builder|Builder
Builder|Builder
oldest(string $column = 'created_at')
Add an "order by" clause for a timestamp to the query. Parameters string $column Return Value
Builder|Builder
$this
inRandomOrder(string $seed = '')
Put the query's results in random order. Parameters string $seed Return Value $this $this
orderByRaw(string $sql, array $bindings = [])
Add a raw "order by" clause to the query. Parameters string $sql array $bindings Return Value $this Builder|Builder
skip(int $value)
Alias to set the "offset" value of the query. Parameters int $value Return Value
Builder|Builder
$this
offset(int $value)
Set the "offset" value of the query. Parameters int $value Return Value $this Builder|Builder
take(int $value)
Alias to set the "limit" value of the query. Parameters int $value Return Value
Builder|Builder
$this
limit(int $value)
Set the "limit" value of the query. Parameters int $value Return Value $this Builder|Builder
forPage(int $page, int $perPage = 15)
Set the limit and offset for a given page. Parameters int $page int $perPage Return Value
Builder|Builder
Builder|Builder
forPageBeforeId(int $perPage = 15, int|null $lastId = 0, string $column = 'id')
Constrain the query to the previous "page" of results before a given ID. Parameters int $perPage int|null $lastId string $column Return Value
Builder|Builder
Builder|Builder
forPageAfterId(int $perPage = 15, int|null $lastId = 0, string $column = 'id')
Constrain the query to the next "page" of results after a given ID. Parameters int $perPage int|null $lastId string $column Return Value
Builder|Builder
protected array
removeExistingOrdersFor(string $column)
Get an array with all orders with a given column removed. Parameters string $column Return Value array Builder|Builder
union(Builder|Closure $query, bool $all = false)
Add a union statement to the query. Parameters
Builder|Closure
$query bool $all Return Value
Builder|Builder
Builder|Builder
unionAll(Builder|Closure $query)
Add a union all statement to the query. Parameters
Builder|Closure
$query Return Value
Builder|Builder
$this
lock(string|bool $value = true)
Lock the selected rows in the table. Parameters string|bool $value Return Value $this Builder
lockForUpdate()
Lock the selected rows in the table for updating. Return Value Builder Builder
sharedLock()
Share lock the selected rows in the table. Return Value Builder string
toSql()
Get the SQL representation of the query. Return Value string mixed|Builder
find(int|string $id, array $columns = ['*'])
Execute a query for a single record by ID. Parameters int|string $id array $columns Return Value mixed|Builder
mixed
value(string $column)
Get a single column's value from the first result of a query. Parameters string $column Return Value mixed Collection
get(array|string $columns = ['*'])
Execute the query as a "select" statement. Parameters array|string $columns Return Value Collection protected array
runSelect()
Run the query as a "select" statement against the connection. Return Value array LengthAwarePaginator
paginate(int $perPage = 15, array $columns = ['*'], string $pageName = 'page', int|null $page = null)
Paginate the given query into a simple paginator. Parameters int $perPage array $columns string $pageName int|null $page Return Value LengthAwarePaginator Paginator
simplePaginate(int $perPage = 15, array $columns = ['*'], string $pageName = 'page', int|null $page = null)
Get a paginator only supporting simple next and previous links. This is more efficient on larger data-sets, etc. Parameters int $perPage array $columns string $pageName int|null $page Return Value Paginator int
getCountForPagination(array $columns = ['*'])
Get the count of the total records for the paginator. Parameters array $columns Return Value int protected array
runPaginationCountQuery(array $columns = ['*'])
Run a pagination count query. Parameters array $columns Return Value array protected array
withoutSelectAliases(array $columns)
Remove the column aliases since they will break count queries. Parameters array $columns Return Value array LazyCollection
cursor()
Get a lazy collection for the given query. Return Value LazyCollection protected void
enforceOrderBy()
Throw an exception if the query doesn't have an orderBy clause. Return Value void Exceptions RuntimeException Collection
pluck(string $column, string|null $key = null)
Get an array with the values of a given column. Parameters string $column string|null $key Return Value Collection protected string|null
stripTableForPluck(string $column)
Strip off the table name or alias from a column identifier. Parameters string $column Return Value string|null protected Collection
pluckFromObjectColumn(array $queryResult, string $column, string $key)
Retrieve column values from rows represented as objects. Parameters array $queryResult string $column string $key Return Value Collection protected Collection
pluckFromArrayColumn(array $queryResult, string $column, string $key)
Retrieve column values from rows represented as arrays. Parameters array $queryResult string $column string $key Return Value Collection string
implode(string $column, string $glue = '')
Concatenate values of a given column as a string. Parameters string $column string $glue Return Value string bool
exists()
Determine if any rows exist for the current query. Return Value bool bool
doesntExist()
Determine if no rows exist for the current query. Return Value bool mixed
existsOr(Closure $callback)
Execute the given callback if no rows exist for the current query. Parameters Closure $callback Return Value mixed mixed
doesntExistOr(Closure $callback)
Execute the given callback if rows exist for the current query. Parameters Closure $callback Return Value mixed int
count(string $columns = '*')
Retrieve the "count" result of the query. Parameters string $columns Return Value int mixed
min(string $column)
Retrieve the minimum value of a given column. Parameters string $column Return Value mixed mixed
max(string $column)
Retrieve the maximum value of a given column. Parameters string $column Return Value mixed mixed
sum(string $column)
Retrieve the sum of the values of a given column. Parameters string $column Return Value mixed mixed
avg(string $column)
Retrieve the average of the values of a given column. Parameters string $column Return Value mixed mixed
average(string $column)
Alias for the "avg" method. Parameters string $column Return Value mixed mixed
aggregate(string $function, array $columns = ['*'])
Execute an aggregate function on the database. Parameters string $function array $columns Return Value mixed float|int
numericAggregate(string $function, array $columns = ['*'])
Execute a numeric aggregate function on the database. Parameters string $function array $columns Return Value float|int protected $this
setAggregate(string $function, array $columns)
Set the aggregate property without running the query. Parameters string $function array $columns Return Value $this protected mixed
onceWithColumns(array $columns, callable $callback)
Execute the given callback while selecting the given columns. After running the callback, the columns are reset to the original value. Parameters array $columns callable $callback Return Value mixed bool
insert(array $values)
Insert a new record into the database. Parameters array $values Return Value bool int
insertOrIgnore(array $values)
Insert a new record into the database while ignoring errors. Parameters array $values Return Value int int
insertGetId(array $values, string|null $sequence = null)
Insert a new record and get the value of the primary key. Parameters array $values string|null $sequence Return Value int int
insertUsing(array $columns, Closure|Builder|string $query)
Insert new records into the table using a subquery. Parameters array $columns
Closure|Builder|string $query Return Value int int
update(array $values)
Update a record in the database. Parameters array $values Return Value int bool
updateOrInsert(array $attributes, array $values = [])
Insert or update a record matching the attributes, and fill it with values. Parameters array $attributes array $values Return Value bool int
increment(string $column, float|int $amount = 1, array $extra = [])
Increment a column's value by a given amount. Parameters string $column float|int $amount array $extra Return Value int Exceptions InvalidArgumentException int
decrement(string $column, float|int $amount = 1, array $extra = [])
Decrement a column's value by a given amount. Parameters string $column float|int $amount array $extra Return Value int Exceptions InvalidArgumentException int
delete(mixed $id = null)
Delete a record from the database. Parameters mixed $id Return Value int void
truncate()
Run a truncate statement on the table. Return Value void Builder
newQuery()
Get a new instance of the query builder. Return Value Builder protected Builder
forSubQuery()
Create a new query instance for a sub-query. Return Value Builder Expression
raw(mixed $value)
Create a raw database expression. Parameters mixed $value Return Value Expression array
getBindings()
Get the current query value bindings in a flattened array. Return Value array array
getRawBindings()
Get the raw array of bindings. Return Value array $this
setBindings(array $bindings, string $type = 'where')
Set the bindings on the query builder. Parameters array $bindings string $type Return Value $this Exceptions InvalidArgumentException $this
addBinding(mixed $value, string $type = 'where')
Add a binding to the query. Parameters mixed $value string $type Return Value $this Exceptions InvalidArgumentException $this
mergeBindings(Builder $query)
Merge an array of bindings into our bindings. Parameters Builder $query Return Value $this protected array
cleanBindings(array $bindings)
Remove all of the expressions from a list of bindings. Parameters array $bindings Return Value array protected string
defaultKeyName()
Get the default key name of the table. Return Value string ConnectionInterface
getConnection()
Get the database connection instance. Return Value ConnectionInterface Processor
getProcessor()
Get the database query processor instance. Return Value Processor Grammar
getGrammar()
Get the query grammar instance. Return Value Grammar $this
useWritePdo()
Use the write pdo for query. Return Value $this protected bool
isQueryable(mixed $value)
Determine if the value is a query builder instance or a Closure. Parameters mixed $value Return Value bool Builder
cloneWithout(array $properties)
Clone the query without the given properties. Parameters array $properties Return Value Builder Builder
cloneWithoutBindings(array $except)
Clone the query without the given bindings. Parameters array $except Return Value Builder $this
dump()
Dump the current SQL and bindings. Return Value $this void
dd()
Die and dump the current SQL and bindings. Return Value void
|
dart:core
List.from factory constructor List.from(Iterable elements, { bool growable: true }) Creates a list containing all elements. The Iterator of elements provides the order of the elements. This constructor returns a growable list when growable is true; otherwise, it returns a fixed-length list. Source external factory List.from(Iterable elements, {bool growable: true});
|
Scene Graph Adaptations Scene Graph Adaptations in Qt Quick
Originally, Qt Quick always relied on OpenGL (OpenGL ES 2.0 or OpenGL 2.0) to parse the scene graph and render the results to a render target From Qt 5.8 onwards, Qt Quick also supports rendering in software, with OpenVG, and with Direct3D 12. This is realized by having additional scene graph adaptations, either in form of plugins (d3d12, openvg) or built-in to the Qt Quick library (software). The default adaptation continues to rely directly on OpenGL. From Qt 5.14 onwards, the default adaptation gains the option of rendering via a graphics abstraction layer, the Qt Rendering Hardware Interface (RHI), provided by the QtGui module. When enabled, no direct OpenGL calls are made. Rather, the scene graph renders by using the APIs provided by the abstraction layer, which is then translated into OpenGL, Vulkan, Metal, or Direct 3D calls. Shader handling is also unified by writing shader code once, compiling to SPIR-V, and then translating to the language appropriate for the various graphics APIs. Switch Between Adaptations in Your Application
Unlike software or d3d12, the RHI-based renderer is not an additional adaptation, and is always built-in. As of Qt 5.14 it can be enabled by setting the environment variable QSG_RHI to a non-zero value before starting the application, or via QQuickWindow8b7c:f320:99b9:690f:4595:cd17:293a:c069setSceneGraphBackend() in combination with QSGRendererInter8b7c:f320:99b9:690f:4595:cd17:293a:c069GraphicsApi. When none of this is done, OpenGL is used directly like in previous versions. Switching to a different adaptation can be achieved in two ways: Use an environment variable - Set the QT_QUICK_BACKEND or the legacy QMLSCENE_DEVICE environment variable before launching applications. Use a C++ API - Call QQuickWindow8b7c:f320:99b9:690f:4595:cd17:293a:c069setSceneGraphBackend() early on in the application's main() function. The following backends are supported: Default - Request with the "" string or a QSGRendererInter8b7c:f320:99b9:690f:4595:cd17:293a:c069GraphicsApi enum value different than the ones listed below. Software - Request with the "software" string or the QSGRendererInter8b7c:f320:99b9:690f:4595:cd17:293a:c069Software enum value. Direct3D 12 - Request with the "d3d12" string or the QSGRendererInter8b7c:f320:99b9:690f:4595:cd17:293a:c069Direct3D12 enum value.
OpenVG - Request with the "openvg" string or the QSGRendererInter8b7c:f320:99b9:690f:4595:cd17:293a:c069OpenVG enum value. To find out which backend is in use, you can enable basic scene graph information logging via the QSG_INFO environment variable or the qt.scenegraph.general logging category. This results in some information being printed onto the debug output, during application startup. Note: In Qt builds with OpenGL disabled, the default adaptation is software. This may change in future releases.
Note: Typically, adaptations other than the default one come with a set of limitations as they are unlikely to provide a feature set that's 100% compatible with OpenGL. However, these adaptations may provide their own specific advantages in certain areas. For more information on the various adaptations, refer to the sections below.
Default Adaptation
When using OpenGL directly, the default adaptation is capable of providing the full Qt Quick 2 feature set. For more details, see Default Adaptation. When using OpenGL, Vulkan, Metal, or Direct 3D via the RHI, the default adaptation is capable of providing most features, including the full batching renderer described in Default Adaptation, but some additional features may not be available as of Qt 5.14. Software Adaptation
The Software adaptation is an alternative renderer for Qt Quick 2 that uses the raster paint engine to render the contents of the scene graph. For more details, see Software Adaptation. Direct3D 12 (experimental)
The Direct3D 12 adaptation is an alternative renderer for Qt Quick 2 when running on Windows 10, both for Win32 and UWP applications. For more details, see Direct3D 12 Adaptation. OpenVG
The OpenVG adaptation is an alternative renderer for Qt Quick 2 that renders the contents of the scene graph using OpenVG commands to provide hardware-accelerated 2D vector and raster graphics. For more details, see OpenVG Adaptation.
|
love.data
Available since LÖVE 11.0 This module is not supported in earlier versions. Provides functionality for creating and transforming data. Types ByteData Data object containing arbitrary bytes in an contiguous memory. 11.0
CompressedData Byte data compressed using a specific algorithm. 0.10.0
Data The superclass of all data.
Functions love.data.compress Compresses a string or data using a specific compression algorithm. 11.0
love.data.decode Decode Data or a string from any of the EncodeFormats to Data or string. 11.0
love.data.decompress Decompresses a CompressedData or previously compressed string or Data object. 11.0
love.data.encode Encode Data or a string to a Data or string in one of the EncodeFormats. 11.0
love.data.getPackedSize Gets the size in bytes that a given format used with love.data.pack will use. 11.0
love.data.hash Compute message digest using specific hash algorithm. 11.0
love.data.newByteData Creates a new Data object containing arbitrary bytes. 11.0
love.data.newDataView Creates a new Data referencing a subsection of an existing Data object. 11.0
love.data.pack Packs (serializes) simple Lua values. 11.0
love.data.unpack Unpacks (deserializes) a byte-string or Data into simple Lua values. 11.0
Enums CompressedDataFormat Compressed data formats. 0.10.0
ContainerType Return type of data-returning functions. 11.0
EncodeFormat Encoding format used to encode or decode data. 11.0
HashFunction Hash algorithm of hash function. 11.0
See Also love
|
pandas.PeriodIndex.weekday propertyPeriodIndex.weekday[source]
The day of the week with Monday=0, Sunday=6.
|
interface_exists (PHP 5 >= 5.0.2, PHP 7, PHP 8)
interface_exists — Checks if the interface has been defined Description interface_exists(string $interface, bool $autoload = true): bool Checks if the given interface has been defined. Parameters
interface
The interface name autoload
Whether to call __autoload or not by default. Return Values Returns true if the interface given by interface has been defined, false otherwise. Examples
Example #1 interface_exists() example <?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// Methods
}
}
?> See Also
get_declared_interfaces() - Returns an array of all declared interfaces class_implements() - Return the interfaces which are implemented by the given class or interface class_exists() - Checks if the class has been defined enum_exists() - Checks if the enum has been defined
|
Angular elements overview Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way. For the sample app that this page describes, see the live example. Custom elements are a Web Platform feature currently supported by Chrome, Edge (Chromium-based), Firefox, Opera, and Safari, and available in other browsers through polyfills (see Browser Support). A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a CustomElementRegistry of defined custom elements, which maps an instantiable JavaScript class to an HTML tag. The @angular/elements package exports a createCustomElement() API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API. Transforming a component to a custom element makes all of the required Angular infrastructure available to the browser. Creating a custom element is simple and straightforward, and automatically connects your component-defined view with change detection and data binding, mapping Angular functionality to the corresponding native HTML equivalents. We are working on custom elements that can be used by web apps built on other frameworks. A minimal, self-contained version of the Angular framework will be injected as a service to support the component's change-detection and data-binding functionality. For more about the direction of development, check out this video presentation. Using custom elements Custom elements bootstrap themselves - they start automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions. Easy dynamic content in an Angular app Transforming a component to a custom element provides an easy path to creating dynamic HTML content in your Angular app. HTML content that you add directly to the DOM in an Angular app is normally displayed without Angular processing, unless you define a dynamic component, adding your own code to connect the HTML tag to your app data, and participate in change detection. With a custom element, all of that wiring is taken care of automatically. Content-rich applications If you have a content-rich app, such as the Angular app that presents this documentation, custom elements let you give your content providers sophisticated Angular functionality without requiring knowledge of Angular. For example, an Angular guide like this one is added directly to the DOM by the Angular navigation tools, but can include special elements like <code-snippet> that perform complex operations. All you need to tell your content provider is the syntax of your custom element. They don't need to know anything about Angular, or anything about your component's data structures or implementation. How it works Use the createCustomElement() function to convert a component into a class that can be registered with the browser as a custom element. After you register your configured class with the browser's custom-element registry, you can use the new element just like a built-in HTML element in content that you add directly into the DOM: <my-popup message="Use Angular!"></my-popup> When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM. The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data. Input properties in the component correspond to input attributes for the element. Transforming components to custom elements Angular provides the createCustomElement() function for converting an Angular component, together with its dependencies, to a custom element. The function collects the component's observable properties, along with the Angular functionality the browser needs to create and destroy instances, and to detect and respond to changes. The conversion process implements the NgElementConstructor interface, and creates a constructor class that is configured to produce a self-bootstrapping instance of your component. Use a JavaScript function, customElements.define(), to register the configured constructor and its associated custom-element tag with the browser's CustomElementRegistry. When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance. Mapping A custom element hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs. Component properties and logic maps directly into HTML attributes and the browser's event system. The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element. It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions. The resulting attribute names use dash-separated lowercase. For example, for a component with @Input('myInputProp') inputProp, the corresponding custom element defines an attribute my-input-prop. Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, for a component with @Output() valueChanged = new EventEmitter(), the corresponding custom element will dispatch events with the name "valueChanged", and the emitted data will be stored on the event’s detail property. If you provide an alias, that value is used; for example, @Output('myClick') clicks = new EventEmitter<string>(); results in dispatch events with the name "myClick". For more information, see Web Component documentation for Creating custom events. Browser support for custom elements The recently-developed custom elements Web Platform feature is currently supported natively in a number of browsers.
Browser Custom Element Support Chrome Supported natively. Edge (Chromium-based) Supported natively. Firefox Supported natively. Opera Supported natively. Safari Supported natively.
In browsers that support Custom Elements natively, the specification requires developers use ES2015 classes to define Custom Elements - developers can opt-in to this by setting the target: "es2015" property in their project's tsconfig.json. As Custom Element and ES2015 support may not be available in all browsers, developers can instead choose to use a polyfill to support older browsers and ES5 code. Use the Angular CLI to automatically set up your project with the correct polyfill: ng add @angular/elements --name=*your_project_name*. For more information about polyfills, see polyfill documentation. For more information about Angular browser support, see Browser Support. Example: A Popup Service Previously, when you wanted to add a component to an app at runtime, you had to define a dynamic component. The app module would have to list your dynamic component under entryComponents, so that the app wouldn't expect it to be present at startup, and then you would have to load it, attach it to an element in the DOM, and wire up all of the dependencies, change detection, and event handling, as described in Dynamic Component Loader. Using an Angular custom element makes the process much simpler and more transparent, by providing all of the infrastructure and framework automatically—all you have to do is define the kind of event handling you want. (You do still have to exclude the component from compilation, if you are not going to use it in your app.) The Popup Service example app (shown below) defines a component that you can either load dynamically or convert to a custom element.
popup.component.ts defines a simple pop-up element that displays an input message, with some animation and styling.
popup.service.ts creates an injectable service that provides two different ways to invoke the PopupComponent; as a dynamic component, or as a custom element. Notice how much more setup is required for the dynamic-loading method.
app.module.ts adds the PopupComponent in the module's entryComponents list, to exclude it from compilation and avoid startup warnings or errors.
app.component.ts defines the app's root component, which uses the PopupService to add the pop-up to the DOM at run time. When the app runs, the root component's constructor converts PopupComponent to a custom element. For comparison, the demo shows both methods. One button adds the popup using the dynamic-loading method, and the other uses the custom element. You can see that the result is the same; only the preparation is different. import { Component, EventEmitter, Input, Output } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'my-popup',
template: `
<span>Popup: {{message}}</span>
<button (click)="closed.next()">✖</button>
`,
host: {
'[@state]': 'state',
},
animations: [
trigger('state', [
state('opened', style({transform: 'translateY(0%)'})),
state('void, closed', style({transform: 'translateY(100%)', opacity: 0})),
transition('* => *', animate('100ms ease-in')),
])
],
styles: [`
:host {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: #009cff;
height: 48px;
padding: 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px solid black;
font-size: 24px;
}
button {
border-radius: 50%;
}
`]
})
export class PopupComponent {
state: 'opened' | 'closed' = 'closed';
@Input()
set message(message: string) {
this._message = message;
this.state = 'opened';
}
get message(): string { return this._message; }
_message: string;
@Output()
closed = new EventEmitter();
} import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core';
import { NgElement, WithProperties } from '@angular/elements';
import { PopupComponent } from './popup.component';
@Injectable()
export class PopupService {
constructor(private injector: Injector,
private applicationRef: ApplicationRef,
private componentFactoryResolver: ComponentFactoryResolver) {}
// Previous dynamic-loading method required you to set up infrastructure
// before adding the popup to the DOM.
showAsComponent(message: string) {
// Create element
const popup = document.createElement('popup-component');
// Create the component and wire it up with the element
const factory = this.componentFactoryResolver.resolveComponentFactory(PopupComponent);
const popupComponentRef = factory.create(this.injector, [], popup);
// Attach to the view so that the change detector knows to run
this.applicationRef.attachView(popupComponentRef.hostView);
// Listen to the close event
popupComponentRef.instance.closed.subscribe(() => {
document.body.removeChild(popup);
this.applicationRef.detachView(popupComponentRef.hostView);
});
// Set the message
popupComponentRef.instance.message = message;
// Add to the DOM
document.body.appendChild(popup);
}
// This uses the new custom-element method to add the popup to the DOM.
showAsElement(message: string) {
// Create element
const popupEl: NgElement & WithProperties<PopupComponent> = document.createElement('popup-element') as any;
// Listen to the close event
popupEl.addEventListener('closed', () => document.body.removeChild(popupEl));
// Set the message
popupEl.message = message;
// Add to the DOM
document.body.appendChild(popupEl);
}
} import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { PopupComponent } from './popup.component';
import { PopupService } from './popup.service';
// Include the `PopupService` provider,
// but exclude `PopupComponent` from compilation,
// because it will be added dynamically.
@NgModule({
imports: [BrowserModule, BrowserAnimationsModule],
providers: [PopupService],
declarations: [AppComponent, PopupComponent],
bootstrap: [AppComponent],
entryComponents: [PopupComponent],
})
export class AppModule {
} import { Component, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { PopupService } from './popup.service';
import { PopupComponent } from './popup.component';
@Component({
selector: 'app-root',
template: `
<input #input value="Message">
<button (click)="popup.showAsComponent(input.value)">Show as component</button>
<button (click)="popup.showAsElement(input.value)">Show as element</button>
`,
})
export class AppComponent {
constructor(injector: Injector, public popup: PopupService) {
// Convert `PopupComponent` to a custom element.
const PopupElement = createCustomElement(PopupComponent, {injector});
// Register the custom element with the browser.
customElements.define('popup-element', PopupElement);
}
} Typings for custom elements Generic DOM APIs, such as document.createElement() or document.querySelector(), return an element type that is appropriate for the specified arguments. For example, calling document.createElement('a') will return an HTMLAnchorElement, which TypeScript knows has an href property. Similarly, document.createElement('div') will return an HTMLDivElement, which TypeScript knows has no href property. When called with unknown elements, such as a custom element name (popup-element in our example), the methods will return a generic type, such as HTMLElement, since TypeScript can't infer the correct type of the returned element. Custom elements created with Angular extend NgElement (which in turn extends HTMLElement). Additionally, these custom elements will have a property for each input of the corresponding component. For example, our popup-element will have a message property of type string. There are a few options if you want to get correct types for your custom elements. Let's assume you create a my-dialog custom element based on the following component: @Component(...)
class MyDialog {
@Input() content: string;
} The most straight forward way to get accurate typings is to cast the return value of the relevant DOM methods to the correct type. For that, you can use the NgElement and WithProperties types (both exported from @angular/elements): const aDialog = document.createElement('my-dialog') as NgElement & WithProperties<{content: string}>;
aDialog.content = 'Hello, world!';
aDialog.content = 123; // <-- ERROR: TypeScript knows this should be a string.
aDialog.body = 'News'; // <-- ERROR: TypeScript knows there is no `body` property on `aDialog`. This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for you custom element. But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence. An alternative way, that only requires defining each custom element's type once, is augmenting the HTMLElementTagNameMap, which TypeScript uses to infer the type of a returned element based on its tag name (for DOM methods such as document.createElement(), document.querySelector(), etc.): declare global {
interface HTMLElementTagNameMap {
'my-dialog': NgElement & WithProperties<{content: string}>;
'my-other-element': NgElement & WithProperties<{foo: 'bar'}>;
...
}
} Now, TypeScript can infer the correct type the same way it does for built-in elements: document.createElement('div') //--> HTMLDivElement (built-in element)
document.querySelector('foo') //--> Element (unknown element)
document.createElement('my-dialog') //--> NgElement & WithProperties<{content: string}> (custom element)
document.querySelector('my-other-element') //--> NgElement & WithProperties<{foo: 'bar'}> (custom element)
|
String.prototype.toUpperCase()
The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
Try it
Syntax
toUpperCase()
Return value
A new string representing the calling string converted to upper case.Exceptions
TypeError When called on null or undefined, for example, String.prototype.toUpperCase.call(undefined). Description
The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. Examples
Basic usage
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
Conversion of non-string this values to strings
This method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = String.prototype.toUpperCase.call({
toString() {
return 'abcdef';
}
});
const b = String.prototype.toUpperCase.call(true);
// prints out 'ABCDEF TRUE'.
console.log(a, b);
Specifications
Specification
ECMAScript Language Specification # sec-string.prototype.touppercase
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
toUpperCase
1
12
1
3
3
1
4.4
18
4
10.1
1
1.0
1.0
0.10.0
See also
String.prototype.toLocaleLowerCase() String.prototype.toLocaleUpperCase() String.prototype.toLowerCase()
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: Jul 28, 2022, by MDN contributors
|
Thread
Available since LÖVE 0.7.0 This type is not supported in earlier versions. A Thread is a chunk of code that can run in parallel with other threads. Data can be sent between different threads with Channel objects. Constructors love.thread.newThread Creates a new Thread from a filename, string or FileData object containing Lua code. 0.7.0
Functions Object:release Immediately destroys the object's Lua reference. 11.0
Object:type Gets the type of the object as a string.
Object:typeOf Checks whether an object is of a certain type.
Thread:demand Receive a message from a thread. Wait for the message to exist before returning. 0.7.0 0.9.0
Thread:get Get a value. 0.8.0 0.9.0
Thread:getError Retrieves the error string from the thread. 0.9.0
Thread:getKeys Returns the names of all messages as a table. 0.8.0 0.9.0
Thread:getName Get the name of a thread. 0.7.0 0.9.0
Thread:isRunning Returns whether the thread is currently running. 0.9.0
Thread:kill Forcefully terminate the thread. 0.7.0 0.8.0
Thread:peek Receive a message from a thread, but leave it in the message box. 0.7.0 0.9.0
Thread:receive Receive a message from a thread. 0.7.0 0.8.0
Thread:send Send a message. 0.7.0 0.8.0
Thread:set Set a value. 0.8.0 0.9.0
Thread:start Starts the thread. 0.7.0
Thread:wait Wait for a thread to finish. 0.7.0
Supertypes Object
Notes Removed in LÖVE 0.9.0 This method for retrieving errors has been replaced by Thread:getError and love.threaderror. If a Lua error occurs in the thread, a message with the name "error" gets pushed to its message pool. Retrieve the message with Thread:get('error'). See Also love.thread
|
pandas.Series.is_monotonic_decreasing
Series.is_monotonic_decreasing
Return boolean if values in the object are monotonic_decreasing New in version 0.19.0.
Returns:
is_monotonic_decreasing : boolean
|
Object Model The standard C++ object model provides very efficient runtime support for the object paradigm. But its static nature is inflexibile in certain problem domains. Graphical user interface programming is a domain that requires both runtime efficiency and a high level of flexibility. Qt provides this, by combining the speed of C++ with the flexibility of the Qt Object Model. Qt adds these features to C++: a very powerful mechanism for seamless object communication called signals and slots
queryable and designable object properties
powerful events and event filters
contextual string translation for internationalization
sophisticated interval driven timers that make it possible to elegantly integrate many tasks in an event-driven GUI hierarchical and queryable object trees that organize object ownership in a natural way guarded pointers (QPointer) that are automatically set to 0 when the referenced object is destroyed, unlike normal C++ pointers which become dangling pointers when their objects are destroyed a dynamic cast that works across library boundaries. support for custom type creation. Many of these Qt features are implemented with standard C++ techniques, based on inheritance from QObject. Others, like the object communication mechanism and the dynamic property system, require the Meta-Object System provided by Qt's own Meta-Object Compiler (moc). The meta-object system is a C++ extension that makes the language better suited to true component GUI programming. Important Classes These classes form the basis of the Qt Object Model.
QMetaClassInfo
Additional information about a class
QMetaEnum
Meta-data about an enumerator
QMetaMethod
Meta-data about a member function
QMetaProperty
Meta-data about a property
QMetaType
Manages named types in the meta-object system
QObject
The base class of all Qt objects
QSignalBlocker
Exception-safe wrapper around QObject8b7c:f320:99b9:690f:4595:cd17:293a:c069lockSignals()
QObjectCleanupHandler
Watches the lifetime of multiple QObjects
QMetaObject
Contains meta-information about Qt objects
QPointer
Template class that provides guarded pointers to QObject
QSignalMapper
Bundles signals from identifiable senders
QVariant
Acts like a union for the most common Qt data types
Qt Objects: Identity vs Value Some of the added features listed above for the Qt Object Model, require that we think of Qt Objects as identities, not values. Values are copied or assigned; identities are cloned. Cloning means to create a new identity, not an exact copy of the old one. For example, twins have different identities. They may look identical, but they have different names, different locations, and may have completely different social networks. Then cloning an identity is a more complex operation than copying or assigning a value. We can see what this means in the Qt Object Model. A Qt Object... might have a unique QObject8b7c:f320:99b9:690f:4595:cd17:293a:c069objectName(). If we copy a Qt Object, what name should we give the copy? has a location in an object hierarchy. If we copy a Qt Object, where should the copy be located? can be connected to other Qt Objects to emit signals to them or to receive signals emitted by them. If we copy a Qt Object, how should we transfer these connections to the copy? can have new properties added to it at runtime that are not declared in the C++ class. If we copy a Qt Object, should the copy include the properties that were added to the original? For these reasons, Qt Objects should be treated as identities, not as values. Identities are cloned, not copied or assigned, and cloning an identity is a more complex operation than copying or assigning a value. Therefore, QObject and all subclasses of QObject (direct or indirect) have their copy constructor and assignment operator disabled.
|
plantTraits Plant Species Traits Data Description This dataset constitutes a description of 136 plant species according to biological attributes (morphological or reproductive) Usage data(plantTraits)
Format A data frame with 136 observations on the following 31 variables. pdias
Diaspore mass (mg) longindex
Seed bank longevity durflow
Flowering duration height
Plant height, an ordered factor with levels 1 < 2 < ... < 8. begflow
Time of first flowering, an ordered factor with levels 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 mycor
Mycorrhizas, an ordered factor with levels 0never < 1 sometimes< 2always vegaer
aerial vegetative propagation, an ordered factor with levels 0never < 1 present but limited< 2important. vegsout
underground vegetative propagation, an ordered factor with 3 levels identical to vegaer above. autopoll
selfing pollination, an ordered factor with levels 0never < 1rare < 2 often< the rule3 insects
insect pollination, an ordered factor with 5 levels 0 < ... < 4. wind
wind pollination, an ordered factor with 5 levels 0 < ... < 4. lign
a binary factor with levels 0:1, indicating if plant is woody. piq
a binary factor indicating if plant is thorny. ros
a binary factor indicating if plant is rosette. semiros
semi-rosette plant, a binary factor (0: no; 1: yes). leafy
leafy plant, a binary factor. suman
summer annual, a binary factor. winan
winter annual, a binary factor. monocarp
monocarpic perennial, a binary factor. polycarp
polycarpic perennial, a binary factor. seasaes
seasonal aestival leaves, a binary factor. seashiv
seasonal hibernal leaves, a binary factor. seasver
seasonal vernal leaves, a binary factor. everalw
leaves always evergreen, a binary factor. everparti
leaves partially evergreen, a binary factor. elaio
fruits with an elaiosome (dispersed by ants), a binary factor. endozoo
endozoochorous fruits, a binary factor. epizoo
epizoochorous fruits, a binary factor. aquat
aquatic dispersal fruits, a binary factor. windgl
wind dispersed fruits, a binary factor. unsp
unspecialized mechanism of seed dispersal, a binary factor. Details Most of factor attributes are not disjunctive. For example, a plant can be usually pollinated by insects but sometimes self-pollination can occured. Source Vallet, Jeanne (2005) Structuration de communautés végétales et analyse comparative de traits biologiques le long d'un gradient d'urbanisation. Mémoire de Master 2 'Ecologie-Biodiversité-Evolution'; Université Paris Sud XI, 30p.+ annexes (in french) Examples
data(plantTraits)
## Calculation of a dissimilarity matrix
library(cluster)
dai.b <- daisy(plantTraits,
type = list(ordratio = 4:11, symm = 12:13, asymm = 14:31))
## Hierarchical classification
agn.trts <- agnes(dai.b, method="ward")
plot(agn.trts, which.plots = 2, cex= 0.6)
plot(agn.trts, which.plots = 1)
cutree6 <- cutree(agn.trts, k=6)
cutree6
## Principal Coordinate Analysis
cmdsdai.b <- cmdscale(dai.b, k=6)
plot(cmdsdai.b[, 1:2], asp = 1, col = cutree6)
Copyright (
|
Storage orders There are two different storage orders for matrices and two-dimensional arrays: column-major and row-major. This page explains these storage orders and how to specify which one should be used.
Column-major and row-major storage The entries of a matrix form a two-dimensional grid. However, when the matrix is stored in memory, the entries have to somehow be laid out linearly. There are two main ways to do this, by row and by column. We say that a matrix is stored in row-major order if it is stored row by row. The entire first row is stored first, followed by the entire second row, and so on. Consider for example the matrix \[ A = \begin{bmatrix} 8 & 2 & 2 & 9 \\ 9 & 1 & 4 & 4 \\ 3 & 5 & 4 & 5 \end{bmatrix}. \] If this matrix is stored in row-major order, then the entries are laid out in memory as follows: 8 2 2 9 9 1 4 4 3 5 4 5
On the other hand, a matrix is stored in column-major order if it is stored column by column, starting with the entire first column, followed by the entire second column, and so on. If the above matrix is stored in column-major order, it is laid out as follows: 8 9 3 2 1 5 2 4 4 9 4 5
This example is illustrated by the following Eigen code. It uses the PlainObjectBas8b7c:f320:99b9:690f:4595:cd17:293a:c069data() function, which returns a pointer to the memory location of the first entry of the matrix. Example
Output
Matrix<int, 3, 4, ColMajor> Acolmajor;
Acolmajor << 8, 2, 2, 9,
9, 1, 4, 4,
3, 5, 4, 5;
cout << "The matrix A:" << endl;
cout << Acolmajor << endl << endl;
cout << "In memory (column-major):" << endl;
for (int i = 0; i < Acolmajor.size(); i++)
cout << *(Acolmajor.data() + i) << " ";
cout << endl << endl;
Matrix<int, 3, 4, RowMajor> Arowmajor = Acolmajor;
cout << "In memory (row-major):" << endl;
for (int i = 0; i < Arowmajor.size(); i++)
cout << *(Arowmajor.data() + i) << " ";
cout << endl;
The matrix A:
8 2 2 9
9 1 4 4
3 5 4 5
In memory (column-major):
8 9 3 2 1 5 2 4 4 9 4 5
In memory (row-major):
8 2 2 9 9 1 4 4 3 5 4 5
Storage orders in Eigen The storage order of a matrix or a two-dimensional array can be set by specifying the Options template parameter for Matrix or Array. As The Matrix class explains, the Matrix class template has six template parameters, of which three are compulsory (Scalar, RowsAtCompileTime and ColsAtCompileTime) and three are optional (Options, MaxRowsAtCompileTime and MaxColsAtCompileTime). If the Options parameter is set to RowMajor, then the matrix or array is stored in row-major order; if it is set to ColMajor, then it is stored in column-major order. This mechanism is used in the above Eigen program to specify the storage order. If the storage order is not specified, then Eigen defaults to storing the entry in column-major. This is also the case if one of the convenience typedefs (Matrix3f, ArrayXXd, etc.) is used. Matrices and arrays using one storage order can be assigned to matrices and arrays using the other storage order, as happens in the above program when Arowmajor is initialized using Acolmajor. Eigen will reorder the entries automatically. More generally, row-major and column-major matrices can be mixed in an expression as we want.
Which storage order to choose? So, which storage order should you use in your program? There is no simple answer to this question; it depends on your application. Here are some points to keep in mind: Your users may expect you to use a specific storage order. Alternatively, you may use other libraries than Eigen, and these other libraries may expect a certain storage order. In these cases it may be easiest and fastest to use this storage order in your whole program. Algorithms that traverse a matrix row by row will go faster when the matrix is stored in row-major order because of better data locality. Similarly, column-by-column traversal is faster for column-major matrices. It may be worthwhile to experiment a bit to find out what is faster for your particular application. The default in Eigen is column-major. Naturally, most of the development and testing of the Eigen library is thus done with column-major matrices. This means that, even though we aim to support column-major and row-major storage orders transparently, the Eigen library may well work best with column-major matrices.
|
st8b7c:f320:99b9:690f:4595:cd17:293a:c069data Defined in header <array> Defined in header <deque> Defined in header <forward_list> Defined in header <iterator> Defined in header <list> Defined in header <map> Defined in header <regex> Defined in header <set> Defined in header <span> (since C++20) Defined in header <string> Defined in header <string_view> Defined in header <unordered_map> Defined in header <unordered_set> Defined in header <vector> template <class C>
constexpr auto data(C& c) -> decltype(c.data());
(1) (since C++17) template <class C>
constexpr auto data(const C& c) -> decltype(c.data());
(2) (since C++17) template <class T, st8b7c:f320:99b9:690f:4595:cd17:293a:c069size_t N>
constexpr T* data(T (&array)[N]) noexcept;
(3) (since C++17) template <class E>
constexpr const E* data(st8b7c:f320:99b9:690f:4595:cd17:293a:c069initializer_list<E> il) noexcept;
(4) (since C++17) Returns a pointer to the block of memory containing the elements of the range.
1,2) returns c.data()
3) returns array
4) returns il.begin()
Parameters c - a container or view with a data() member function
array - an array of arbitrary type
il - an initializer list
Return value A pointer to the block of memory containing the elements of the range.
Exceptions
1) May throw implementation-defined exceptions. Notes The overload for st8b7c:f320:99b9:690f:4595:cd17:293a:c069initializer_list is necessary because it does not have a member function data.
Feature-test macro
__cpp_lib_nonmember_container_access
Possible implementation First version
template <class C>
constexpr auto data(C& c) -> decltype(c.data())
{
return c.data();
}
Second version
template <class C>
constexpr auto data(const C& c) -> decltype(c.data())
{
return c.data();
}
Third version
template <class T, st8b7c:f320:99b9:690f:4595:cd17:293a:c069size_t N>
constexpr T* data(T (&array)[N]) noexcept
{
return array;
}
Fourth version
template <class E>
constexpr const E* data(st8b7c:f320:99b9:690f:4595:cd17:293a:c069initializer_list<E> il) noexcept
{
return il.begin();
}
Example #include <string>
#include <cstring>
#include <iostream>
int main()
{
st8b7c:f320:99b9:690f:4595:cd17:293a:c069string s {"Hello world!\n"};
char a[20]; // storage for a C-style string
st8b7c:f320:99b9:690f:4595:cd17:293a:c069strcpy(a, st8b7c:f320:99b9:690f:4595:cd17:293a:c069data(s));
// [s.data(), s.data() + s.size()] is guaranteed to be an NTBS since C++11
st8b7c:f320:99b9:690f:4595:cd17:293a:c069cout << a;
} Output:
Hello world! See also ranges8b7c:f320:99b9:690f:4595:cd17:293a:c069ta
(C++20) obtains a pointer to the beginning of a contiguous range (customization point object)
ranges8b7c:f320:99b9:690f:4595:cd17:293a:c069ta
(C++20) obtains a pointer to the beginning of a read-only contiguous range (customization point object)
|
[Java] Class StaticTypeCheckingVisitor
org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor
public class StaticTypeCheckingVisitor
extends ClassCodeVisitorSupport The main class code visitor responsible for static type checking. It will perform various inspections like checking assignment types, type inference, ... Eventually, class nodes may be annotated with inferred type information. Nested Class Summary
Nested classes
Modifiers Name Description
static class StaticTypeCheckingVisitor.SignatureCodecFactory
protected class StaticTypeCheckingVisitor.VariableExpressionTypeMemoizer Field Summary
Fields
Modifiers Name Description
protected static ClassNode CLOSUREPARAMS_CLASSNODE
static MethodNode CLOSURE_CALL_NO_ARG
static MethodNode CLOSURE_CALL_ONE_ARG
static MethodNode CLOSURE_CALL_VARGS
protected static Expression CURRENT_SIGNATURE_PROTOCOL
protected static int CURRENT_SIGNATURE_PROTOCOL_VERSION
protected static ClassNode DELEGATES_TO
protected static ClassNode DELEGATES_TO_TARGET
protected static ClassNode DGM_CLASSNODE
protected static List<MethodNode> EMPTY_METHODNODE_LIST
protected static ClassNode ENUMERATION_TYPE
protected static Object ERROR_COLLECTOR
static Statement GENERATED_EMPTY_STATEMENT
protected static MethodNode GET_DELEGATE
protected static MethodNode GET_OWNER
protected static MethodNode GET_THISOBJECT
protected static ClassNode ITERABLE_TYPE
protected static ClassNode LINKEDHASHMAP_CLASSNODE
protected static ClassNode MAP_ENTRY_TYPE
protected static ClassNode NAMED_PARAMS_CLASSNODE
protected static ClassNode TYPECHECKED_CLASSNODE
protected static ClassNode[] TYPECHECKING_ANNOTATIONS
protected static ClassNode TYPECHECKING_INFO_NODE
protected FieldNode currentField
protected PropertyNode currentProperty
protected DefaultTypeCheckingExtension extension
protected ReturnAdder returnAdder
protected ReturnStatementListener returnListener
protected TypeCheckingContext typeCheckingContext Constructor Summary
Constructors
Constructor and description StaticTypeCheckingVisitor(SourceUnit source, ClassNode classNode)
Methods Summary
Methods
Type Params Return Type Name and description protected void
addAmbiguousErrorMessage(List<MethodNode> foundMethods, String name, ClassNode[] args, Expression expr)
protected void
addAssignmentError(ClassNode leftType, ClassNode rightType, Expression expression)
protected void
addCategoryMethodCallError(Expression call)
protected void
addClosureReturnType(ClassNode returnType)
public void
addError(String msg, ASTNode expr)
protected void
addNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, Expression call)
protected void
addReceivers(List<Receiver<String>> receivers, Collection<Receiver<String>> owners, boolean implicitThis)
protected void
addStaticTypeError(String msg, ASTNode expr)
public void
addTypeCheckingExtension(TypeCheckingExtension extension)
protected void
addTypeCheckingInfoAnnotation(MethodNode node)
protected void
addUnsupportedPreOrPostfixExpressionError(Expression expression)
protected void
afterSwitchConditionExpressionVisited(SwitchStatement statement)
protected boolean
areCategoryMethodCalls(List<MethodNode> foundMethods, String name, ClassNode[] args)
protected boolean
checkCast(ClassNode targetType, Expression source)
protected void
checkClosureParameters(Expression callArguments, ClassNode receiver)
deprecated:
this method is unused, replaced with DelegatesTo inference.
protected void
checkForbiddenSpreadArgument(ArgumentListExpression argumentList)
protected void
checkGroovyConstructorMap(Expression receiver, ClassNode receiverType, MapExpression mapExpression)
protected void
checkGroovyStyleConstructor(ClassNode node, ClassNode[] arguments)Checks that a constructor style expression is valid regarding the number of arguments and the argument types. protected MethodNode
checkGroovyStyleConstructor(ClassNode node, ClassNode[] arguments, ASTNode source)Checks that a constructor style expression is valid regarding the number of arguments and the argument types. protected ClassNode
checkReturnType(ReturnStatement statement)
protected boolean
existsProperty(PropertyExpression pexp, boolean checkForReadOnly)
protected boolean
existsProperty(PropertyExpression pexp, boolean readMode, ClassCodeVisitorSupport visitor)Checks whether a property exists on the receiver, or on any of the possible receiver classes (found in the temporary type information table) public static String
extractPropertyNameFromMethodName(String prefix, String methodName)Given a method name and a prefix, returns the name of the property that should be looked up, following the java beans rules. protected Object
extractTemporaryTypeInfoKey(Expression expression)When instanceof checks are found in the code, we store temporary type information data in the TypeCheckingContext.temporaryIfBranchTypeInformation table. protected static ClassNode[]
extractTypesFromParameters(Parameter[] parameters)
protected ClassNode
findCurrentInstanceOfClass(Expression expr, ClassNode type)A helper method which determines which receiver class should be used in error messages when a field or attribute is not found. protected BinaryExpression
findInstanceOfNotReturnExpression(IfStatement ifElse)Check IfStatement matched pattern : Object var1; if (! protected List<MethodNode>
findMethod(ClassNode receiver, String name, ClassNode args)
protected MethodNode
findMethodOrFail(Expression expr, ClassNode receiver, String name, ClassNode args)
protected List<MethodNode>
findMethodsWithGenerated(ClassNode receiver, String name)Returns methods defined for the specified receiver and adds "non-existing" methods that will be generated afterwards by the compiler; for example if a method is using default values and the class node isn't compiled yet. protected BinaryExpression
findNotInstanceOfReturnExpression(IfStatement ifElse)Check IfStatement matched pattern : Object var1; if (var1 ! protected static String
formatArgumentList(ClassNode[] nodes)
protected ClassNode[]
getArgumentTypes(ArgumentListExpression args)
protected DelegationMetadata
getDelegationMetadata(ClosureExpression expression)
protected static ClassNode
getGroupOperationResultType(ClassNode a, ClassNode b)
protected ClassNode
getInferredReturnType(ASTNode exp)Returns the inferred return type of a closure or a method, if stored on the AST node. protected ClassNode
getInferredReturnTypeFromWithClosureArgument(Expression callArguments)In the case of a Object.with { ... } call, this method is supposed to retrieve the inferred closure return type. protected ClassNode
getOriginalDeclarationType(Expression lhs)
protected ClassNode
getResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr)
protected SourceUnit
getSourceUnit()
protected List<ClassNode>
getTemporaryTypesForExpression(Expression objectExpression)
protected ClassNode
getType(ASTNode exp)
protected ClassNode[]
getTypeCheckingAnnotations()Returns array of type checking annotations. public TypeCheckingContext
getTypeCheckingContext()Returns the current type checking context. protected static boolean
hasRHSIncompleteGenericTypeInfo(ClassNode inferredRightExpressionType)
protected void
inferClosureParameterTypes(ClassNode receiver, Expression arguments, ClosureExpression expression, Parameter target, MethodNode method)Performs type inference on closure argument types whenever code like this is found: foo.collect { it.toUpperCase() }. protected ClassNode
inferComponentType(ClassNode containerType, ClassNode indexType)
protected void
inferDiamondType(ConstructorCallExpression cce, ClassNode lType)
protected ClassNode
inferListExpressionType(ListExpression list)
public static ClassNode
inferLoopElementType(ClassNode collectionType)Given a loop collection type, returns the inferred type of the loop element. protected ClassNode
inferMapExpressionType(MapExpression map)
protected ClassNode
inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments)If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. protected ClassNode
inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments, GenericsType[] explicitTypeHints)If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. public void
initialize()
protected static boolean
isClassInnerClassOrEqualTo(ClassNode toBeChecked, ClassNode start)
protected static boolean
isNullConstant(Expression expression)
protected boolean
isSecondPassNeededForControlStructure(Map<VariableExpression, ClassNode> varOrigType, Map<VariableExpression, List<ClassNode>> oldTracker)
public boolean
isSkipMode(AnnotatedNode node)
protected boolean
isSkippedInnerClass(AnnotatedNode node)Tests if a node is an inner class node, and if it is, then checks if the enclosing method is skipped. protected static boolean
isSuperExpression(Expression expression)
protected static boolean
isThisExpression(Expression expression)
protected List<Receiver<String>>
makeOwnerList(Expression objectExpression)Given an object expression (a receiver expression), generate the list of potential receiver types. public void
performSecondPass()
protected Map<VariableExpression, ClassNode>
popAssignmentTracking(Map<VariableExpression, List<ClassNode>> oldTracker)
protected static String
prettyPrintMethodList(List<MethodNode> nodes)
protected Map<VariableExpression, List<ClassNode>>
pushAssignmentTracking()
protected void
pushInstanceOfTypeInfo(Expression objectOfInstanceOf, Expression typeExpression)Stores information about types when [objectOfInstanceof instanceof typeExpression] is visited. protected void
restoreVariableExpressionMetadata(Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit)
public void
returnStatementAdded(ReturnStatement returnStatement)
protected void
saveVariableExpressionMetadata(Set<VariableExpression> closureSharedExpressions, Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit)
public void
setCompilationUnit(CompilationUnit compilationUnit)
public void
setMethodsToBeVisited(Set<MethodNode> methodsToBeVisited)
protected boolean
shouldSkipClassNode(ClassNode node)
protected boolean
shouldSkipMethodNode(MethodNode node)
protected void
silentlyVisitMethodNode(MethodNode directMethodCallCandidate)Visits a method call target, to infer the type. protected void
startMethodInference(MethodNode node, ErrorCollector collector)
protected ClassNode
storeInferredReturnType(ASTNode node, ClassNode type)Stores the inferred return type of a closure or a method. protected void
storeTargetMethod(Expression call, MethodNode directMethodCallCandidate)
protected void
storeType(Expression exp, ClassNode cn)
protected void
typeCheckAssignment(BinaryExpression assignmentExpression, Expression leftExpression, ClassNode leftExpressionType, Expression rightExpression, ClassNode rightExpressionType)
protected void
typeCheckClosureCall(Expression arguments, ClassNode[] argumentTypes, Parameter[] parameters)
protected MethodNode
typeCheckMapConstructor(ConstructorCallExpression call, ClassNode receiver, Expression arguments)
protected boolean
typeCheckMethodsWithGenericsOrFail(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod, Expression location)
public void
visitArrayExpression(ArrayExpression expression)
public void
visitAttributeExpression(AttributeExpression expression)
public void
visitBinaryExpression(BinaryExpression expression)
public void
visitBitwiseNegationExpression(BitwiseNegationExpression expression)
public void
visitBlockStatement(BlockStatement block)
public void
visitCaseStatement(CaseStatement statement)
public void
visitCastExpression(CastExpression expression)
public void
visitClass(ClassNode node)
public void
visitClassExpression(ClassExpression expression)
public void
visitClosingBlock(BlockStatement block)
public void
visitClosureExpression(ClosureExpression expression)
public void
visitClosureExpression(ClosureExpression expression)
public void
visitConstructor(ConstructorNode node)
public void
visitConstructorCallExpression(ConstructorCallExpression call)
protected void
visitConstructorOrMethod(MethodNode node, boolean isConstructor)
public void
visitExpressionStatement(ExpressionStatement statement)
public void
visitField(FieldNode node)
public void
visitForLoop(ForStatement forLoop)
public void
visitIfElse(IfStatement ifElse)
protected void
visitInstanceofNot(BinaryExpression be)
public void
visitMethod(MethodNode node)
protected void
visitMethodCallArguments(ClassNode receiver, ArgumentListExpression arguments, boolean visitClosures, MethodNode selectedMethod)
public void
visitMethodCallExpression(MethodCallExpression mce)
public void
visitMethodCallExpression(MethodCallExpression call)
public void
visitMethodPointerExpression(MethodPointerExpression expression)
public void
visitNotExpression(NotExpression expression)
protected void
visitObjectInitializerStatements(ClassNode node)
public void
visitPostfixExpression(PostfixExpression expression)
public void
visitPrefixExpression(PrefixExpression expression)
public void
visitProperty(PropertyNode node)
public void
visitPropertyExpression(PropertyExpression expression)
public void
visitRangeExpression(RangeExpression expression)
public void
visitReturnStatement(ReturnStatement statement)
public void
visitReturnStatement(ReturnStatement returnStatement)
public void
visitStaticMethodCallExpression(StaticMethodCallExpression call)
public void
visitSwitch(SwitchStatement statement)
public void
visitTernaryExpression(TernaryExpression expression)
public void
visitTryCatchFinally(TryCatchStatement statement)
public void
visitUnaryMinusExpression(UnaryMinusExpression expression)
public void
visitUnaryPlusExpression(UnaryPlusExpression expression)
public void
visitVariableExpression(VariableExpression vexp)
public void
visitWhileLoop(WhileStatement loop)
protected static ClassNode
wrapTypeIfNecessary(ClassNode type)Returns a wrapped type if, and only if, the provided class node is a primitive type. Inherited Methods Summary
Inherited Methods
Methods inherited from class Name class ClassCodeVisitorSupport addError, getSourceUnit, visitAnnotation, visitAnnotations, visitAnnotations, visitAssertStatement, visitBlockStatement, visitBreakStatement, visitCaseStatement, visitCatchStatement, visitClass, visitClassCodeContainer, visitConstructor, visitConstructorOrMethod, visitContinueStatement, visitDeclarationExpression, visitDoWhileLoop, visitExpressionStatement, visitField, visitForLoop, visitIfElse, visitImports, visitMethod, visitObjectInitializerStatements, visitPackage, visitProperty, visitReturnStatement, visitStatement, visitSwitch, visitSynchronizedStatement, visitThrowStatement, visitTryCatchFinally, visitWhileLoop class CodeVisitorSupport afterSwitchConditionExpressionVisited, visitArgumentlistExpression, visitArrayExpression, visitAssertStatement, visitAttributeExpression, visitBinaryExpression, visitBitwiseNegationExpression, visitBlockStatement, visitBooleanExpression, visitBreakStatement, visitBytecodeExpression, visitCaseStatement, visitCastExpression, visitCatchStatement, visitClassExpression, visitClosureExpression, visitClosureListExpression, visitConstantExpression, visitConstructorCallExpression, visitContinueStatement, visitDeclarationExpression, visitDoWhileLoop, visitEmptyStatement, visitExpressionStatement, visitFieldExpression, visitForLoop, visitGStringExpression, visitIfElse, visitLambdaExpression, visitListExpression, visitMapEntryExpression, visitMapExpression, visitMethodCallExpression, visitMethodPointerExpression, visitMethodReferenceExpression, visitNotExpression, visitPostfixExpression, visitPrefixExpression, visitPropertyExpression, visitRangeExpression, visitReturnStatement, visitShortTernaryExpression, visitSpreadExpression, visitSpreadMapExpression, visitStaticMethodCallExpression, visitSwitch, visitSynchronizedStatement, visitTernaryExpression, visitThrowStatement, visitTryCatchFinally, visitTupleExpression, visitUnaryMinusExpression, visitUnaryPlusExpression, visitVariableExpression, visitWhileLoop Field Detail protected static final ClassNode CLOSUREPARAMS_CLASSNODE
public static final MethodNode CLOSURE_CALL_NO_ARG
public static final MethodNode CLOSURE_CALL_ONE_ARG
public static final MethodNode CLOSURE_CALL_VARGS
protected static final Expression CURRENT_SIGNATURE_PROTOCOL
protected static final int CURRENT_SIGNATURE_PROTOCOL_VERSION
protected static final ClassNode DELEGATES_TO
protected static final ClassNode DELEGATES_TO_TARGET
protected static final ClassNode DGM_CLASSNODE
protected static final List<MethodNode> EMPTY_METHODNODE_LIST
protected static final ClassNode ENUMERATION_TYPE
protected static final Object ERROR_COLLECTOR
public static final Statement GENERATED_EMPTY_STATEMENT
protected static final MethodNode GET_DELEGATE
protected static final MethodNode GET_OWNER
protected static final MethodNode GET_THISOBJECT
protected static final ClassNode ITERABLE_TYPE
@Deprecated protected static final ClassNode LINKEDHASHMAP_CLASSNODE
protected static final ClassNode MAP_ENTRY_TYPE
protected static final ClassNode NAMED_PARAMS_CLASSNODE
protected static final ClassNode TYPECHECKED_CLASSNODE
protected static final ClassNode[] TYPECHECKING_ANNOTATIONS
protected static final ClassNode TYPECHECKING_INFO_NODE
protected FieldNode currentField
protected PropertyNode currentProperty
protected DefaultTypeCheckingExtension extension
protected final ReturnAdder returnAdder
protected final ReturnStatementListener returnListener
protected TypeCheckingContext typeCheckingContext
Constructor Detail public StaticTypeCheckingVisitor(SourceUnit source, ClassNode classNode) Method Detail protected void addAmbiguousErrorMessage(List<MethodNode> foundMethods, String name, ClassNode[] args, Expression expr) protected void addAssignmentError(ClassNode leftType, ClassNode rightType, Expression expression) protected void addCategoryMethodCallError(Expression call) protected void addClosureReturnType(ClassNode returnType) @Override public void addError(String msg, ASTNode expr) protected void addNoMatchingMethodError(ClassNode receiver, String name, ClassNode[] args, Expression call) protected void addReceivers(List<Receiver<String>> receivers, Collection<Receiver<String>> owners, boolean implicitThis) protected void addStaticTypeError(String msg, ASTNode expr) public void addTypeCheckingExtension(TypeCheckingExtension extension) protected void addTypeCheckingInfoAnnotation(MethodNode node) protected void addUnsupportedPreOrPostfixExpressionError(Expression expression) @Override protected void afterSwitchConditionExpressionVisited(SwitchStatement statement) protected boolean areCategoryMethodCalls(List<MethodNode> foundMethods, String name, ClassNode[] args) protected boolean checkCast(ClassNode targetType, Expression source) @Deprecated protected void checkClosureParameters(Expression callArguments, ClassNode receiver)
deprecated:
this method is unused, replaced with DelegatesTo inference.
protected void checkForbiddenSpreadArgument(ArgumentListExpression argumentList) protected void checkGroovyConstructorMap(Expression receiver, ClassNode receiverType, MapExpression mapExpression) @Deprecated protected void checkGroovyStyleConstructor(ClassNode node, ClassNode[] arguments) Checks that a constructor style expression is valid regarding the number of arguments and the argument types.
deprecated:
use checkGroovyStyleConstructor(org.codehaus.groovy.ast.ClassNode, org.codehaus.groovy.ast.ClassNode[], org.codehaus.groovy.ast.ASTNode) )}
Parameters:
node - the class node for which we will try to find a matching constructor
arguments - the constructor arguments
protected MethodNode checkGroovyStyleConstructor(ClassNode node, ClassNode[] arguments, ASTNode source) Checks that a constructor style expression is valid regarding the number of arguments and the argument types.
Parameters:
node - the class node for which we will try to find a matching constructor
arguments - the constructor arguments
protected ClassNode checkReturnType(ReturnStatement statement) protected boolean existsProperty(PropertyExpression pexp, boolean checkForReadOnly) protected boolean existsProperty(PropertyExpression pexp, boolean readMode, ClassCodeVisitorSupport visitor) Checks whether a property exists on the receiver, or on any of the possible receiver classes (found in the temporary type information table)
Parameters:
pexp - a property expression
readMode - if true, look for property read, else for property set
visitor - if not null, when the property node is found, visit it with the provided visitor
Returns:
true if the property is defined in any of the possible receiver classes
public static String extractPropertyNameFromMethodName(String prefix, String methodName) Given a method name and a prefix, returns the name of the property that should be looked up, following the java beans rules. For example, "getName" would return "name", while "getFullName" would return "fullName". If the prefix is not found, returns null.
Parameters:
prefix - the method name prefix ("get", "is", "set", ...)
methodName - the method name
Returns:
a property name if the prefix is found and the method matches the java beans rules, null otherwise
protected Object extractTemporaryTypeInfoKey(Expression expression) When instanceof checks are found in the code, we store temporary type information data in the TypeCheckingContext.temporaryIfBranchTypeInformation table. This method computes the key which must be used to store this type info.
Parameters:
expression - the expression for which to compute the key
Returns:
a key to be used for TypeCheckingContext.temporaryIfBranchTypeInformation
protected static ClassNode[] extractTypesFromParameters(Parameter[] parameters) protected ClassNode findCurrentInstanceOfClass(Expression expr, ClassNode type) A helper method which determines which receiver class should be used in error messages when a field or attribute is not found. The returned type class depends on whether we have temporary type information available (due to instanceof checks) and whether there is a single candidate in that case.
Parameters:
expr - the expression for which an unknown field has been found
type - the type of the expression (used as fallback type)
Returns:
if temporary information is available and there's only one type, returns the temporary type class otherwise falls back to the provided type class.
protected BinaryExpression findInstanceOfNotReturnExpression(IfStatement ifElse) Check IfStatement matched pattern : Object var1; if (!(var1 instanceOf Runnable)) { return } // Here var1 instance of Runnable
Return expression , which contains instanceOf (without not) Return null, if not found protected List<MethodNode> findMethod(ClassNode receiver, String name, ClassNode args) protected MethodNode findMethodOrFail(Expression expr, ClassNode receiver, String name, ClassNode args) protected List<MethodNode> findMethodsWithGenerated(ClassNode receiver, String name) Returns methods defined for the specified receiver and adds "non-existing" methods that will be generated afterwards by the compiler; for example if a method is using default values and the class node isn't compiled yet.
Parameters:
receiver - the receiver where to find methods
name - the name of the methods to return
Returns:
the methods that are defined on the receiver completed with stubs for future methods
protected BinaryExpression findNotInstanceOfReturnExpression(IfStatement ifElse) Check IfStatement matched pattern : Object var1; if (var1 !instanceOf Runnable) { return } // Here var1 instance of Runnable
Return expression , which contains instanceOf (without not) Return null, if not found protected static String formatArgumentList(ClassNode[] nodes) protected ClassNode[] getArgumentTypes(ArgumentListExpression args) protected DelegationMetadata getDelegationMetadata(ClosureExpression expression) protected static ClassNode getGroupOperationResultType(ClassNode a, ClassNode b) protected ClassNode getInferredReturnType(ASTNode exp) Returns the inferred return type of a closure or a method, if stored on the AST node. This method doesn't perform any type inference by itself.
Parameters:
exp - a ClosureExpression or MethodNode
Returns:
the inferred type, as stored on node metadata.
protected ClassNode getInferredReturnTypeFromWithClosureArgument(Expression callArguments) In the case of a Object.with { ... } call, this method is supposed to retrieve the inferred closure return type.
Parameters:
callArguments - the argument list from the Object#with(Closure) call, ie. a single closure expression
Returns:
the inferred closure return type or null
protected ClassNode getOriginalDeclarationType(Expression lhs) protected ClassNode getResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr) @Override protected SourceUnit getSourceUnit() protected List<ClassNode> getTemporaryTypesForExpression(Expression objectExpression) protected ClassNode getType(ASTNode exp) protected ClassNode[] getTypeCheckingAnnotations() Returns array of type checking annotations. Subclasses may override this method in order to provide additional types which must be looked up when checking if a method or a class node should be skipped.
The default implementation returns TypeChecked. public TypeCheckingContext getTypeCheckingContext() Returns the current type checking context. The context is used internally by the type checker during type checking to store various state data.
Returns:
the type checking context
@Deprecated protected static boolean hasRHSIncompleteGenericTypeInfo(ClassNode inferredRightExpressionType) protected void inferClosureParameterTypes(ClassNode receiver, Expression arguments, ClosureExpression expression, Parameter target, MethodNode method) Performs type inference on closure argument types whenever code like this is found: foo.collect { it.toUpperCase() }.
In this case the type checker tries to find if the collect method has its Closure argument annotated with ClosureParams. If so, then additional type inference can be performed and the type of it may be inferred.
Parameters:
receiver
arguments
expression - closure or lambda expression for which the argument types should be inferred
target - parameter which may provide ClosureParams annotation or SAM type
method - method that declares target
protected ClassNode inferComponentType(ClassNode containerType, ClassNode indexType) protected void inferDiamondType(ConstructorCallExpression cce, ClassNode lType) protected ClassNode inferListExpressionType(ListExpression list) public static ClassNode inferLoopElementType(ClassNode collectionType) Given a loop collection type, returns the inferred type of the loop element. Used, for example, to infer the element type of a (for e in list) loop.
Parameters:
collectionType - the type of the collection
Returns:
the inferred component type
protected ClassNode inferMapExpressionType(MapExpression map) protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. For example, the method Arrays.asList(T...) is parameterized with T, which can be deduced type arguments or call arguments.
Parameters:
method - the method node
arguments - the method call arguments
receiver - the object expression type
protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments, GenericsType[] explicitTypeHints) If a method call returns a parameterized type, then perform additional inference on the return type, so that the type gets actual type arguments. For example, the method Arrays.asList(T...) is parameterized with T, which can be deduced type arguments or call arguments.
Parameters:
method - the method node
arguments - the method call arguments
receiver - the object expression type
explicitTypeHints - type arguments (optional), for example Collections.<String>emptyList()
public void initialize() protected static boolean isClassInnerClassOrEqualTo(ClassNode toBeChecked, ClassNode start) protected static boolean isNullConstant(Expression expression) protected boolean isSecondPassNeededForControlStructure(Map<VariableExpression, ClassNode> varOrigType, Map<VariableExpression, List<ClassNode>> oldTracker) public boolean isSkipMode(AnnotatedNode node) protected boolean isSkippedInnerClass(AnnotatedNode node) Tests if a node is an inner class node, and if it is, then checks if the enclosing method is skipped.
Returns:
true if the inner class node should be skipped
protected static boolean isSuperExpression(Expression expression) protected static boolean isThisExpression(Expression expression) protected List<Receiver<String>> makeOwnerList(Expression objectExpression) Given an object expression (a receiver expression), generate the list of potential receiver types.
Parameters:
objectExpression - the receiver expression
Returns:
the list of types the receiver may be
public void performSecondPass() protected Map<VariableExpression, ClassNode> popAssignmentTracking(Map<VariableExpression, List<ClassNode>> oldTracker) protected static String prettyPrintMethodList(List<MethodNode> nodes) protected Map<VariableExpression, List<ClassNode>> pushAssignmentTracking() protected void pushInstanceOfTypeInfo(Expression objectOfInstanceOf, Expression typeExpression) Stores information about types when [objectOfInstanceof instanceof typeExpression] is visited.
Parameters:
objectOfInstanceOf - the expression which must be checked against instanceof
typeExpression - the expression which represents the target type
protected void restoreVariableExpressionMetadata(Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) @Override public void returnStatementAdded(ReturnStatement returnStatement) protected void saveVariableExpressionMetadata(Set<VariableExpression> closureSharedExpressions, Map<VariableExpression, Map<StaticTypesMarker, Object>> typesBeforeVisit) public void setCompilationUnit(CompilationUnit compilationUnit) public void setMethodsToBeVisited(Set<MethodNode> methodsToBeVisited) protected boolean shouldSkipClassNode(ClassNode node) protected boolean shouldSkipMethodNode(MethodNode node) protected void silentlyVisitMethodNode(MethodNode directMethodCallCandidate) Visits a method call target, to infer the type. Don't report errors right away, that will be done by a later visitMethod call. protected void startMethodInference(MethodNode node, ErrorCollector collector) protected ClassNode storeInferredReturnType(ASTNode node, ClassNode type) Stores the inferred return type of a closure or a method. We are using a separate key to store inferred return type because the inferred type of a closure is Closure, which is different from the inferred type of the code of the closure.
Parameters:
node - a ClosureExpression or a MethodNode
type - the inferred return type of the code
Returns:
the old value of the inferred type
protected void storeTargetMethod(Expression call, MethodNode directMethodCallCandidate) protected void storeType(Expression exp, ClassNode cn) protected void typeCheckAssignment(BinaryExpression assignmentExpression, Expression leftExpression, ClassNode leftExpressionType, Expression rightExpression, ClassNode rightExpressionType) protected void typeCheckClosureCall(Expression arguments, ClassNode[] argumentTypes, Parameter[] parameters) protected MethodNode typeCheckMapConstructor(ConstructorCallExpression call, ClassNode receiver, Expression arguments) protected boolean typeCheckMethodsWithGenericsOrFail(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod, Expression location) @Override public void visitArrayExpression(ArrayExpression expression) @Override public void visitAttributeExpression(AttributeExpression expression) @Override public void visitBinaryExpression(BinaryExpression expression) @Override public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) @Override public void visitBlockStatement(BlockStatement block) @Override public void visitCaseStatement(CaseStatement statement) @Override public void visitCastExpression(CastExpression expression) @Override public void visitClass(ClassNode node) @Override public void visitClassExpression(ClassExpression expression) public void visitClosingBlock(BlockStatement block) @Override public void visitClosureExpression(ClosureExpression expression) @Override public void visitClosureExpression(ClosureExpression expression) @Override public void visitConstructor(ConstructorNode node) @Override public void visitConstructorCallExpression(ConstructorCallExpression call) @Override protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) @Override public void visitExpressionStatement(ExpressionStatement statement) @Override public void visitField(FieldNode node) @Override public void visitForLoop(ForStatement forLoop) @Override public void visitIfElse(IfStatement ifElse) protected void visitInstanceofNot(BinaryExpression be) @Override public void visitMethod(MethodNode node) protected void visitMethodCallArguments(ClassNode receiver, ArgumentListExpression arguments, boolean visitClosures, MethodNode selectedMethod) @Override public void visitMethodCallExpression(MethodCallExpression mce) @Override public void visitMethodCallExpression(MethodCallExpression call) @Override public void visitMethodPointerExpression(MethodPointerExpression expression) @Override public void visitNotExpression(NotExpression expression) @Override protected void visitObjectInitializerStatements(ClassNode node) @Override public void visitPostfixExpression(PostfixExpression expression) @Override public void visitPrefixExpression(PrefixExpression expression) @Override public void visitProperty(PropertyNode node) @Override public void visitPropertyExpression(PropertyExpression expression) @Override public void visitRangeExpression(RangeExpression expression) @Override public void visitReturnStatement(ReturnStatement statement) @Override public void visitReturnStatement(ReturnStatement returnStatement) @Override public void visitStaticMethodCallExpression(StaticMethodCallExpression call) @Override public void visitSwitch(SwitchStatement statement) @Override public void visitTernaryExpression(TernaryExpression expression) @Override public void visitTryCatchFinally(TryCatchStatement statement) @Override public void visitUnaryMinusExpression(UnaryMinusExpression expression) @Override public void visitUnaryPlusExpression(UnaryPlusExpression expression) @Override public void visitVariableExpression(VariableExpression vexp) @Override public void visitWhileLoop(WhileStatement loop) protected static ClassNode wrapTypeIfNecessary(ClassNode type) Returns a wrapped type if, and only if, the provided class node is a primitive type. This method differs from ClassHelper#getWrapper(org.codehaus.groovy.ast.ClassNode) as it will return the same instance if the provided type is not a generic type.
Returns:
the wrapped type
|
CategoryAxis3D QML Type Manipulates an axis of a graph. More...
Import Statement:
import QtDataVisualization 1.2
Since:
QtDataVisualization 1.0
Instantiates:
QCategory3DAxis
Inherits:
AbstractAxis3D
List of all members, including inherited members Properties
labels : list Detailed Description This type provides an axis that can be given labels. Property Documentation labels : list
The labels for the axis applied to categories. If there are fewer labels than categories, the remaining ones do not have a label. If category labels are not defined explicitly, labels are generated from the data row (or column) labels of the primary series of the graph.
|
ItemNotFoundException class ItemNotFoundException extends RuntimeException (View source)
|
Deno.mkdir
Creates a new directory with the specified path. await Deno.mkdir("new_dir");
await Deno.mkdir("nested/directories", { recursive: true });
await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
Defaults to throwing error if the directory already exists. Requires allow-write permission.
function mkdir(path: string | URL, options?: MkdirOptions): Promise<void>;
mkdir(path: string | URL, options?: MkdirOptions): Promise<void>
Parameters
path: string | URL
options?: MkdirOptions optional
Return Type
Promise<void>
|
sklearn.isotonic.check_increasing sklearn.isotonic.check_increasing(x, y)[source]
Determine whether y is monotonically correlated with x. y is found increasing or decreasing with respect to x based on a Spearman correlation test. Parameters:
xarray-like of shape (n_samples,)
Training data.
yarray-like of shape (n_samples,)
Training target. Returns:
increasing_boolboolean
Whether the relationship is increasing or decreasing. Notes The Spearman correlation coefficient is estimated from the data, and the sign of the resulting estimate is used as the result. In the event that the 95% confidence interval based on Fisher transform spans zero, a warning is raised. References Fisher transformation. Wikipedia. https://en.wikipedia.org/wiki/Fisher_transformation
|
matplotlib.axes.Axes.set_autoscale_on
Axes.set_autoscale_on(b)
Set whether autoscaling is applied on plot commands accepts: [ True | False ]
|
Class: Phaser.Component.PhysicsBody Constructor
new PhysicsBody()
The PhysicsBody component manages the Game Objects physics body and physics enabling.It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. Source code: gameobjects/components/PhysicsBody.js (Line 13) Public Properties
body : Phaser.Physics.Arcade.Body | Phaser.Physics.P2.Body | Phaser.Physics.Ninja.Body | null
body is the Game Objects physics body. Once a Game Object is enabled for physics you access all associatedproperties and methods via it. By default Game Objects won't add themselves to any physics system and their body property will be null. To enable this Game Object for physics you need to call game.physics.enable(object, system) where object is this objectand system is the Physics system you are using. If none is given it defaults to Phaser.Physics.Arcade. You can alternatively call game.physics.arcade.enable(object), or add this Game Object to a physics enabled Group. Important: Enabling a Game Object for P2 or Ninja physics will automatically set its anchor property to 0.5,so the physics body is centered on the Game Object. If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. Type Phaser.Physics.Arcade.Body | Phaser.Physics.P2.Body | Phaser.Physics.Ninja.Body | null Source code: gameobjects/components/PhysicsBody.js (Line 91)
x : number
The position of the Game Object on the x axis relative to the local coordinates of the parent. Source code: gameobjects/components/PhysicsBody.js (Line 98)
y : number
The position of the Game Object on the y axis relative to the local coordinates of the parent. Source code: gameobjects/components/PhysicsBody.js (Line 124) Public Methods
<static> postUpdate()
The PhysicsBody component postUpdate handler.Called automatically by the Game Object. Source code: gameobjects/components/PhysicsBody.js (Line 61)
<static> preUpdate()
The PhysicsBody component preUpdate handler.Called automatically by the Game Object. Source code: gameobjects/components/PhysicsBody.js (Line 21)
|
QWhatsThis Class The QWhatsThis class provides a simple description of any widget, i.e. answering the question "What's This?". More...
Header:
#include <QWhatsThis>
qmake:
QT += widgets
List of all members, including inherited members Static Public Members
QAction *
createAction(QObject *parent = Q_NULLPTR)
void
enterWhatsThisMode()
void
hideText()
bool
inWhatsThisMode()
void
leaveWhatsThisMode()
void
showText(const QPoint &pos, const QString &text, QWidget *w = Q_NULLPTR)
Detailed Description The QWhatsThis class provides a simple description of any widget, i.e. answering the question "What's This?". "What's This?" help is part of an application's online help system, and provides users with information about the functionality and usage of a particular widget. "What's This?" help texts are typically longer and more detailed than tooltips, but generally provide less information than that supplied by separate help windows. QWhatsThis provides a single window with an explanatory text that pops up when the user asks "What's This?". The default way for users to ask the question is to move the focus to the relevant widget and press Shift+F1. The help text appears immediately; it goes away as soon as the user does something else. (Note that if there is a shortcut for Shift+F1, this mechanism will not work.) Some dialogs provide a "?" button that users can click to enter "What's This?" mode; they then click the relevant widget to pop up the "What's This?" window. It is also possible to provide a a menu option or toolbar button to switch into "What's This?" mode. To add "What's This?" text to a widget or an action, you simply call QWidget8b7c:f320:99b9:690f:4595:cd17:293a:c069setWhatsThis() or QAction8b7c:f320:99b9:690f:4595:cd17:293a:c069setWhatsThis(). The text can be either rich text or plain text. If you specify a rich text formatted string, it will be rendered using the default stylesheet, making it possible to embed images in the displayed text. To be as fast as possible, the default stylesheet uses a simple method to determine whether the text can be rendered as plain text. See Qt8b7c:f320:99b9:690f:4595:cd17:293a:c069mightBeRichText() for details. newAct = new QAction(tr("&New"), this);
newAct->setShortcut(tr("Ctrl+N"));
newAct->setStatusTip(tr("Create a new file"));
newAct->setWhatsThis(tr("Click this option to create a new file.")); An alternative way to enter "What's This?" mode is to call createAction(), and add the returned QAction to either a menu or a tool bar. By invoking this context help action (in the picture below, the button with the arrow and question mark icon) the user switches into "What's This?" mode. If they now click on a widget the appropriate help text is shown. The mode is left when help is given or when the user presses Esc.
You can enter "What's This?" mode programmatically with enterWhatsThisMode(), check the mode with inWhatsThisMode(), and return to normal mode with leaveWhatsThisMode(). If you want to control the "What's This?" behavior of a widget manually see Qt8b7c:f320:99b9:690f:4595:cd17:293a:c069WA_CustomWhatsThis. It is also possible to show different help texts for different regions of a widget, by using a QHelpEvent of type QEvent8b7c:f320:99b9:690f:4595:cd17:293a:c069WhatsThis. Intercept the help event in your widget's QWidget8b7c:f320:99b9:690f:4595:cd17:293a:c069vent() function and call QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069showText() with the text you want to display for the position specified in QHelpEvent8b7c:f320:99b9:690f:4595:cd17:293a:c069pos(). If the text is rich text and the user clicks on a link, the widget also receives a QWhatsThisClickedEvent with the link's reference as QWhatsThisClickedEvent8b7c:f320:99b9:690f:4595:cd17:293a:c069href(). If a QWhatsThisClickedEvent is handled (i.e. QWidget8b7c:f320:99b9:690f:4595:cd17:293a:c069vent() returns true), the help window remains visible. Call QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069hideText() to hide it explicitly. See also QToolTip. Member Function Documentation
[static] QAction *QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069reateAction(QObject *parent = Q_NULLPTR) Returns a ready-made QAction, used to invoke "What's This?" context help, with the given parent. The returned QAction provides a convenient way to let users enter "What's This?" mode.
[static] void QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069nterWhatsThisMode() This function switches the user interface into "What's This?" mode. The user interface can be switched back into normal mode by the user (e.g. by them clicking or pressing Esc), or programmatically by calling leaveWhatsThisMode(). When entering "What's This?" mode, a QEvent of type Qt8b7c:f320:99b9:690f:4595:cd17:293a:c069nterWhatsThisMode is sent to all toplevel widgets. See also inWhatsThisMode() and leaveWhatsThisMode().
[static] void QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069hideText() If a "What's This?" window is showing, this destroys it. See also showText().
[static] bool QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069inWhatsThisMode() Returns true if the user interface is in "What's This?" mode; otherwise returns false. See also enterWhatsThisMode().
[static] void QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069leaveWhatsThisMode() If the user interface is in "What's This?" mode, this function switches back to normal mode; otherwise it does nothing. When leaving "What's This?" mode, a QEvent of type Qt8b7c:f320:99b9:690f:4595:cd17:293a:c069LeaveWhatsThisMode is sent to all toplevel widgets. See also enterWhatsThisMode() and inWhatsThisMode().
[static] void QWhatsThis8b7c:f320:99b9:690f:4595:cd17:293a:c069showText(const QPoint &pos, const QString &text, QWidget *w = Q_NULLPTR) Shows text as a "What's This?" window, at global position pos. The optional widget argument, w, is used to determine the appropriate screen on multi-head systems. See also hideText().
|
dart:html
createNSResolver method @DomName('XPathEvaluator.createNSResolver') @DocsEditable() XPathNSResolver createNSResolver(Node nodeResolver) Source @DomName('XPathEvaluator.createNSResolver')
@DocsEditable()
XPathNSResolver createNSResolver(Node nodeResolver) =>
_blink.BlinkXPathEvaluator.instance
.createNSResolver_Callback_1_(this, nodeResolver);
|
Frequently Asked Questions (FAQ) What Kapacitor event handlers are supported in Chronograf? What applications are supported in Chronograf? How do I connect Chronograf to an InfluxEnterprise cluster? What visualization types does Chronograf support? What does the status column indicate on the Host List page? Why is my host’s status red when data are still arriving? Known Issues Why is my query’s field key order inconsistent? Why does the query builder break after I add my template variable to a query? What Kapacitor event handlers are supported in Chronograf? Chronograf integrates with Kapacitor, InfluxData’s data processing platform, to send alert messages to event handlers. Chronograf supports the following event handlers: Alerta Exec HipChat HTTP/Post Log (available in versions 360-397-9958+) OpsGenie PagerDuty Sensu Slack SMTP/Email Talk Telegram TCP VictorOps To configure a Kapacitor event handler in Chronograf, install Kapacitor and connect it to Chronograf. The Configure Kapacitor page includes the event handler configuration options; see the Configure Kapacitor Event Handlers guide for more information. What applications are supported in Chronograf? Chronograf offers pre-created dashboards for several Telegraf input plugins/applications. We list those applications below and link to their Telegraf documentation: Apache Consul Docker Elastic etcd HAProxy IIS InfluxDB Kubernetes Memcached Mesos MongoDB MySQL Network NGINX NSQ PHPfpm Ping PostgreSQL Processes RabbitMQ Redis Riak
System CPU Disk DiskIO Memory Net Netstat Processes Procstat
Varnish Windows Performance Counters Enable and disable applications in your Telegraf configuration file. See the Telegraf Configuration documentation for more information. How do I connect Chronograf to an InfluxEnterprise cluster? The connection details form requires additional information when connecting Chronograf to an InfluxEnterprise cluster. When you enter InfluxDB’s HTTP bind address in the Connection String input, Chronograf automatically checks if that InfluxDB instance is a data node. If it is a data node, Chronograf automatically adds the Meta Service Connection URL input to the connection details form. Enter the HTTP bind address of one of your cluster’s meta nodes into that input and Chronograf takes care of the rest. Note that the example above assumes that you do not have authentication enabled. If you have authentication enabled, the form requires username and password information. For more details about monitoring an InfluxEnterprise cluster, see the Monitor an InfluxEnterprise Cluster guide. What visualization types does Chronograf support? Chronograf’s dashboards support six visualization types. Line Show time-series in a line graph. Stacked Show time-series arranged on top of each other. Step-Plot Show time-series in a staircase graph. SingleStat Show the time-series’ single most recent value. If a cell’s query includes a GROUP BY tag clause, Chronograf sorts the different series lexicographically and shows the most recent field value associated with the first series. For example, if a query groups by the name tag key and name has two tag values (chronelda and chronz), Chronograf shows the most recent field value associated with the chronelda series. If a cell’s query includes more than one field key in the SELECT clause, Chronograf returns the most recent field value associated with the first field key in the SELECT clause. For example, if a query’s SELECT clause is SELECT "chronogiraffe","chronelda", Chronograf shows the most recent field value associated with the chronogiraffe field key. Line+Stat Show time-series in a line graph and overlay the time-series’ single most recent value. Bar Show time-series in a bar chart. Bar graphs are available in versions 360-397-9958+. What does the status column indicate on the Host List page? The status icon is a high-level measure of your host’s health. If Chronograf has not received data from a host for the past minute, the status icon is red. If Chronograf has received data from a host within the past minute, the status icon is green. Why is my host’s status red when data are still arriving? There are several possible explanations for an inaccurate red status icon: The status icon depends on your host’s local time in UTC. Use the Network Time Protocol (NTP) to synchronize time between hosts; if hosts’ clocks aren’t synchronized with NTP, the status icon can be inaccurate. The status icon turns red when Chronograf has not received data from a host for the past minute. Chronograf uses data from Telegraf to perform that calculation. By default, Telegraf sends data in ten-second intervals; you can change that interval setting in Telegraf’s configuration file. If you configure the setting to an interval that’s greater than one minute, Chronograf assumes that the host is not reporting data and changes the status icon to red. Why is my query’s field key order inconsistent? In versions 1.3.0-1.3.1, Chronograf doesn’t preserve the order of the items in the SELECT clause in query editor mode. Chronograf may change the order of the items in the SELECT clause after it executes the query and populates the cell with the query results. This issue affects the SingleStat and Line+Stat graph types. If a cell’s query includes more than one field key in the SELECT clause, Chronograf returns the most recent stat associated with the first field key in the SELECT clause. If you sorted the field keys in your query to rely on that behavior, it is important to note that Chronograf may change that order when it executes your query. This is a known issue and it is fixed in versions 360-397-9958+. Why does the query builder break after I add my template variable to a query? Currently, adding a template variable to a cell’s query renders the query builder unusable. If you click on a database in the builder’s Databases column after adding a template variable to your query, Chronograf simply overwrites your existing query. Note that this behavior does not apply to Chronograf’s pre-created template variable: :dashboardTime:. This is a known issue and it will be fixed in a future release.
|
apply_filters( 'rest_pre_echo_response', array $result, WP_REST_Server $server, WP_REST_Request $request ) Filters the REST API response. Description Allows modification of the response data after inserting embedded data (if any) and before echoing the response data. Parameters $result array Response data to send to the client. $server WP_REST_Server Server instance. $request WP_REST_Request Request used to generate the response. Source File: wp-includes/rest-api/class-wp-rest-server.php. View all references $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
Related Used By Used By Description WP_REST_Server8b7c:f320:99b9:690f:4595:cd17:293a:c069serve_request() wp-includes/rest-api/class-wp-rest-server.php Handles serving a REST API request.
Changelog Version Description 4.8.1 Introduced.
|
love.touch.getPressure
Available since LÖVE 0.10.0 This function is not supported in earlier versions. Gets the current pressure of the specified touch-press. Function Synopsis pressure = love.touch.getPressure( id ) Arguments
light userdata id The identifier of the touch-press. Use love.touch.getTouches, love.touchpressed, or love.touchmoved to obtain touch id values.
Returns
number pressure The pressure of the touch-press. Most touch screens aren't pressure sensitive, in which case the pressure will be 1.
See Also
love.touch
love.touch.getTouches
love.touchpressed
love.touchmoved
|
dart:html
shadowRoot property ShadowRoot shadowRoot Source @DomName('Element.shadowRoot')
@DocsEditable()
// https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#api-shadow-aware-create-shadow-root
@Experimental()
ShadowRoot get shadowRoot =>
_blink.BlinkElement.instance.shadowRoot_Getter_(this);
|
get_theme_root_uri( string $stylesheet_or_template = '', string $theme_root = '' ): string Retrieves URI for themes directory. Description Does not have trailing slash. Parameters $stylesheet_or_template string Optional The stylesheet or template name of the theme. Default is to leverage the main theme root. Default: '' $theme_root string Optional The theme root for which calculations will be based, preventing the need for a get_raw_theme_root() call. Default: '' Return string Themes directory URI. Source File: wp-includes/theme.php. View all references function get_theme_root_uri( $stylesheet_or_template = '', $theme_root = '' ) {
global $wp_theme_directories;
if ( $stylesheet_or_template && ! $theme_root ) {
$theme_root = get_raw_theme_root( $stylesheet_or_template );
}
if ( $stylesheet_or_template && $theme_root ) {
if ( in_array( $theme_root, (array) $wp_theme_directories, true ) ) {
// Absolute path. Make an educated guess. YMMV -- but note the filter below.
if ( 0 === strpos( $theme_root, WP_CONTENT_DIR ) ) {
$theme_root_uri = content_url( str_replace( WP_CONTENT_DIR, '', $theme_root ) );
} elseif ( 0 === strpos( $theme_root, ABSPATH ) ) {
$theme_root_uri = site_url( str_replace( ABSPATH, '', $theme_root ) );
} elseif ( 0 === strpos( $theme_root, WP_PLUGIN_DIR ) || 0 === strpos( $theme_root, WPMU_PLUGIN_DIR ) ) {
$theme_root_uri = plugins_url( basename( $theme_root ), $theme_root );
} else {
$theme_root_uri = $theme_root;
}
} else {
$theme_root_uri = content_url( $theme_root );
}
} else {
$theme_root_uri = content_url( 'themes' );
}
/**
* Filters the URI for themes directory.
*
* @since 1.5.0
*
* @param string $theme_root_uri The URI for themes directory.
* @param string $siteurl WordPress web address which is set in General Options.
* @param string $stylesheet_or_template The stylesheet or template name of the theme.
*/
return apply_filters( 'theme_root_uri', $theme_root_uri, get_option( 'siteurl' ), $stylesheet_or_template );
}
Hooks apply_filters( 'theme_root_uri', string $theme_root_uri, string $siteurl, string $stylesheet_or_template )
Filters the URI for themes directory. Related Uses Uses Description get_raw_theme_root() wp-includes/theme.php Gets the raw theme root relative to the content directory with no filters applied. content_url() wp-includes/link-template.php Retrieves the URL to the content directory. plugins_url() wp-includes/link-template.php Retrieves a URL within the plugins or mu-plugins directory. site_url() wp-includes/link-template.php Retrieves the URL for the current site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible. apply_filters() wp-includes/plugin.php Calls the callback functions that have been added to a filter hook. get_option() wp-includes/option.php Retrieves an option value based on an option name.
Used By Used By Description get_stylesheet_directory_uri() wp-includes/theme.php Retrieves stylesheet directory URI for the active theme. get_template_directory_uri() wp-includes/theme.php Retrieves template directory URI for the active theme. WP_Them8b7c:f320:99b9:690f:4595:cd17:293a:c069get_theme_root_uri() wp-includes/class-wp-theme.php Returns the URL to the directory of the theme root.
Changelog Version Description 1.5.0 Introduced.
|
AbstractQueuedSynchronizer
package java.util.concurrent.locks
extends AbstractOwnableSynchronizer implements Serializable
extended by ReentrantLock_Sync
Available on java
Methods
finalacquire(param1:Int):Void
finalacquireInterruptibly(param1:Int):Void
finalacquireShared(param1:Int):Void
finalacquireSharedInterruptibly(param1:Int):Void
finalgetExclusiveQueuedThreads():Collection<Thread>
finalgetFirstQueuedThread():Thread
finalgetQueueLength():Int
finalgetQueuedThreads():Collection<Thread>
finalgetSharedQueuedThreads():Collection<Thread>
finalgetWaitQueueLength(param1:AbstractQueuedSynchronizer_ConditionObject):Int
finalgetWaitingThreads(param1:AbstractQueuedSynchronizer_ConditionObject):Collection<Thread>
finalhasContended():Bool
finalhasQueuedPredecessors():Bool
finalhasQueuedThreads():Bool
finalhasWaiters(param1:AbstractQueuedSynchronizer_ConditionObject):Bool
finalisQueued(param1:Thread):Bool
finalowns(param1:AbstractQueuedSynchronizer_ConditionObject):Bool
finalrelease(param1:Int):Bool
finalreleaseShared(param1:Int):Bool
toString():String
finaltryAcquireNanos(param1:Int, param2:Int64):Bool
finaltryAcquireSharedNanos(param1:Int, param2:Int64):Bool
|
Interface Doc All Superinterfaces: Comparable<Object> All Known Subinterfaces:
AnnotationTypeDoc, AnnotationTypeElementDoc, ClassDoc, ConstructorDoc, ExecutableMemberDoc, FieldDoc, MemberDoc, MethodDoc, PackageDoc, ProgramElementDoc, RootDoc
@Deprecated(since="9",
forRemoval=true)
public interface Doc
extends Comparable<Object>
Deprecated, for removal: This API element is subject to removal in a future version. The declarations in this package have been superseded by those in the package jdk.javadoc.doclet. For more information, see the Migration Guide in the documentation for that package. Represents Java language constructs (package, class, constructor, method, field) which have comments and have been processed by this run of javadoc. All Doc objects are unique, that is, they are == comparable. Since: 1.2 Methods Modifier and Type Method Description String commentText() Deprecated, for removal: This API element is subject to removal in a future version. Return the text of the comment for this doc item. int compareTo(Object obj) Deprecated, for removal: This API element is subject to removal in a future version. Compares this doc object with the specified object for order. Tag[] firstSentenceTags() Deprecated, for removal: This API element is subject to removal in a future version. Return the first sentence of the comment as an array of tags. String getRawCommentText() Deprecated, for removal: This API element is subject to removal in a future version. Return the full unprocessed text of the comment. Tag[] inlineTags() Deprecated, for removal: This API element is subject to removal in a future version. Return comment as an array of tags. boolean isAnnotationType() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an annotation type? boolean isAnnotationTypeElement() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an annotation type element? boolean isClass() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a class (and not an interface or annotation type)? boolean isConstructor() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a constructor? boolean isEnum() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an enum type? boolean isEnumConstant() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an enum constant? boolean isError() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an error class? boolean isException() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an exception class? boolean isField() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a field (but not an enum constant)? boolean isIncluded() Deprecated, for removal: This API element is subject to removal in a future version. Return true if this Doc item is included in the result set. boolean isInterface() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an interface (but not an annotation type)? boolean isMethod() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a method (but not a constructor or annotation type element)? boolean isOrdinaryClass() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an ordinary class? String name() Deprecated, for removal: This API element is subject to removal in a future version. Returns the non-qualified name of this Doc item. SourcePosition position() Deprecated, for removal: This API element is subject to removal in a future version. Return the source position of the first line of the corresponding declaration, or null if no position is available. SeeTag[] seeTags() Deprecated, for removal: This API element is subject to removal in a future version. Return the see also tags in this Doc item. void setRawCommentText(String rawDocumentation) Deprecated, for removal: This API element is subject to removal in a future version. Set the full unprocessed text of the comment. Tag[] tags() Deprecated, for removal: This API element is subject to removal in a future version. Return all tags in this Doc item. Tag[] tags(String tagname) Deprecated, for removal: This API element is subject to removal in a future version. Return tags of the specified kind in this Doc item. Methods commentText String commentText() Deprecated, for removal: This API element is subject to removal in a future version. Return the text of the comment for this doc item. Tags have been removed. Returns: the text of the comment for this doc item. tags Tag[] tags() Deprecated, for removal: This API element is subject to removal in a future version. Return all tags in this Doc item. Returns: an array of Tag objects containing all tags on this Doc item. tags Tag[] tags(String tagname) Deprecated, for removal: This API element is subject to removal in a future version. Return tags of the specified kind in this Doc item. For example, if 'tagname' has value "@serial", all tags in this Doc item of kind "@serial" will be returned. Parameters:
tagname - name of the tag kind to search for. Returns: an array of Tag containing all tags whose 'kind()' matches 'tagname'. seeTags SeeTag[] seeTags() Deprecated, for removal: This API element is subject to removal in a future version. Return the see also tags in this Doc item. Returns: an array of SeeTag containing all @see tags. inlineTags Tag[] inlineTags() Deprecated, for removal: This API element is subject to removal in a future version. Return comment as an array of tags. Includes inline tags (i.e. {@link reference} tags) but not block tags. Each section of plain text is represented as a Tag of kind "Text". Inline tags are represented as a SeeTag of kind "@see" and name "@link". Returns: an array of Tags representing the comment firstSentenceTags Tag[] firstSentenceTags() Deprecated, for removal: This API element is subject to removal in a future version.
Return the first sentence of the comment as an array of tags. Includes inline tags (i.e. {@link reference} tags) but not block tags. Each section of plain text is represented as a Tag of kind "Text". Inline tags are represented as a SeeTag of kind "@see" and name "@link".
If the locale is English language, the first sentence is determined by the rules described in the Java Language Specification (first version): "This sentence ends at the first period that is followed by a blank, tab, or line terminator or at the first tagline.", in addition a line will be terminated by block HTML tags: <p> </p> <h1> <h2> <h3> <h4> <h5> <h6> <hr> <pre> or </pre>. If the locale is not English, the sentence end will be determined by BreakIterator.getSentenceInstance(Locale).
Returns: an array of Tags representing the first sentence of the comment getRawCommentText String getRawCommentText() Deprecated, for removal: This API element is subject to removal in a future version. Return the full unprocessed text of the comment. Tags are included as text. Used mainly for store and retrieve operations like internalization. Returns: the full unprocessed text of the comment. setRawCommentText void setRawCommentText(String rawDocumentation) Deprecated, for removal: This API element is subject to removal in a future version. Set the full unprocessed text of the comment. Tags are included as text. Used mainly for store and retrieve operations like internalization. Parameters:
rawDocumentation - A String containing the full unprocessed text of the comment. name String name() Deprecated, for removal: This API element is subject to removal in a future version. Returns the non-qualified name of this Doc item. Returns: the name compareTo int compareTo(Object obj) Deprecated, for removal: This API element is subject to removal in a future version.
Compares this doc object with the specified object for order. Returns a negative integer, zero, or a positive integer as this doc object is less than, equal to, or greater than the given object.
This method satisfies the Comparable interface.
Specified by:
compareTo in interface Comparable<Object>
Parameters:
obj - the Object to be compared. Returns: a negative integer, zero, or a positive integer as this Object is less than, equal to, or greater than the given Object. Throws:
ClassCastException - the specified Object's type prevents it from being compared to this Object. isField boolean isField() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a field (but not an enum constant)? Returns: true if it represents a field isEnumConstant boolean isEnumConstant() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an enum constant? Returns: true if it represents an enum constant Since: 1.5 isConstructor boolean isConstructor() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a constructor? Returns: true if it represents a constructor isMethod boolean isMethod() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a method (but not a constructor or annotation type element)? Returns: true if it represents a method isAnnotationTypeElement boolean isAnnotationTypeElement() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an annotation type element? Returns: true if it represents an annotation type element Since: 1.5 isInterface boolean isInterface() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an interface (but not an annotation type)? Returns: true if it represents an interface isException boolean isException() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an exception class? Returns: true if it represents an exception isError boolean isError() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an error class? Returns: true if it represents a error isEnum boolean isEnum() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an enum type? Returns: true if it represents an enum type Since: 1.5 isAnnotationType boolean isAnnotationType() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an annotation type? Returns: true if it represents an annotation type Since: 1.5 isOrdinaryClass boolean isOrdinaryClass() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item an ordinary class? (i.e. not an interface, annotation type, enum, exception, or error)? Returns: true if it represents an ordinary class isClass boolean isClass() Deprecated, for removal: This API element is subject to removal in a future version. Is this Doc item a class (and not an interface or annotation type)? This includes ordinary classes, enums, errors and exceptions. Returns: true if it represents a class isIncluded boolean isIncluded() Deprecated, for removal: This API element is subject to removal in a future version. Return true if this Doc item is included in the result set. Returns: true if this Doc item is included in the result set. position SourcePosition position() Deprecated, for removal: This API element is subject to removal in a future version. Return the source position of the first line of the corresponding declaration, or null if no position is available. A default constructor returns null because it has no location in the source file. Returns: the source positino of the first line of the corresponding declaration, or null if no position is available. A default constructor returns null because it has no location in the source file. Since: 1.4
|
Looking Up and Expanding Abbreviations Abbrevs are usually expanded by certain interactive commands, including self-insert-command. This section describes the subroutines used in writing such commands, as well as the variables they use for communication. Function: abbrev-symbol abbrev &optional table
This function returns the symbol representing the abbrev named abbrev. It returns nil if that abbrev is not defined. The optional second argument table is the abbrev table in which to look it up. If table is nil, this function tries first the current buffer’s local abbrev table, and second the global abbrev table.
Function: abbrev-expansion abbrev &optional table
This function returns the string that abbrev would expand into (as defined by the abbrev tables used for the current buffer). It returns nil if abbrev is not a valid abbrev. The optional argument table specifies the abbrev table to use, as in abbrev-symbol.
Command: expand-abbrev
This command expands the abbrev before point, if any. If point does not follow an abbrev, this command does nothing. To do the expansion, it calls the function that is the value of the abbrev-expand-function variable, with no arguments, and returns whatever that function does. The default expansion function returns the abbrev symbol if it did expansion, and nil otherwise. If the abbrev symbol has a hook function that is a symbol whose no-self-insert property is non-nil, and if the hook function returns nil as its value, then the default expansion function returns nil, even though expansion did occur.
Function: abbrev-insert abbrev &optional name start end
This function inserts the abbrev expansion of abbrev, replacing the text between start and end. If start is omitted, it defaults to point. name, if non-nil, should be the name by which this abbrev was found (a string); it is used to figure out whether to adjust the capitalization of the expansion. The function returns abbrev if the abbrev was successfully inserted, otherwise it returns nil.
Command: abbrev-prefix-mark &optional arg
This command marks the current location of point as the beginning of an abbrev. The next call to expand-abbrev will use the text from here to point (where it is then) as the abbrev to expand, rather than using the previous word as usual. First, this command expands any abbrev before point, unless arg is non-nil. (Interactively, arg is the prefix argument.) Then it inserts a hyphen before point, to indicate the start of the next abbrev to be expanded. The actual expansion removes the hyphen.
User Option: abbrev-all-caps
When this is set non-nil, an abbrev entered entirely in upper case is expanded using all upper case. Otherwise, an abbrev entered entirely in upper case is expanded by capitalizing each word of the expansion.
Variable: abbrev-start-location
The value of this variable is a buffer position (an integer or a marker) for expand-abbrev to use as the start of the next abbrev to be expanded. The value can also be nil, which means to use the word before point instead. abbrev-start-location is set to nil each time expand-abbrev is called. This variable is also set by abbrev-prefix-mark.
Variable: abbrev-start-location-buffer
The value of this variable is the buffer for which abbrev-start-location has been set. Trying to expand an abbrev in any other buffer clears abbrev-start-location. This variable is set by abbrev-prefix-mark.
Variable: last-abbrev
This is the abbrev-symbol of the most recent abbrev expanded. This information is left by expand-abbrev for the sake of the unexpand-abbrev command (see Expanding Abbrevs in The GNU Emacs Manual).
Variable: last-abbrev-location
This is the location of the most recent abbrev expanded. This contains information left by expand-abbrev for the sake of the unexpand-abbrev command.
Variable: last-abbrev-text
This is the exact expansion text of the most recent abbrev expanded, after case conversion (if any). Its value is nil if the abbrev has already been unexpanded. This contains information left by expand-abbrev for the sake of the unexpand-abbrev command.
Variable: abbrev-expand-function
The value of this variable is a function that expand-abbrev will call with no arguments to do the expansion. The function can do anything it wants before and after performing the expansion. It should return the abbrev symbol if expansion took place.
The following sample code shows a simple use of abbrev-expand-function. It assumes that foo-mode is a mode for editing certain files in which lines that start with ‘#’ are comments. You want to use Text mode abbrevs for those lines. The regular local abbrev table, foo-mode-abbrev-table is appropriate for all other lines. See Standard Abbrev Tables, for the definitions of local-abbrev-table and text-mode-abbrev-table. See Advising Functions, for details of add-function. (defun foo-mode-abbrev-expand-function (expand)
(if (not (save-excursion (forward-line 0) (eq (char-after) ?#)))
;; Performs normal expansion.
(funcall expand)
;; We're inside a comment: use the text-mode abbrevs.
(let ((local-abbrev-table text-mode-abbrev-table))
(funcall expand))))
(add-hook 'foo-mode-hook
(lambda ()
(add-function :around (local 'abbrev-expand-function)
#'foo-mode-abbrev-expand-function)))
Copyright
|
:picture-in-picture
The :picture-in-picture CSS pseudo-class matches the element which is currently in picture-in-picture mode.
Syntax
:picture-in-picture
Usage notes
The :picture-in-picture pseudo-class lets you configure your stylesheets to automatically adjust the size, style, or layout of content when a video switches back and forth between picture-in-picture and traditional presentation modes.Examples
In this example, a video has a box shadow when it is displayed in the floating window.HTML
The page's HTML looks like this: <h1>MDN Web Docs Demo: :picture-in-picture pseudo-class</h1>
<p>This demo uses the <code>:picture-in-picture</code> pseudo-class to automatically
change the style of a video entirely using CSS.</p>
<video id="pip-video"></video>
The <video> with the ID "pip-video" will change between having a red box shadow or not, depending on whether or not it is displayed in the picture-in-picture floating window.
CSS
The magic happens in the CSS. :picture-in-picture {
box-shadow: 0 0 0 5px red;
}
Specifications
Specification
Selectors Level 4 # pip-state
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
:picture-in-picture
76
79
No
No
63
No
76
76
No
54
No
12.0
See also
Picture-in-picture API HTMLVideoElement.requestPictureInPicture() HTMLVideoElement.autoPictureInPicture HTMLVideoElement.disablePictureInPicture Document.pictureInPictureEnabled Document.exitPictureInPicture() Document.pictureInPictureElement
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: May 25, 2022, by MDN contributors
|
Illuminate\Container Classes BoundMethod Container ContextualBindingBuilder RewindableGenerator Exceptions EntryNotFoundException
|
Deprecation: Local Mode Listen (CHEF-18) [edit on GitHub] When using chef-client Local Mode, there are two ways to launch the internal Chef Zero server. Originally we launched it as a normal network service on localhost and then connected to it as per normal. Unfortunately this meant that any user or process on the machine could also connect to the Zero server during the converge and because Chef Zero has no authentication or authorization systems, they could potentially alter data mid-converge. We later added a “socketless” mode, which runs the Zero server completely internally and never exposes it on a real socket. Remediation If you need to re-enable socket mode for now, you can run chef-client –local-mode –listen or set knife[:listen] = true in your .chef/knife.rb or .chef/config.rb.
|
formatISO9075
Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).
Description
Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.
Usage
// CommonJS
var formatISO9075 = require('date-fns/formatISO9075')
// ES 2015
import formatISO9075 from 'date-fns/formatISO9075'
// ESM
import { formatISO9075 } from 'date-fns'
Syntax
formatISO9075(date, [options])
Arguments
Name
Description
date
the original date
options
an object with options.
options.format
if 'basic', hide delimiters between date and time values.
options.representation
format date, time, or both.
Returns
Description
the formatted date string
Exceptions
Type
Description
TypeError
1 argument required
RangeError
date must not be Invalid Date
RangeError
options.format must be 'extended' or 'basic'
RangeError
options.representation must be 'date', 'time' or 'complete'
Examples
// Represent 18 September 2019 in ISO 9075 format:
const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))
//=> '2019-09-18 19:00:52'
// Represent 18 September 2019 in ISO 9075, short format:
const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })
//=> '20190918 190052'
// Represent 18 September 2019 in ISO 9075 format, date only:
const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })
//=> '2019-09-18'
// Represent 18 September 2019 in ISO 9075 format, time only:
const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })
//=> '19:00:52'
|
libvirt_lxc – Run tasks in lxc containers via libvirt Synopsis Parameters Status Synopsis Run commands or put/fetch files to an existing lxc container using libvirt Parameters Parameter Choices/Defaults Configuration Comments remote_addr - Default:"The set user as per docker\u0027s configuration" var: ansible_host var: ansible_libvirt_lxc_host Container identifier Status This connection is not guaranteed to have a backwards compatible interface. [preview]
This connection is maintained by the Ansible Community. [community]
Authors Michael Scherer <[email protected]> Hint If you notice any issues in this documentation, you can edit this document to improve it. Hint Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
© 2012–2018 Michael DeHaan
|
pandas.DataFrame.asfreq
DataFrame.asfreq(freq, method=None, how=None, normalize=False) [source]
Convert TimeSeries to specified frequency. Optionally provide filling method to pad/backfill missing values.
Parameters:
freq : DateOffset object, or string method : {‘backfill’/’bfill’, ‘pad’/’ffill’}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): ‘pad’ / ‘ffill’: propagate last valid observation forward to next valid ‘backfill’ / ‘bfill’: use NEXT valid observation to fill how : {‘start’, ‘end’}, default end For PeriodIndex only, see PeriodIndex.asfreq normalize : bool, default False Whether to reset output index to midnight
Returns:
converted : type of caller Notes To learn more about the frequency strings, please see this link.
|
CREATE AGGREGATE CREATE AGGREGATE — define a new aggregate function Synopsis
CREATE [ OR REPLACE ] AGGREGATE name ( [ argmode ] [ argname ] arg_data_type [ , ... ] ) (
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , COMBINEFUNC = combinefunc ]
[ , SERIALFUNC = serialfunc ]
[ , DESERIALFUNC = deserialfunc ]
[ , INITCOND = initial_condition ]
[ , MSFUNC = msfunc ]
[ , MINVFUNC = minvfunc ]
[ , MSTYPE = mstate_data_type ]
[ , MSSPACE = mstate_data_size ]
[ , MFINALFUNC = mffunc ]
[ , MFINALFUNC_EXTRA ]
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = minitial_condition ]
[ , SORTOP = sort_operator ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
)
CREATE [ OR REPLACE ] AGGREGATE name ( [ [ argmode ] [ argname ] arg_data_type [ , ... ] ]
ORDER BY [ argmode ] [ argname ] arg_data_type [ , ... ] ) (
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , INITCOND = initial_condition ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
[ , HYPOTHETICAL ]
)
or the old syntax
CREATE [ OR REPLACE ] AGGREGATE name (
BASETYPE = base_type,
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , COMBINEFUNC = combinefunc ]
[ , SERIALFUNC = serialfunc ]
[ , DESERIALFUNC = deserialfunc ]
[ , INITCOND = initial_condition ]
[ , MSFUNC = msfunc ]
[ , MINVFUNC = minvfunc ]
[ , MSTYPE = mstate_data_type ]
[ , MSSPACE = mstate_data_size ]
[ , MFINALFUNC = mffunc ]
[ , MFINALFUNC_EXTRA ]
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = minitial_condition ]
[ , SORTOP = sort_operator ]
)
Description CREATE AGGREGATE defines a new aggregate function. CREATE OR REPLACE AGGREGATE will either define a new aggregate function or replace an existing definition. Some basic and commonly-used aggregate functions are included with the distribution; they are documented in Section 9.21. If one defines new types or needs an aggregate function not already provided, then CREATE AGGREGATE can be used to provide the desired features. When replacing an existing definition, the argument types, result type, and number of direct arguments may not be changed. Also, the new definition must be of the same kind (ordinary aggregate, ordered-set aggregate, or hypothetical-set aggregate) as the old one. If a schema name is given (for example, CREATE AGGREGATE myschema.myagg ...) then the aggregate function is created in the specified schema. Otherwise it is created in the current schema. An aggregate function is identified by its name and input data type(s). Two aggregates in the same schema can have the same name if they operate on different input types. The name and input data type(s) of an aggregate must also be distinct from the name and input data type(s) of every ordinary function in the same schema. This behavior is identical to overloading of ordinary function names (see CREATE FUNCTION). A simple aggregate function is made from one or two ordinary functions: a state transition function sfunc, and an optional final calculation function ffunc. These are used as follows:
sfunc( internal-state, next-data-values ) ---> next-internal-state
ffunc( internal-state ) ---> aggregate-value
PostgreSQL creates a temporary variable of data type stype to hold the current internal state of the aggregate. At each input row, the aggregate argument value(s) are calculated and the state transition function is invoked with the current state value and the new argument value(s) to calculate a new internal state value. After all the rows have been processed, the final function is invoked once to calculate the aggregate's return value. If there is no final function then the ending state value is returned as-is. An aggregate function can provide an initial condition, that is, an initial value for the internal state value. This is specified and stored in the database as a value of type text, but it must be a valid external representation of a constant of the state value data type. If it is not supplied then the state value starts out null. If the state transition function is declared “strict”, then it cannot be called with null inputs. With such a transition function, aggregate execution behaves as follows. Rows with any null input values are ignored (the function is not called and the previous state value is retained). If the initial state value is null, then at the first row with all-nonnull input values, the first argument value replaces the state value, and the transition function is invoked at each subsequent row with all-nonnull input values. This is handy for implementing aggregates like max. Note that this behavior is only available when state_data_type is the same as the first arg_data_type. When these types are different, you must supply a nonnull initial condition or use a nonstrict transition function. If the state transition function is not strict, then it will be called unconditionally at each input row, and must deal with null inputs and null state values for itself. This allows the aggregate author to have full control over the aggregate's handling of null values. If the final function is declared “strict”, then it will not be called when the ending state value is null; instead a null result will be returned automatically. (Of course this is just the normal behavior of strict functions.) In any case the final function has the option of returning a null value. For example, the final function for avg returns null when it sees there were zero input rows. Sometimes it is useful to declare the final function as taking not just the state value, but extra parameters corresponding to the aggregate's input values. The main reason for doing this is if the final function is polymorphic and the state value's data type would be inadequate to pin down the result type. These extra parameters are always passed as NULL (and so the final function must not be strict when the FINALFUNC_EXTRA option is used), but nonetheless they are valid parameters. The final function could for example make use of get_fn_expr_argtype to identify the actual argument type in the current call. An aggregate can optionally support moving-aggregate mode, as described in Section 37.12.1. This requires specifying the MSFUNC, MINVFUNC, and MSTYPE parameters, and optionally the MSSPACE, MFINALFUNC, MFINALFUNC_EXTRA, MFINALFUNC_MODIFY, and MINITCOND parameters. Except for MINVFUNC, these parameters work like the corresponding simple-aggregate parameters without M; they define a separate implementation of the aggregate that includes an inverse transition function. The syntax with ORDER BY in the parameter list creates a special type of aggregate called an ordered-set aggregate; or if HYPOTHETICAL is specified, then a hypothetical-set aggregate is created. These aggregates operate over groups of sorted values in order-dependent ways, so that specification of an input sort order is an essential part of a call. Also, they can have direct arguments, which are arguments that are evaluated only once per aggregation rather than once per input row. Hypothetical-set aggregates are a subclass of ordered-set aggregates in which some of the direct arguments are required to match, in number and data types, the aggregated argument columns. This allows the values of those direct arguments to be added to the collection of aggregate-input rows as an additional “hypothetical” row. An aggregate can optionally support partial aggregation, as described in Section 37.12.4. This requires specifying the COMBINEFUNC parameter. If the state_data_type is internal, it's usually also appropriate to provide the SERIALFUNC and DESERIALFUNC parameters so that parallel aggregation is possible. Note that the aggregate must also be marked PARALLEL SAFE to enable parallel aggregation. Aggregates that behave like MIN or MAX can sometimes be optimized by looking into an index instead of scanning every input row. If this aggregate can be so optimized, indicate it by specifying a sort operator. The basic requirement is that the aggregate must yield the first element in the sort ordering induced by the operator; in other words:
SELECT agg(col) FROM tab;
must be equivalent to:
SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;
Further assumptions are that the aggregate ignores null inputs, and that it delivers a null result if and only if there were no non-null inputs. Ordinarily, a data type's < operator is the proper sort operator for MIN, and > is the proper sort operator for MAX. Note that the optimization will never actually take effect unless the specified operator is the “less than” or “greater than” strategy member of a B-tree index operator class. To be able to create an aggregate function, you must have USAGE privilege on the argument types, the state type(s), and the return type, as well as EXECUTE privilege on the supporting functions. Parameters name The name (optionally schema-qualified) of the aggregate function to create. argmode The mode of an argument: IN or VARIADIC. (Aggregate functions do not support OUT arguments.) If omitted, the default is IN. Only the last argument can be marked VARIADIC. argname The name of an argument. This is currently only useful for documentation purposes. If omitted, the argument has no name. arg_data_type An input data type on which this aggregate function operates. To create a zero-argument aggregate function, write * in place of the list of argument specifications. (An example of such an aggregate is count(*).) base_type In the old syntax for CREATE AGGREGATE, the input data type is specified by a basetype parameter rather than being written next to the aggregate name. Note that this syntax allows only one input parameter. To define a zero-argument aggregate function with this syntax, specify the basetype as "ANY" (not *). Ordered-set aggregates cannot be defined with the old syntax. sfunc The name of the state transition function to be called for each input row. For a normal N-argument aggregate function, the sfunc must take N+1 arguments, the first being of type state_data_type and the rest matching the declared input data type(s) of the aggregate. The function must return a value of type state_data_type. This function takes the current state value and the current input data value(s), and returns the next state value. For ordered-set (including hypothetical-set) aggregates, the state transition function receives only the current state value and the aggregated arguments, not the direct arguments. Otherwise it is the same. state_data_type The data type for the aggregate's state value. state_data_size The approximate average size (in bytes) of the aggregate's state value. If this parameter is omitted or is zero, a default estimate is used based on the state_data_type. The planner uses this value to estimate the memory required for a grouped aggregate query. ffunc The name of the final function called to compute the aggregate's result after all input rows have been traversed. For a normal aggregate, this function must take a single argument of type state_data_type. The return data type of the aggregate is defined as the return type of this function. If ffunc is not specified, then the ending state value is used as the aggregate's result, and the return type is state_data_type. For ordered-set (including hypothetical-set) aggregates, the final function receives not only the final state value, but also the values of all the direct arguments. If FINALFUNC_EXTRA is specified, then in addition to the final state value and any direct arguments, the final function receives extra NULL values corresponding to the aggregate's regular (aggregated) arguments. This is mainly useful to allow correct resolution of the aggregate result type when a polymorphic aggregate is being defined.
FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } This option specifies whether the final function is a pure function that does not modify its arguments. READ_ONLY indicates it does not; the other two values indicate that it may change the transition state value. See Notes below for more detail. The default is READ_ONLY, except for ordered-set aggregates, for which the default is READ_WRITE. combinefunc The combinefunc function may optionally be specified to allow the aggregate function to support partial aggregation. If provided, the combinefunc must combine two state_data_type values, each containing the result of aggregation over some subset of the input values, to produce a new state_data_type that represents the result of aggregating over both sets of inputs. This function can be thought of as an sfunc, where instead of acting upon an individual input row and adding it to the running aggregate state, it adds another aggregate state to the running state. The combinefunc must be declared as taking two arguments of the state_data_type and returning a value of the state_data_type. Optionally this function may be “strict”. In this case the function will not be called when either of the input states are null; the other state will be taken as the correct result. For aggregate functions whose state_data_type is internal, the combinefunc must not be strict. In this case the combinefunc must ensure that null states are handled correctly and that the state being returned is properly stored in the aggregate memory context. serialfunc An aggregate function whose state_data_type is internal can participate in parallel aggregation only if it has a serialfunc function, which must serialize the aggregate state into a bytea value for transmission to another process. This function must take a single argument of type internal and return type bytea. A corresponding deserialfunc is also required. deserialfunc Deserialize a previously serialized aggregate state back into state_data_type. This function must take two arguments of types bytea and internal, and produce a result of type internal. (Note: the second, internal argument is unused, but is required for type safety reasons.) initial_condition The initial setting for the state value. This must be a string constant in the form accepted for the data type state_data_type. If not specified, the state value starts out null. msfunc The name of the forward state transition function to be called for each input row in moving-aggregate mode. This is exactly like the regular transition function, except that its first argument and result are of type mstate_data_type, which might be different from state_data_type. minvfunc The name of the inverse state transition function to be used in moving-aggregate mode. This function has the same argument and result types as msfunc, but it is used to remove a value from the current aggregate state, rather than add a value to it. The inverse transition function must have the same strictness attribute as the forward state transition function. mstate_data_type The data type for the aggregate's state value, when using moving-aggregate mode. mstate_data_size The approximate average size (in bytes) of the aggregate's state value, when using moving-aggregate mode. This works the same as state_data_size. mffunc The name of the final function called to compute the aggregate's result after all input rows have been traversed, when using moving-aggregate mode. This works the same as ffunc, except that its first argument's type is mstate_data_type and extra dummy arguments are specified by writing MFINALFUNC_EXTRA. The aggregate result type determined by mffunc or mstate_data_type must match that determined by the aggregate's regular implementation.
MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } This option is like FINALFUNC_MODIFY, but it describes the behavior of the moving-aggregate final function. minitial_condition The initial setting for the state value, when using moving-aggregate mode. This works the same as initial_condition. sort_operator The associated sort operator for a MIN- or MAX-like aggregate. This is just an operator name (possibly schema-qualified). The operator is assumed to have the same input data types as the aggregate (which must be a single-argument normal aggregate).
PARALLEL = { SAFE | RESTRICTED | UNSAFE } The meanings of PARALLEL SAFE, PARALLEL RESTRICTED, and PARALLEL UNSAFE are the same as in CREATE FUNCTION. An aggregate will not be considered for parallelization if it is marked PARALLEL UNSAFE (which is the default!) or PARALLEL RESTRICTED. Note that the parallel-safety markings of the aggregate's support functions are not consulted by the planner, only the marking of the aggregate itself. HYPOTHETICAL For ordered-set aggregates only, this flag specifies that the aggregate arguments are to be processed according to the requirements for hypothetical-set aggregates: that is, the last few direct arguments must match the data types of the aggregated (WITHIN GROUP) arguments. The HYPOTHETICAL flag has no effect on run-time behavior, only on parse-time resolution of the data types and collations of the aggregate's arguments. The parameters of CREATE AGGREGATE can be written in any order, not just the order illustrated above. Notes In parameters that specify support function names, you can write a schema name if needed, for example SFUNC = public.sum. Do not write argument types there, however — the argument types of the support functions are determined from other parameters. Ordinarily, PostgreSQL functions are expected to be true functions that do not modify their input values. However, an aggregate transition function, when used in the context of an aggregate, is allowed to cheat and modify its transition-state argument in place. This can provide substantial performance benefits compared to making a fresh copy of the transition state each time. Likewise, while an aggregate final function is normally expected not to modify its input values, sometimes it is impractical to avoid modifying the transition-state argument. Such behavior must be declared using the FINALFUNC_MODIFY parameter. The READ_WRITE value indicates that the final function modifies the transition state in unspecified ways. This value prevents use of the aggregate as a window function, and it also prevents merging of transition states for aggregate calls that share the same input values and transition functions. The SHAREABLE value indicates that the transition function cannot be applied after the final function, but multiple final-function calls can be performed on the ending transition state value. This value prevents use of the aggregate as a window function, but it allows merging of transition states. (That is, the optimization of interest here is not applying the same final function repeatedly, but applying different final functions to the same ending transition state value. This is allowed as long as none of the final functions are marked READ_WRITE.) If an aggregate supports moving-aggregate mode, it will improve calculation efficiency when the aggregate is used as a window function for a window with moving frame start (that is, a frame start mode other than UNBOUNDED PRECEDING). Conceptually, the forward transition function adds input values to the aggregate's state when they enter the window frame from the bottom, and the inverse transition function removes them again when they leave the frame at the top. So, when values are removed, they are always removed in the same order they were added. Whenever the inverse transition function is invoked, it will thus receive the earliest added but not yet removed argument value(s). The inverse transition function can assume that at least one row will remain in the current state after it removes the oldest row. (When this would not be the case, the window function mechanism simply starts a fresh aggregation, rather than using the inverse transition function.) The forward transition function for moving-aggregate mode is not allowed to return NULL as the new state value. If the inverse transition function returns NULL, this is taken as an indication that the inverse function cannot reverse the state calculation for this particular input, and so the aggregate calculation will be redone from scratch for the current frame starting position. This convention allows moving-aggregate mode to be used in situations where there are some infrequent cases that are impractical to reverse out of the running state value. If no moving-aggregate implementation is supplied, the aggregate can still be used with moving frames, but PostgreSQL will recompute the whole aggregation whenever the start of the frame moves. Note that whether or not the aggregate supports moving-aggregate mode, PostgreSQL can handle a moving frame end without recalculation; this is done by continuing to add new values to the aggregate's state. This is why use of an aggregate as a window function requires that the final function be read-only: it must not damage the aggregate's state value, so that the aggregation can be continued even after an aggregate result value has been obtained for one set of frame boundaries. The syntax for ordered-set aggregates allows VARIADIC to be specified for both the last direct parameter and the last aggregated (WITHIN GROUP) parameter. However, the current implementation restricts use of VARIADIC in two ways. First, ordered-set aggregates can only use VARIADIC "any", not other variadic array types. Second, if the last direct parameter is VARIADIC "any", then there can be only one aggregated parameter and it must also be VARIADIC "any". (In the representation used in the system catalogs, these two parameters are merged into a single VARIADIC "any" item, since pg_proc cannot represent functions with more than one VARIADIC parameter.) If the aggregate is a hypothetical-set aggregate, the direct arguments that match the VARIADIC "any" parameter are the hypothetical ones; any preceding parameters represent additional direct arguments that are not constrained to match the aggregated arguments. Currently, ordered-set aggregates do not need to support moving-aggregate mode, since they cannot be used as window functions. Partial (including parallel) aggregation is currently not supported for ordered-set aggregates. Also, it will never be used for aggregate calls that include DISTINCT or ORDER BY clauses, since those semantics cannot be supported during partial aggregation. Examples See Section 37.12. Compatibility CREATE AGGREGATE is a PostgreSQL language extension. The SQL standard does not provide for user-defined aggregate functions. See Also
ALTER AGGREGATE, DROP AGGREGATE
Prev Up Next
CREATE ACCESS METHOD Home CREATE CAST
|
QMqttMessageStatusProperties Class The QMqttMessageStatusProperties class represents additional information provided by the server during message delivery. More...
Header:
#include <QMqttMessageStatusProperties>
qmake:
QT += mqtt
Since:
Qt 5.12
List of all members, including inherited members Public Functions
QString
reason() const
QMqtt8b7c:f320:99b9:690f:4595:cd17:293a:c069ReasonCode
reasonCode() const
QMqttUserProperties
userProperties() const
Detailed Description
Depending on the QoS level of a message being sent by QMqttClient8b7c:f320:99b9:690f:4595:cd17:293a:c069publish(), a server reports the state of delivery. Additionally to the QMqtt8b7c:f320:99b9:690f:4595:cd17:293a:c069MessageStatus, complementary information might be included by the server. These are exposed to users via QMqttMessageStatusProperties. Note: Message status properties are part of the MQTT 5.0 specification and cannot be used when connecting with a lower protocol level. See QMqttClient8b7c:f320:99b9:690f:4595:cd17:293a:c069ProtocolVersion for more information. Member Function Documentation
QString QMqttMessageStatusProperties8b7c:f320:99b9:690f:4595:cd17:293a:c069reason() const
Returns the reason string of a failed message delivery.
QMqtt8b7c:f320:99b9:690f:4595:cd17:293a:c069ReasonCode QMqttMessageStatusProperties8b7c:f320:99b9:690f:4595:cd17:293a:c069reasonCode() const
Returns the reason code of a failed message delivery.
QMqttUserProperties QMqttMessageStatusProperties8b7c:f320:99b9:690f:4595:cd17:293a:c069userProperties() const
Returns properties specified in conjunction with a message.
|
matplotlib.axes.Axes.update_datalim
Axes.update_datalim(self, xys, updatex=True, updatey=True)
Extend the dataLim BBox to include the given points. If no data is set currently, the BBox will ignore its limits and set the bound to be the bounds of the xydata (xys). Otherwise, it will compute the bounds of the union of its current data and the data in xys.
Parameters:
xys : 2D array-like
The points to include in the data limits BBox. This can be either a list of (x, y) tuples or a Nx2 array.
updatex, updatey : bool, optional, default True
Whether to update the x/y limits.
|
Process Internals The fields of a process (for a complete list, see the definition of struct Lisp_Process in process.h) include: name
A Lisp string, the name of the process. command
A list containing the command arguments that were used to start this process. For a network or serial process, it is nil if the process is running or t if the process is stopped. filter
A Lisp function used to accept output from the process. sentinel
A Lisp function called whenever the state of the process changes. buffer
The associated buffer of the process. pid
An integer, the operating system’s process ID. Pseudo-processes such as network or serial connections use a value of 0. childp
A flag, t if this is really a child process. For a network or serial connection, it is a plist based on the arguments to make-network-process or make-serial-process. mark
A marker indicating the position of the end of the last output from this process inserted into the buffer. This is often but not always the end of the buffer. kill_without_query
If this is non-zero, killing Emacs while this process is still running does not ask for confirmation about killing the process. raw_status
The raw process status, as returned by the wait system call. status
The process status, as process-status should return it. This is a Lisp symbol, a cons cell, or a list. tick update_tick
If these two fields are not equal, a change in the status of the process needs to be reported, either by running the sentinel or by inserting a message in the process buffer. pty_flag
Non-zero if communication with the subprocess uses a pty; zero if it uses a pipe. infd
The file descriptor for input from the process. outfd
The file descriptor for output to the process. tty_name
The name of the terminal that the subprocess is using, or nil if it is using pipes. decode_coding_system
Coding-system for decoding the input from this process. decoding_buf
A working buffer for decoding. decoding_carryover
Size of carryover in decoding. encode_coding_system
Coding-system for encoding the output to this process. encoding_buf
A working buffer for encoding. inherit_coding_system_flag
Flag to set coding-system of the process buffer from the coding system used to decode process output. type
Symbol indicating the type of process: real, network, serial.
Copyright
|
XRProjectionLayer.textureArrayLength
The read-only textureArrayLength property of the XRProjectionLayer interface indicates layer's layer count for array textures when using texture-array as the textureType. The projection layer's layer count for array textures is determined by the user agent or the device. It is reported in the XRSubImage, which can only be accessed inside the frame loop. If you want to manage your own depth buffers and don't want to wait for first frame after layer creation to determine the required dimensions for those buffers, the textureArrayLength property allows access to layer count for array textures outside the frame loop. Allocation of these buffers can happen directly after layer creation.
Value
A number indicating the number of layers of the color textures when using texture-array as the textureType. Otherwise it will be 1.
Specifications
No specification foundNo specification data found for api.XRProjectionLayer.textureArrayLength.Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.
Browser compatibility
No compatibility data found for api.XRProjectionLayer.textureArrayLength.Check for problems with this page or contribute missing data to mdn/browser-compat-data.
See also
XRSubImage
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 19, 2021, by MDN contributors
|
ToggleButtonStyle QML Type Provides custom styling for ToggleButton. More...
Import Statement:
import QtQuick.Controls.Styles 1.4
Since:
Qt 5.5
List of all members, including inherited members Properties
checkedDropShadowColor : color
checkedGradient : Gradient
control : ToggleButton
inactiveGradient : Gradient
uncheckedDropShadowColor : color
uncheckedGradient : Gradient Detailed Description You can create a custom toggle button by replacing the same delegates that ButtonStyle provides. Property Documentation checkedDropShadowColor : color
The color that is used for the drop shadow below the checked state indicator. See also uncheckedDropShadowColor. checkedGradient : Gradient
The gradient that is displayed on the checked state indicator. See also uncheckedGradient and inactiveGradient. [read-only] control : ToggleButton
The ToggleButton that this style is attached to. inactiveGradient : Gradient
The gradient that is displayed on the inactive state indicator. The inactive state indicator will be the checked gradient when the button is unchecked, and the unchecked gradient when the button is checked. See also checkedGradient and uncheckedGradient. uncheckedDropShadowColor : color
The color that is used for the drop shadow below the checked state indicator. See also checkedDropShadowColor. uncheckedGradient : Gradient
The gradient that is displayed on the unchecked state indicator. See also checkedGradient and inactiveGradient.
|
tf.distribute.HierarchicalCopyAllReduce View source on GitHub Reduction using hierarchical copy all-reduce. Inherits From: AllReduceCrossDeviceOps View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.distribute.HierarchicalCopyAllReduce, `tf.compat.v2.distribute.HierarchicalCopyAllReduce`
tf.distribute.HierarchicalCopyAllReduce(
num_packs=1
)
It reduces to one GPU along edges in some hierarchy and broadcasts back to each GPU along the same path. Before performing all-reduce, tensors will be repacked or aggregated for more efficient cross-device transportation. This is a reduction created for Nvidia DGX-1 which assumes GPUs connects like that on DGX-1 machine. If you have different GPU inter-connections, it is likely that it would be slower than tf.distribute.ReductionToOneDevice.
Args
num_packs values will be packed in this many splits. num_packs should be greater than or equals 0. When it is zero, no packing will be done.
Raises ValueError if num_packs is negative.
Methods batch_reduce View source
batch_reduce(
reduce_op, value_destination_pairs
)
Reduce PerReplica objects in a batch. Reduce each first element in value_destination_pairs to each second element which indicates the destinations.
Args
reduce_op Indicates how per_replica_value will be reduced. Accepted values are tf.distribute.ReduceOp.SUM, tf.distribute.ReduceOp.MEAN.
value_destination_pairs a list or a tuple of tuples of PerReplica objects (or tensors with device set if there is one device) and destinations.
Returns a list of Mirrored objects.
Raises
ValueError if value_destination_pairs is not a list or a tuple of tuples of PerReplica objects and destinations broadcast View source
broadcast(
tensor, destinations
)
Broadcast the tensor to destinations.
Args
tensor the tensor to broadcast.
destinations the broadcast destinations.
Returns a Mirrored object.
reduce View source
reduce(
reduce_op, per_replica_value, destinations
)
Reduce per_replica_value to destinations. It runs the reduction operation defined by reduce_op and put the result on destinations.
Args
reduce_op Indicates how per_replica_value will be reduced. Accepted values are tf.distribute.ReduceOp.SUM, tf.distribute.ReduceOp.MEAN.
per_replica_value a PerReplica object or a tensor with device set.
destinations the reduction destinations.
Returns a Mirrored object.
Raises
ValueError if per_replica_value can't be converted to a PerReplica object.
|
public static function Drupal8b7c:f320:99b9:690f:4595:cd17:293a:c069transliteration public static Drupal8b7c:f320:99b9:690f:4595:cd17:293a:c069transliteration() Returns the transliteration service. Return value \Drupal\Core\Transliteration\PhpTransliteration The transliteration manager. File
core/lib/Drupal.php, line 628 Contains \Drupal. Class
Drupal Static Service Container wrapper. Code public static function transliteration() {
return stati8b7c:f320:99b9:690f:4595:cd17:293a:c069getContainer()->get('transliteration');
}
|
dart:html requestQuota method void requestQuota(
int newQuotaInBytes, [StorageQuotaCallback? quotaCallback,
StorageErrorCallback? errorCallback] ) Implementation void requestQuota(int newQuotaInBytes,
[StorageQuotaCallback? quotaCallback,
StorageErrorCallback? errorCallback]) native;
|
protected property DrupalCacheArray8b7c:f320:99b9:690f:4595:cd17:293a:c069$keysToPersist An array of keys to add to the cache at the end of the request. File
includes/bootstrap.inc, line 330 Functions that need to be loaded on every Drupal request. Class
DrupalCacheArray Provides a caching wrapper to be used in place of large array structures. Code protected $keysToPersist = array();
|
st8b7c:f320:99b9:690f:4595:cd17:293a:c069decay Defined in header <type_traits> template< class T >
struct decay;
(since C++11) Applies lvalue-to-rvalue, array-to-pointer, and function-to-pointer implicit conversions to the type T, removes cv-qualifiers, and defines the resulting type as the member typedef type. Formally:
If T names the type "array of U" or "reference to array of U", the member typedef type is U*.
Otherwise, if T is a function type F or a reference thereto, the member typedef type is st8b7c:f320:99b9:690f:4595:cd17:293a:c069add_pointer<F>8b7c:f320:99b9:690f:4595:cd17:293a:c069type.
Otherwise, the member typedef type is st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_cv<st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_reference<T>8b7c:f320:99b9:690f:4595:cd17:293a:c069type>8b7c:f320:99b9:690f:4595:cd17:293a:c069type.
These conversions model the type conversion applied to all function arguments when passed by value.
The behavior of a program that adds specializations for decay is undefined.
Member types Name Definition
type the result of applying the decay type conversions to T
Helper types template< class T >
using decay_t = typename decay<T>8b7c:f320:99b9:690f:4595:cd17:293a:c069type;
(since C++14) Possible implementation template< class T >
struct decay {
private:
typedef typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_reference<T>8b7c:f320:99b9:690f:4595:cd17:293a:c069type U;
public:
typedef typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069conditional<
st8b7c:f320:99b9:690f:4595:cd17:293a:c069is_array<U>8b7c:f320:99b9:690f:4595:cd17:293a:c069value,
typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_extent<U>8b7c:f320:99b9:690f:4595:cd17:293a:c069type*,
typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069conditional<
st8b7c:f320:99b9:690f:4595:cd17:293a:c069is_function<U>8b7c:f320:99b9:690f:4595:cd17:293a:c069value,
typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069add_pointer<U>8b7c:f320:99b9:690f:4595:cd17:293a:c069type,
typename st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_cv<U>8b7c:f320:99b9:690f:4595:cd17:293a:c069type
>8b7c:f320:99b9:690f:4595:cd17:293a:c069type
>8b7c:f320:99b9:690f:4595:cd17:293a:c069type type;
};
Example #include <type_traits>
template <typename T, typename U>
constexpr bool is_decay_equ = st8b7c:f320:99b9:690f:4595:cd17:293a:c069is_same_v<st8b7c:f320:99b9:690f:4595:cd17:293a:c069decay_t<T>, U>;
int main()
{
static_assert(
is_decay_equ<int, int> &&
! is_decay_equ<int, float> &&
is_decay_equ<int&, int> &&
is_decay_equ<int&&, int> &&
is_decay_equ<const int&, int> &&
is_decay_equ<int[2], int*> &&
! is_decay_equ<int[4][2], int*> &&
! is_decay_equ<int[4][2], int**> &&
is_decay_equ<int[4][2], int(*)[2]> &&
is_decay_equ<int(int), int(*)(int)>
);
} See also remove_cvref
(C++20) combines st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_cv and st8b7c:f320:99b9:690f:4595:cd17:293a:c069remove_reference (class template)
implicit conversion array-to-pointer, function-to-pointer, lvalue-to-rvalue conversions
|
statistics.module Logs and displays access statistics for a site. File modules/statistics/statistics.module Functions
Name Description statistics_block_configure Implements hook_block_configure(). statistics_block_info Implements hook_block_info(). statistics_block_save Implements hook_block_save(). statistics_block_view Implements hook_block_view(). statistics_cron Implements hook_cron(). statistics_exit Implements hook_exit(). statistics_get Retrieves a node's "view statistics". statistics_help Implements hook_help(). statistics_menu Implements hook_menu(). statistics_node_delete Implements hook_node_delete(). statistics_node_view Implements hook_node_view(). statistics_permission Implements hook_permission(). statistics_ranking Implements hook_ranking(). statistics_title_list Returns the most viewed content of all time, today, or the last-viewed node. statistics_update_index Implements hook_update_index(). statistics_user_cancel Implements hook_user_cancel(). statistics_user_delete Implements hook_user_delete(). _statistics_format_item Formats an item for display, including both the item title and the link. _statistics_link Generates a link to a path, truncating the displayed text to a given width.
|
pandas.Series.unique
Series.unique(self) [source]
Return unique values of Series object. Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.
Returns:
ndarray or ExtensionArray
The unique values returned as a NumPy array. See Notes. See also
unique
Top-level unique method for any 1-d array-like object.
Index.unique
Return Index with unique values from an Index object. Notes Returns the unique values as a NumPy array. In case of an extension-array backed Series, a new ExtensionArray of that type with just the unique values is returned. This includes Categorical Period Datetime with Timezone Interval Sparse IntegerNA See Examples section. Examples >>> pd.Series([2, 1, 3, 3], name='A').unique()
array([2, 1, 3])
>>> pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique()
array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')
>>> pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern')
... for _ in range(3)]).unique()
<DatetimeArray>
['2016-01-01 00:00:00-05:00']
Length: 1, dtype: datetime64[ns, US/Eastern]
An unordered Categorical will return categories in the order of appearance. >>> pd.Series(pd.Categorical(list('baabc'))).unique()
[b, a, c]
Categories (3, object): [b, a, c]
An ordered Categorical preserves the category ordering. >>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'),
... ordered=True)).unique()
[b, a, c]
Categories (3, object): [a < b < c]
|
Recovering Data From A Corrupt SQLite Database
1. Recovering (Some) Data From A Corrupt SQLite Database 1.1. Limitations 2. Recovery Using The ".recover" Command In The CLI 3. Building The Recovery API Into An Application 3.1. Source Code Files 3.2. How To Implement Recovery 3.3. Example Implementations
1. Recovering (Some) Data From A Corrupt SQLite Database SQLite databases are remarkably rebust. Application faults and power failures typically leave the content of the database intact. However, it is possible to corrupt an SQLite database. For example, hardware malfunctions can damage the database file, or a rogue process can open the database and overwrite parts of it.
Given a corrupt database file, it is sometimes desirable to try to salvage as much data from the file as possible. The recovery API is designed to facilitate this.
1.1. Limitations It is sometimes possible to perfectly restore a database that has gone corrupt, but that is the exception. Usually the recovered database will be defective in a number of ways:
Some content might be permanently deleted and unrecoverable. This can happen, for example, if a rogue process overwrites part of the database file.
Previously deleted content might reappear. Normally when SQLite does a DELETE operation, it does not actually overwrite the old content but instead remembers that space is available for reuse during the next INSERT. If such deleted content is still in the file when a recovery is attempted, it might be extracted and "resurrected".
Recovered content might be altered. For example, the value stored in a particular row might change from 48 to 49. Or it might change from an integer into a string or blob. A value that was NULL might become an integer. A string value might become a BLOB. And so forth.
Constraints may not be valid after recovery. CHECK constraints, FOREIGN KEY constraints, UNIQUE constraints, type constraints on STRICT tables - any of these might be violated in the recovered database.
Content might be moved from one table into another.
The recovery API does as good of a job as it can at restoring a database, but the results will always be suspect. Sometimes (for example if the corruption is restricted to indexes) the recovery will perfectly restore the database content. However in other cases, the recovery will be imperfect. The impact of this imperfection depends on the application. A database that holds a list of bookmarks is still a list of bookmarks after recovery. A few bookmarks might be missing or added or altered after recovery, but the list is "fuzzy" and imperfect to begin with so adding a bit more uncertainty will not be fatal to the application. But if an accounting database goes corrupt and is subsequently recovered, the books might be out of balance.
It is best to think of the recovery API as a salvage undertaking. Recovery will extract as much usable data as it can from the wreck of the old database, but some parts may be damaged beyond repair and some rework and testing should be performed prior to returning the recovered database to service.
2. Recovery Using The ".recover" Command In The CLI The easiest way to manually recover a corrupt database is using the Command Line Interface or "CLI" for SQLite. The CLI is a program named "sqlite3". Use it to recover a corrupt database file using a command similar to the following:
sqlite3 corrupt.db .recover >data.sql
This will generate SQL text in the file named "data.sql" that can be used to reconstruct the original database:
sqlite3 recovered.db <data.sql
The ".recover" option is actually a command that is issued to the CLI. That command can accept arguments. For example, by running:
sqlite3 corruptdb ".recover --ignore-freelist" >data.sql
Notice that the ".recover" command and its arguments must be contained in quotes. The following options are supported:
--ignore-freelist Ignore pages of the database that appear to be part of the freelist. Normally the freelist is scanned, and if it contains pages that look like they have content, that content is output. But if the page really is on the freelist, that can mean that previously deleted information is reintroduced into the database. --lost-and-found TABLE
If content is found during recovery that cannot be associated with a particular table, it is put into the "lost_and_found" table. Use this option to change the name of the "lost_and_found" table to "TABLE". --no-rowids If this option is provided, then rowid values that are not also INTEGER PRIMARY KEY values are not extracted from the corrupt database.
3. Building The Recovery API Into An Application
3.1. Source Code Files If you want to build the recovery API into your application, you will need to add some source files to your build, above and beyond the usual "sqlite3.c" and "sqlite3.h" source files. You will need:
sqlite3recover.c
This is the main source file that implements the recovery API. sqlite3recover.h
This is the header file that goes with sqlite3recover.h. dbdata.c
This file implements two virtual tables name "sqlite_dbdata" and "sqlite_dbptr" that required by sqlite3recover.c. The two C source file above need to be linked into your application in the same way as "sqlite3.c" is linked in. And the header file needs to be accessible to the compiler when the C files are being compiled.
3.2. How To Implement Recovery These are the basic steps needed to recover content from a corrupt Database:
Creates an sqlite3_recover handle by calling either sqlite3_recover_init() or sqlite3_recover_init_sql(). Use sqlite3_recover_init() to store the recovered content in a separate database and use sqlite3_recover_init_sql() to generate SQL text that will reconstruct the database.
Make zero or more calls to sqlite3_recover_config() to set options on the new sqlite3_recovery handle.
Invoke sqlite3_recover_step() repeatedly until it returns something other than SQLITE_OK. If it returns SQLITE_DONE, then the recovery operation completed without error. If it returns some other non-SQLITE_OK value, then an error has occurred. The sqlite3_recover_run() interface is also available as a convenience wrapper that simply invokes sqlite3_recover_step() repeatedly until it returns something other than SQLITE_DONE.
Retrieves any error code and English language error message using the sqlite3_recover_errcode() and sqlite3_recover_errmsg() interfaces, respectively.
Invoke sqlite3_recover_finish() to destroy the sqlite3_recover object.
Details of the interface are described in comments in the sqlite3_recover.h header file.
3.3. Example Implementations Examples of how the recovery extension is used by SQLite itself can be seen at the following links:
https://sqlite.org/src/info/30475c820dc5ab8a8?ln=999,1026
An example of the recovery extension found in the "fuzzcheck" testing utility in the SQLite tree.
https://sqlite.org/src/info/84bb08d8762920285f08f1c0?ln=7299,7361
The code that implements the ".recover" command in the CLI.
This page last modified on 2022-11-04 15:23:18 UTC
SQLite is in the Public Domain.
https://sqlite.org/recovery.html
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.