text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>chef-server-ctl (executable) — chef-client Man Pages</title>

    <link rel="stylesheet" href="_static/guide.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

chef-server-ctl (executable)¶

The Chef server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef server, run chef-pedant, and then tail Chef server log files.

backup-recover¶

The <tt class="docutils literal">backup-recover</tt> subcommand is used to force the Chef server to attempt to become the backup server. This is the opposite of the <tt class="docutils literal">master-recover</tt> subcommand.

Warning

If this command is run on both back-end servers, it will put the back-end cluster into a state where no server holds the DRBD resource.

This subcommand has the following syntax:

$ chef-server-ctl backup-recover

cleanse¶

The <tt class="docutils literal">cleanse</tt> subcommand is used to re-set the Chef server to the state it was in before the first time the <tt class="docutils literal">reconfigure</tt> subcommand is run to destroy all data, configuration files, and logs.

This subcommand has the following syntax:

$ chef-server-ctl cleanse

gather-logs¶

The <tt class="docutils literal">gather-logs</tt> subcommand is used to gather the Chef server log files into a tarball that contains all of the important log files and system information.

This subcommand has the following syntax:

$ chef-server-ctl gather-logs

ha-status¶

The <tt class="docutils literal">ha-status</tt> subcommand is used to check the status for services running in a High Availability topology. This command will verify the following:

The Keepalived daemon is enabled in the config

The DRBD process is enabled in the config

The underlying block device or logical volume for DRBD has been created and configured

The DRBD device exists

The current state of the server is <tt class="docutils literal">master</tt> or <tt class="docutils literal">backup</tt>; any migration processes have completed

The failover virtual IP address is correctly attached to only the <tt class="docutils literal">master</tt> node

The DRBD state is correct based on the state of the server being <tt class="docutils literal">master</tt> or <tt class="docutils literal">backup</tt>

The DRBD mount point is correctly mounted to only the <tt class="docutils literal">master</tt> node

The DRBD replication IP addresses are pingable

The <tt class="docutils literal">runit</tt> status of the services are correct (up or down) based on the <tt class="docutils literal">master</tt> or <tt class="docutils literal">backup</tt> state of the server

This subcommand has the following syntax:

$ chef-server-ctl ha-status

If this command runs successfully, it will return the following:

$ [OK] all checks passed.

Otherwise it will print out a list of errors, similar to the following:

...
[OK] nginx is running correctly, and I am master.
[ERROR] redis_lb is not running.
[OK] opscode-erchef is running correctly, and I am master.
...
[ERROR] ERRORS WERE DETECTED.

For example:

[OK] keepalived HA services enabled
[OK] DRBD disk replication enabled
[OK] DRBD partition /dev/opscode/drbd found
[OK] DRBD device /dev/drbd0 found
[OK] cluster status = master
[OK] found VIP IP address and I am master
[OK] found VRRP communications interface eth1
[OK] my DRBD status is Connected/Primary/UpToDate and I am master
[OK] my DRBD partition is mounted and I am master
[OK] DRBD primary IP address pings
[OK] DRBD secondary IP address pings
...
[OK] all checks passed.

help¶

The <tt class="docutils literal">help</tt> subcommand is used to print a list of all available chef-server-ctl commands.

This subcommand has the following syntax:

$ chef-server-ctl help

install¶

The <tt class="docutils literal">install</tt> subcommand is used to install premium features of the Chef server: Chef management console, Chef analytics, chef-client run reporting, high availability configurations, Chef push jobs, and Chef server replication.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl install name_of_premium_feature (options)

where <tt class="docutils literal">name_of_premium_feature</tt> represents the command line value associated with the premium feature:

Options

This subcommand has the following options:

<tt class="docutils literal">--path PATH</tt>

Use to specify the location of a package. This option is not required when packages are downloaded from https://packagecloud.io/.

Use Downloads¶

The <tt class="docutils literal">install</tt> subcommand downloads packages from https://packagecloud.io/ by default. For systems that are not behind a firewall (and have connectivity to https://packagecloud.io/), these packages can be installed as described below.

<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>

Feature
Command

Chef Manage

Use Chef management console to manage data bags, attributes, run-lists, roles, environments, and cookbooks from a web user interface.

(Front end machines only.) Run:

$ chef-server-ctl install opscode-manage

then:

$ opscode-manage-ctl reconfigure

and then:

$ chef-server-ctl reconfigure

Chef Push Jobs

Use Chef push jobs to run jobs—an action or a command to be executed—against nodes independently of a chef-client run.

Run:

$ chef-server-ctl install opscode-push-jobs-server

then:

$ opscode-push-jobs-server-ctl reconfigure

and then:

$ chef-server-ctl reconfigure

Chef Replication

Use Chef replication to asynchronously distribute cookbook, environment, role, and data bag data from a single, primary Chef server to one (or more) replicas of that Chef server.

Run:

$ chef-server-ctl install chef-sync

and then:

$ chef-sync-ctl reconfigure

and then:

$ chef-server-ctl reconfigure

Reporting

Use Chef reporting to keep track of what happens during every chef-client runs across all of the infrastructure being managed by Chef. Run Chef reporting with Chef management console to view reports from a web user interface.

(Front end machines only.) Run:

$ chef-server-ctl install opscode-reporting

then:

$ opscode-reporting-ctl reconfigure

and then:

$ chef-server-ctl reconfigure

Use Local Packages¶

The <tt class="docutils literal">install</tt> subcommand downloads packages from https://packagecloud.io/ by default. For systems that are behind a firewall (and do not have connectivity to https://packagecloud.io/), these packages can be installed manually. First download the package that is appropriate for the platform and save it to a local path. Then run the <tt class="docutils literal">install</tt> command using the <tt class="docutils literal">--path</tt> option to specify the location for the package:

$ chef-server-ctl install NAME_OF_PACKAGE --path /path/to/package

For example:

$ chef-server-ctl install opscode-manage-1.6.2-1.el6.x86_64 --path /home/vagrant

master-recover¶

The <tt class="docutils literal">master-recover</tt> subcommand is used to force the Chef server to attempt to become the master server. This command is typically run in tandem with the <tt class="docutils literal">backup-recover</tt> subcommand on the back-end peer, unless the back-end peer is no longer available.

This subcommand has the following syntax:

$ chef-server-ctl master-recover

org-create¶

The <tt class="docutils literal">org-create</tt> subcommand is used to create an organization. (The validation key for the organization is returned to <tt class="docutils literal">STDOUT</tt> when creating an organization using this command.)

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-create ORG_NAME ORG_FULL_NAME (options)

Options

This subcommand has the following options:

<tt class="docutils literal">-a USER_NAME</tt>, <tt class="docutils literal">--association_user USER_NAME</tt>

Use to associate a user with an organization and add them to the <tt class="docutils literal">admins</tt> and <tt class="docutils literal">billing_admins</tt> security groups.

<tt class="docutils literal">-f FILE_NAME</tt>, <tt class="docutils literal">--filename FILE_NAME</tt>

Use to write the private key to a file instead of <tt class="docutils literal">STDOUT</tt>.

Examples

$ chef-server-ctl org-create prod Production

$ chef-server-ctl org-create staging Staging -a chef-admin

$ chef-server-ctl org-create dev Development -f /tmp/id-dev.key

org-delete¶

The <tt class="docutils literal">org-delete</tt> subcommand is used to delete an organization.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-delete ORG_NAME

Examples

$ chef-server-ctl org-delete infra-testing-20140909

$ chef-server-ctl org-delete pedant-testing-org

org-list¶

The <tt class="docutils literal">org-list</tt> subcommand is used to list all of the organizations currently present on the Chef server.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-list (options)

Options

This subcommand has the following options:

<tt class="docutils literal">-a</tt>, <tt class="docutils literal">--all-orgs</tt>

Use to show all organizations.

<tt class="docutils literal">-w</tt>, <tt class="docutils literal">--with-uri</tt>

Use to show the corresponding URIs.

org-show¶

The <tt class="docutils literal">org-show</tt> subcommand is used to show the details for an organization.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-show ORG_NAME

org-user-add¶

The <tt class="docutils literal">org-user-add</tt> subcommand is used to add a user to an organization.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-user-add ORG_NAME USER_NAME (options)

Options

This subcommand has the following options:

<tt class="docutils literal">--admin</tt>

Use to add the user to the <tt class="docutils literal">admins</tt> group.

Examples

$ chef-server-ctl org-user-add prod john_smith

$ chef-server-ctl org-user-add preprod testmaster

$ chef-server-ctl org-user-add dev grantmc --admin

org-user-remove¶

The <tt class="docutils literal">org-user-remove</tt> subcommand is used to remove a user from an organization.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl org-user-remove ORG_NAME USER_NAME

Examples

$ chef-server-ctl org-user-remove prod john_smith

$ chef-server-ctl org-user-remove prod testmaster

password¶

Warning

This subcommand is currently disabled.

reconfigure¶

The <tt class="docutils literal">reconfigure</tt> subcommand is used when changes are made to the private-chef.rb file to reconfigure the server. When changes are made to the private-chef.rb file, they will not be applied to the Chef server configuration until after this command is run. This subcommand will also restart any services for which the <tt class="docutils literal">service_name['enabled']</tt> setting is set to <tt class="docutils literal">true</tt>.

This subcommand has the following syntax:

$ chef-server-ctl reconfigure

show-config¶

The <tt class="docutils literal">show-config</tt> subcommand is used to view the configuration that will be generated by the <tt class="docutils literal">reconfigure</tt> subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation.

This subcommand has the following syntax:

$ chef-server-ctl show-config

uninstall¶

The <tt class="docutils literal">uninstall</tt> subcommand is used to remove the Chef server application, but without removing any of the data. This subcommand will shut down all services (including the <tt class="docutils literal">runit</tt> process supervisor).

This subcommand has the following syntax:

$ chef-server-ctl uninstall

Note

To revert the <tt class="docutils literal">uninstall</tt> subcommand, run the <tt class="docutils literal">reconfigure</tt> subcommand (because the <tt class="docutils literal">start</tt> subcommand is disabled by the <tt class="docutils literal">uninstall</tt> command).

upgrade¶

The <tt class="docutils literal">upgrade</tt> subcommand is used to upgrade the Chef server.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl upgrade (options)

Options

Note

Options for the <tt class="docutils literal">upgrade</tt> subcommand may only be used when upgrading from Open Source Chef 11 to Chef server 12.

This subcommand has the following options:

<tt class="docutils literal">-d DIRECTORY</tt>, <tt class="docutils literal">--chef11-data-dir DIRECTORY</tt>

The directory in which Open Source Chef 11 data is located. Default value: a temporary directory.

<tt class="docutils literal">-e DIRECTORY</tt>, <tt class="docutils literal">--chef12-data-dir DIRECTORY</tt>

The directory in which Chef server 12 data is located. Default value: a temporary directory.

<tt class="docutils literal">-f FULL_NAME</tt>, <tt class="docutils literal">--full-org-name FULL_NAME</tt>

The full name of the Chef server organization. A full organization name must begin with a non-white space character and must be between 1 and 1023 characters. For example: <tt class="docutils literal">Chef Software, Inc.</tt>. If this option is not specified, the <tt class="docutils literal">upgrade</tt> command will prompt for it.

<tt class="docutils literal">-h</tt>, <tt class="docutils literal">--help</tt>

Use to show help for the <tt class="docutils literal">chef-server-ctl upgrade</tt> subcommand.

<tt class="docutils literal">-k KEY</tt>, <tt class="docutils literal">--key KEY</tt>

All users are assigned a public key. Use to write the public key to a file. Default value: <tt class="docutils literal">/etc/chef-server/admin.pem</tt>.

<tt class="docutils literal">-o ORG_NAME</tt>, <tt class="docutils literal">--org-name ORG_NAME</tt>

The name of the Chef server organization. An organization name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: <tt class="docutils literal">chef</tt>. If this option is not specified, the <tt class="docutils literal">upgrade</tt> command will prompt for it.

<tt class="docutils literal">-s URL</tt>, <tt class="docutils literal">--chef11-server-url URL</tt>

The URL for the Open Source Chef or Enterprise Chef server, version 11. Default value: <tt class="docutils literal">https://localhost</tt>.

<tt class="docutils literal">-t NUMBER</tt>, <tt class="docutils literal">--upload-threads NUMBER</tt>

The number of threads to use when migrating cookbooks. Default value: <tt class="docutils literal">10</tt>.

<tt class="docutils literal">-u USER</tt>, <tt class="docutils literal">--user</tt>

Use to create a client as an admin client. This is required for any user to access Open Source Chef as an administrator.

<tt class="docutils literal">-x URL</tt>, <tt class="docutils literal">--chef12-server-url URL</tt>

The URL for the Chef server, version 12. Default value: <tt class="docutils literal">https://localhost</tt>.

<tt class="docutils literal">-y</tt>, <tt class="docutils literal">--yes</tt>

Use to skip confirmation prompts during the upgrade process.

user-create¶

The <tt class="docutils literal">user-create</tt> subcommand is used to create a user.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL PASSWORD (options)

Options

This subcommand has the following options:

<tt class="docutils literal">-f FILE_NAME</tt>, <tt class="docutils literal">--filename FILE_NAME</tt>

Use to write the private key to a file instead of <tt class="docutils literal">STDOUT</tt>.

Examples

$ chef-server-ctl user-create john_smith John Smith john_smith@example.com insecure-passord

$ chef-server-ctl user-create jane_doe Jane Doe jane_doe@example.com PaSSword -f /tmp/jane_doe.key

$ chef-server-ctl user-create waldendude Henry David Thoreau waldendude@example.com excursions

user-delete¶

The <tt class="docutils literal">user-delete</tt> subcommand is used to delete a user.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl user-delete USER_NAME

Examples

$ chef-server-ctl user-delete john_smith

$ chef-server-ctl user-delete jane_doe

user-edit¶

The <tt class="docutils literal">user-edit</tt> subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl user-edit USER_NAME

Examples

$ chef-server-ctl user-edit john_smith

$ chef-server-ctl user-edit jane_doe

user-list¶

The <tt class="docutils literal">user-list</tt> subcommand is used to view a list of users.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl user-list (options)

Options

This subcommand has the following options:

<tt class="docutils literal">-w</tt>, <tt class="docutils literal">--with-uri</tt>

Use to show the corresponding URIs.

user-show¶

The <tt class="docutils literal">user-show</tt> subcommand is used to show the details for a user.

Syntax

This subcommand has the following syntax:

$ chef-server-ctl user-show USER_NAME (options)

Options

This subcommand has the following options:

<tt class="docutils literal">-l</tt>, <tt class="docutils literal">--with-orgs</tt>

Use to show the corresponding organizations.

Service Subcommands¶

The Chef server has a built in process supervisor, which ensures that all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service.

hup¶

The <tt class="docutils literal">hup</tt> subcommand is used to send a <tt class="docutils literal">SIGHUP</tt> to all services. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl hup name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

int¶

The <tt class="docutils literal">int</tt> subcommand is used to send a <tt class="docutils literal">SIGINT</tt> to all services. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl int name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

kill¶

The <tt class="docutils literal">kill</tt> subcommand is used to send a <tt class="docutils literal">SIGKILL</tt> to all services. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl kill name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

once¶

The supervisor for the Chef server is configured to restart any service that fails, unless that service has been asked to change its state. The <tt class="docutils literal">once</tt> subcommand is used to tell the supervisor to not attempt to restart any service that fails.

This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the <tt class="docutils literal">once</tt> subcommand followed by the <tt class="docutils literal">status</tt> subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl once name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

restart¶

The <tt class="docutils literal">restart</tt> subcommand is used to restart all services enabled on the Chef server or to restart an individual service by specifying the name of that service in the command.

Warning

When running the Chef server in a high availability configuration, restarting all services may trigger failover.

This subcommand has the following syntax:

$ chef-server-ctl restart name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand. When a service is successfully restarted the output should be similar to:

$ ok: run: service_name: (pid 12345) 1s

service-list¶

The <tt class="docutils literal">service-list</tt> subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*).

This subcommand has the following syntax:

$ chef-server-ctl service-list

start¶

The <tt class="docutils literal">start</tt> subcommand is used to start all services that are enabled in the Chef server. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl start name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand. When a service is successfully started the output should be similar to:

$ ok: run: service_name: (pid 12345) 1s

The supervisor for the Chef server is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the <tt class="docutils literal">kill</tt> subcommand to stop the process, investigate the cause (if required), and then use the <tt class="docutils literal">start</tt> subcommand to re-enable it.

status¶

The <tt class="docutils literal">status</tt> subcommand is used to show the status of all services available to the Chef server. The results will vary based on the configuration of a given server. This subcommand has the following syntax:

$ chef-server-ctl status

and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command:

$ chef-server-ctl status name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

When service status is requested, the output should be similar to:

$ run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s

where

<tt class="docutils literal">run:</tt> is the state of the service (<tt class="docutils literal">run:</tt> or <tt class="docutils literal">down:</tt>)

<tt class="docutils literal">service_name:</tt> is the name of the service for which status is returned

<tt class="docutils literal">(pid 12345)</tt> is the process identifier

<tt class="docutils literal">12345s</tt> is the uptime of the service, in seconds

For example:

$ down: opscode-erchef: (pid 35546) 10s

By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as <tt class="docutils literal">run:</tt> even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the opscode-erchef should be investigated further:

run: oc-id
run: opscode-chef: (pid 4327) 13671s; run: log: (pid 4326) 13671s
run: opscode-erchef: (pid 5383) 5s; run: log: (pid 4382) 13669s
run: opscode-expander: (pid 4078) 13694s; run: log: (pid 4077) 13694s
run: opscode-expander-reindexer: (pid 4130) 13692s; run: log: (pid 4114) 13692s

High Availability¶

On back-end servers in a High Availability topology, Keepalived is used by the clustering service to determine whether a service should be running. If the <tt class="docutils literal">status</tt> subcommand is run against any of these nodes, a few things change:

On the back-end node that is currently the backup server, it is normal to see only one running process: Keepalived

On the back-end node that is currently the master server, it is normal to see all services running. It is also normal to see some services in a down state if the server, on reboot, did not attempt to start the services because Keepalived determines which services are restarted based on the state of the cluster

A sample status line for a service that is running on the master server in a High Availability topology:

run: opscode-solr: (pid 25341) 239s, normally down; run: log: (pid 5700) 145308s

Log Files¶

A typical status line for a service that is running any of the Chef server front-end services is similar to the following:

run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s

where:

<tt class="docutils literal">run</tt> describes the state in which the supervisor attempts to keep processes. This state is either <tt class="docutils literal">run</tt> or <tt class="docutils literal">down</tt>. If a service is in a <tt class="docutils literal">down</tt> state, it should be stopped

<tt class="docutils literal">name_of_service</tt> is the service name, for example: <tt class="docutils literal">opscode-solr4</tt>

<tt class="docutils literal">(pid 1486) 7819s;</tt> is the process identifier followed by the amount of time (in seconds) the service has been running

<tt class="docutils literal">run: log: (pid 1485) 7819s</tt> is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process

If the service is down, the status line will appear similar to the following:

down: opscode-solr4: 3s, normally up; run: log: (pid 1485) 8526s

where

<tt class="docutils literal">down</tt> indicates that the service is in a down state

<tt class="docutils literal">3s, normally up;</tt> indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot

stop¶

The <tt class="docutils literal">stop</tt> subcommand is used to stop all services enabled on the Chef server. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl stop name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand. When a service is successfully stopped the output should be similar to:

$ ok: diwb: service_name: 0s, normally up

For example:

$ chef-server-ctl stop

will return something similar to:

ok: down: nginx: 393s, normally up
ok: down: opscode-chef: 391s, normally up
ok: down: opscode-erchef: 391s, normally up
ok: down: opscode-expander: 390s, normally up
ok: down: opscode-expander-reindexer: 389s, normally up
ok: down: opscode-solr4: 389s, normally up
ok: down: postgresql: 388s, normally up
ok: down: rabbitmq: 388s, normally up
ok: down: redis_lb: 387s, normally up

tail¶

The <tt class="docutils literal">tail</tt> subcommand is used to follow all of the Chef server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl tail name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.

term¶

The <tt class="docutils literal">term</tt> subcommand is used to send a <tt class="docutils literal">SIGTERM</tt> to all services. This command can also be run for an individual service by specifying the name of the service in the command.

This subcommand has the following syntax:

$ chef-server-ctl term name_of_service

where <tt class="docutils literal">name_of_service</tt> represents the name of any service that is listed after running the <tt class="docutils literal">service-list</tt> subcommand.


text:
id: polycasts-season-1
showid: polycasts
layout: shows/series-index
collection: polycasts
title: "Polycasts: Season 1"
description: ""
published: true

date: 2014-09-22
article:
  written_on: 2015-02-24
  updated_on: 2015-02-24
---

redpajama_set_name: RedPajamaGithub


text:
namespace device {

class UsbDeviceHandle;

struct CombinedInterfaceInfo {
  CombinedInterfaceInfo() = default;
  CombinedInterfaceInfo(const mojom::UsbInterfaceInfo* interface,
                        const mojom::UsbAlternateInterfaceInfo* alternate);

  bool IsValid() const;

  const mojom::UsbInterfaceInfo* interface = nullptr;
  const mojom::UsbAlternateInterfaceInfo* alternate = nullptr;
};

struct UsbDeviceDescriptor {
  UsbDeviceDescriptor();
  UsbDeviceDescriptor(const UsbDeviceDescriptor& other) = delete;
  ~UsbDeviceDescriptor();

  // Parses |buffer| for USB descriptors. Any configuration descriptors found
  // will be added to |configurations|. If a device descriptor is found it will
  // be used to populate this struct's fields. This function may be called more
  // than once (i.e. for multiple buffers containing a configuration descriptor
  // each).
  bool Parse(base::span<const uint8_t> buffer);

  uint8_t i_manufacturer = 0;
  uint8_t i_product = 0;
  uint8_t i_serial_number = 0;
  uint8_t num_configurations = 0;
  mojom::UsbDeviceInfoPtr device_info;
};

void ReadUsbDescriptors(
    scoped_refptr<UsbDeviceHandle> device_handle,
    base::OnceCallback<void(std::unique_ptr<UsbDeviceDescriptor>)> callback);

bool ParseUsbStringDescriptor(const std::vector<uint8_t>& descriptor,
                              std::u16string* output);

void ReadUsbStringDescriptors(
    scoped_refptr<UsbDeviceHandle> device_handle,
    std::unique_ptr<std::map<uint8_t, std::u16string>> index_map,
    base::OnceCallback<void(std::unique_ptr<std::map<uint8_t, std::u16string>>)>
        callback);

mojom::UsbEndpointInfoPtr BuildUsbEndpointInfoPtr(const uint8_t* data);

mojom::UsbEndpointInfoPtr BuildUsbEndpointInfoPtr(uint8_t address,
                                                  uint8_t attributes,
                                                  uint16_t maximum_packet_size,
                                                  uint8_t polling_interval);

mojom::UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(const uint8_t* data);

mojom::UsbInterfaceInfoPtr BuildUsbInterfaceInfoPtr(uint8_t interface_number,
                                                    uint8_t alternate_setting,
                                                    uint8_t interface_class,
                                                    uint8_t interface_subclass,
                                                    uint8_t interface_protocol);

void AggregateInterfacesForConfig(mojom::UsbConfigurationInfo* config);

CombinedInterfaceInfo FindInterfaceInfoFromConfig(
    const mojom::UsbConfigurationInfo* config,
    uint8_t interface_number,
    uint8_t alternate_setting);

mojom::UsbConfigurationInfoPtr BuildUsbConfigurationInfoPtr(
    const uint8_t* data);

mojom::UsbConfigurationInfoPtr BuildUsbConfigurationInfoPtr(
    uint8_t configuration_value,
    bool self_powered,
    bool remote_wakeup,
    uint8_t maximum_power);

void AssignFirstInterfaceNumbers(mojom::UsbConfigurationInfo* config);

}  // namespace device

#endif  // SERVICES_DEVICE_USB_USB_DESCRIPTORS_H_


text:
package tcert

import (
	"crypto/ecdsa"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha512"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"encoding/base64"
	"fmt"
	"time"

	"math/big"
	"strconv"

	"github.com/cloudflare/cfssl/log"
)

var (
	// TCertEncTCertIndex is the ASN1 object identifier of the TCert index.
	TCertEncTCertIndex = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 7}

	// TCertEncEnrollmentID is the ASN1 object identifier of the enrollment id.
	TCertEncEnrollmentID = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 8}

	// TCertAttributesHeaders is the ASN1 object identifier of attributes header.
	TCertAttributesHeaders = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 9}

	// Padding for encryption.
	Padding = []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}

	// tcertSubject is the subject name placed in all generated TCerts
	tcertSubject = pkix.Name{CommonName: "Fabric Transaction Certificate"}
)

// LoadMgr is the constructor for a TCert manager given key and certificate file names
// @parameter caKeyFile is the file name for the CA's key
// @parameter caCertFile is the file name for the CA's cert
func LoadMgr(caKeyFile, caCertFile string) (*Mgr, error) {
	caKey, err := LoadKey(caKeyFile)
	if err != nil {
		return nil, err
	}
	caCert, err := LoadCert(caCertFile)
	if err != nil {
		return nil, err
	}
	return NewMgr(caKey, caCert)
}

// NewMgr is the constructor for a TCert manager given a key and an x509 certificate
// @parameter caKey is used for signing a certificate request
// @parameter caCert is used for extracting CA data to associate with issued certificates
func NewMgr(caKey interface{}, caCert *x509.Certificate) (*Mgr, error) {
	mgr := new(Mgr)
	mgr.CAKey = caKey
	mgr.CACert = caCert
	mgr.ValidityPeriod = time.Hour * 24 * 365 // default to 1 year
	mgr.MaxAllowedBatchSize = 1000
	return mgr, nil
}

// Mgr is the manager for the TCert library
type Mgr struct {
	// CAKey is used for signing a certificate request
	CAKey interface{}
	// CACert is used for extracting CA data to associate with issued certificates
	CACert *x509.Certificate
	// ValidityPeriod is the duration that the issued certificate will be valid
	// unless the user requests a shorter validity period.
	// The default value is 1 year.
	ValidityPeriod time.Duration
	// MaxAllowedBatchSize is the maximum number of TCerts which can be requested at a time.
	// The default value is 1000.
	MaxAllowedBatchSize uint
}

// GetBatch gets a batch of TCerts
// @parameter req Is the TCert batch request
// @parameter ecert Is the enrollment certificate of the caller
func (tm *Mgr) GetBatch(req *GetBatchRequest, ecert *x509.Certificate) (*GetBatchResponse, error) {

	log.Debugf("GetBatch req=%+v", req)

	// Set numTCertsInBatch to the number of TCerts to get.
	// If 0 are requested, retrieve the maximum allowable;
	// otherwise, retrieve the number requested it not too many.
	var numTCertsInBatch int
	if req.Count == 0 {
		numTCertsInBatch = int(tm.MaxAllowedBatchSize)
	} else if req.Count <= tm.MaxAllowedBatchSize {
		numTCertsInBatch = int(req.Count)
	} else {
		return nil, fmt.Errorf("You may not request %d TCerts; the maximum is %d",
			req.Count, tm.MaxAllowedBatchSize)
	}

	// Certs are valid for the min of requested and configured max
	vp := tm.ValidityPeriod
	if req.ValidityPeriod > 0 && req.ValidityPeriod < vp {
		vp = req.ValidityPeriod
	}

	// Create a template from which to create all other TCerts.
	// Since a TCert is anonymous and unlinkable, do not include
	template := &x509.Certificate{
		Subject: tcertSubject,
	}
	template.NotBefore = time.Now()
	template.NotAfter = template.NotBefore.Add(vp)
	template.IsCA = false
	template.KeyUsage = x509.KeyUsageDigitalSignature
	template.SubjectKeyId = []byte{1, 2, 3, 4}

	// Generate nonce for TCertIndex
	nonce := make([]byte, 16) // 8 bytes rand, 8 bytes timestamp
	rand.Reader.Read(nonce[:8])

	pub := ecert.PublicKey.(*ecdsa.PublicKey)

	mac := hmac.New(sha512.New384, []byte(createHMACKey()))
	raw, _ := x509.MarshalPKIXPublicKey(pub)
	mac.Write(raw)
	kdfKey := mac.Sum(nil)

	var set []TCert

	for i := 0; i < numTCertsInBatch; i++ {
		tcertid, uuidError := GenerateIntUUID()
		if uuidError != nil {
			return nil, fmt.Errorf("Failure generating UUID: %s", uuidError)
		}
		// Compute TCertIndex
		tidx := []byte(strconv.Itoa(2*i + 1))
		tidx = append(tidx[:], nonce[:]...)
		tidx = append(tidx[:], Padding...)

		mac := hmac.New(sha512.New384, kdfKey)
		mac.Write([]byte{1})
		extKey := mac.Sum(nil)[:32]

		mac = hmac.New(sha512.New384, kdfKey)
		mac.Write([]byte{2})
		mac = hmac.New(sha512.New384, mac.Sum(nil))
		mac.Write(tidx)

		one := new(big.Int).SetInt64(1)
		k := new(big.Int).SetBytes(mac.Sum(nil))
		k.Mod(k, new(big.Int).Sub(pub.Curve.Params().N, one))
		k.Add(k, one)

		tmpX, tmpY := pub.ScalarBaseMult(k.Bytes())
		txX, txY := pub.Curve.Add(pub.X, pub.Y, tmpX, tmpY)
		txPub := ecdsa.PublicKey{Curve: pub.Curve, X: txX, Y: txY}

		// Compute encrypted TCertIndex
		encryptedTidx, encryptErr := CBCPKCS7Encrypt(extKey, tidx)
		if encryptErr != nil {
			return nil, encryptErr
		}

		extensions, ks, extensionErr := generateExtensions(tcertid, encryptedTidx, ecert, req)

		if extensionErr != nil {
			return nil, extensionErr
		}

		template.PublicKey = txPub
		template.Extensions = extensions
		template.ExtraExtensions = extensions
		template.SerialNumber = tcertid

		raw, err := x509.CreateCertificate(rand.Reader, template, tm.CACert, &txPub, tm.CAKey)
		if err != nil {
			return nil, fmt.Errorf("Failed in TCert x509.CreateCertificate: %s", err)
		}

		pem := ConvertDERToPEM(raw, "CERTIFICATE")

		set = append(set, TCert{pem, ks})
	}

	tcertID := GenNumber(big.NewInt(20))
	tcertResponse := &GetBatchResponse{tcertID, time.Now(), kdfKey, set}

	return tcertResponse, nil

}

/**
*  Create HMAC Key
*  returns HMAC String
 */
func createHMACKey() string {
	key := make([]byte, 49)
	rand.Reader.Read(key)
	var cooked = base64.StdEncoding.EncodeToString(key)
	return cooked
}

// Generate encrypted extensions to be included into the TCert (TCertIndex, EnrollmentID and attributes).
func generateExtensions(tcertid *big.Int, tidx []byte, enrollmentCert *x509.Certificate, batchRequest *GetBatchRequest) ([]pkix.Extension, map[string][]byte, error) {
	// For each TCert we need to store and retrieve to the user the list of Ks used to encrypt the EnrollmentID and the attributes.
	ks := make(map[string][]byte)
	attrs := batchRequest.Attrs
	extensions := make([]pkix.Extension, len(attrs))

	preK1 := batchRequest.PreKey
	mac := hmac.New(sha512.New384, []byte(preK1))
	mac.Write(tcertid.Bytes())
	preK0 := mac.Sum(nil)

	// Compute encrypted EnrollmentID
	mac = hmac.New(sha512.New384, preK0)
	mac.Write([]byte("enrollmentID"))
	enrollmentIDKey := mac.Sum(nil)[:32]

	enrollmentID := []byte(GetEnrollmentIDFromCert(enrollmentCert))
	enrollmentID = append(enrollmentID, Padding...)

	encEnrollmentID, err := CBCPKCS7Encrypt(enrollmentIDKey, enrollmentID)
	if err != nil {
		return nil, nil, err
	}

	// save k used to encrypt EnrollmentID
	ks["enrollmentId"] = enrollmentIDKey

	attributeIdentifierIndex := 9
	count := 0
	attributesHeader := make(map[string]int)

	// Append attributes to the extensions slice
	for i := 0; i < len(attrs); i++ {
		count++
		name := attrs[i].Name
		value := []byte(attrs[i].Value)

		// Save the position of the attribute extension on the header.
		attributesHeader[name] = count

		// Encrypt attribute if enabled
		if batchRequest.EncryptAttrs {
			mac = hmac.New(sha512.New384, preK0)
			mac.Write([]byte(name))
			attributeKey := mac.Sum(nil)[:32]

			value = append(value, Padding...)
			value, err = CBCPKCS7Encrypt(attributeKey, value)
			if err != nil {
				return nil, nil, err
			}

			// Save the key used to encrypt the attribute
			ks[name] = attributeKey
		}

		// Generate an ObjectIdentifier for the extension holding the attribute
		TCertEncAttributes := asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, attributeIdentifierIndex + count}

		// Add the attribute extension to the extensions array
		extensions[count-1] = pkix.Extension{Id: TCertEncAttributes, Critical: false, Value: value}
	}

	// Append the TCertIndex to the extensions
	extensions = append(extensions, pkix.Extension{Id: TCertEncTCertIndex, Critical: true, Value: tidx})

	// Append the encrypted EnrollmentID to the extensions
	extensions = append(extensions, pkix.Extension{Id: TCertEncEnrollmentID, Critical: false, Value: encEnrollmentID})

	// Append the attributes header if there was attributes to include in the TCert
	if len(attrs) > 0 {
		extensions = append(extensions, pkix.Extension{Id: TCertAttributesHeaders, Critical: false, Value: buildAttributesHeader(attributesHeader)})
	}

	return extensions, ks, nil
}

func buildAttributesHeader(attributesHeader map[string]int) []byte {
	var headerString string
	for k, v := range attributesHeader {
		headerString = headerString + k + "->" + strconv.Itoa(v) + "#"
	}
	return []byte(headerString)
}


text:
<!DOCTYPE html>

<link rel="help" href="https://drafts.css-houdini.org/css-layout-api/#dom-layoutconstraintsoptions-fixedblocksize">
<link rel="match" href="../green-square-ref.html">
<meta name="assert" content="This test checks that fixing the block size of children works as expected." />


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.DynamoDB.Model
{
    /// <summary>Put Item Result
    /// </summary>
    public class PutItemResult
    {

        private Dictionary<string,AttributeValue> attributes = new Dictionary<string,AttributeValue>();
        private double? consumedCapacityUnits;

        /// <summary>
        /// Attribute values before the put operation, but only if the <c>ReturnValues</c> parameter is specified as <c>ALL_OLD</c> in the request.
        ///
        /// </summary>
        public Dictionary<string,AttributeValue> Attributes
        {
            get { return this.attributes; }
            set { this.attributes = value; }
        }

        /// <summary>
        /// Adds the KeyValuePairs to the Attributes dictionary.
        /// </summary>
        /// <param name="pairs">The pairs to be added to the Attributes dictionary.</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PutItemResult WithAttributes(params KeyValuePair<string, AttributeValue>[] pairs)
        {
            foreach (KeyValuePair<string, AttributeValue> pair in pairs)
            {
                this.Attributes[pair.Key] = pair.Value;
            }

            return this;
        }

        // Check to see if Attributes property is set
        internal bool IsSetAttributes()
        {
            return this.attributes != null;
        }

        /// <summary>
        /// The number of Capacity Units of the provisioned throughput of the table consumed during the operation. <c>GetItem</c>, <c>BatchGetItem</c>,
        /// <c>BatchWriteItem</c>, <c>Query</c>, and <c>Scan</c> operations consume <c>ReadCapacityUnits</c>, while <c>PutItem</c>, <c>UpdateItem</c>,
        /// and <c>DeleteItem</c> operations consume <c>WriteCapacityUnits</c>.
        ///
        /// </summary>
        public double ConsumedCapacityUnits
        {
            get { return this.consumedCapacityUnits ?? default(double); }
            set { this.consumedCapacityUnits = value; }
        }

        /// <summary>
        /// Sets the ConsumedCapacityUnits property
        /// </summary>
        /// <param name="consumedCapacityUnits">The value to set for the ConsumedCapacityUnits property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PutItemResult WithConsumedCapacityUnits(double consumedCapacityUnits)
        {
            this.consumedCapacityUnits = consumedCapacityUnits;
            return this;
        }

        // Check to see if ConsumedCapacityUnits property is set
        internal bool IsSetConsumedCapacityUnits()
        {
            return this.consumedCapacityUnits.HasValue;
        }
    }
}


text:
package edu.umb.cs110.q01a.q01;

public class Daltons {
	public static void main (String[] args) {
		boolean result = false;
		// Check if brothers are from shortest to tallest
		if (args[0].equals("Joe") && args[1].equals("William") && args[2].equals("Jack") && args[3].equals("Averell")) {
			result = true;
		}
		// Check if brothers are from tallest to shortest
		else if (args[0].equals("Averell") && args[1].equals("Jack") && args[2].equals("William") && args[3].equals("Joe")) {
			result = true;
		}
		System.out.println(result);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Microsoft.Research.Science.Data.Climate.Common
{
    public struct DataScale
    {
        public double AddOffset, ScaleFactor, MissingValue;
        public DataScale(Variable v)
        {
            double add_offset = 0;
            double scale_factor = 1.0;
            double missingValue = double.NaN;

            string[] AddOffsetKeys = new string[] { "add_offset", "AddOffset" };
            string[] MissingValueKeys = new string[] { "missing_value", "MissingValue" };
            string[] scaleFactorKeys = new string[] { "scale_factor", "ScaleFactor" };

            foreach (string ao_key in AddOffsetKeys)
                if (v.Metadata.ContainsKey(ao_key))
                {
                    add_offset = Convert.ToDouble(v.Metadata[ao_key]);
                    break;
                }

            foreach (string sf_key in scaleFactorKeys)
                if (v.Metadata.ContainsKey(sf_key))
                {
                    scale_factor = Convert.ToDouble(v.Metadata[sf_key]);
                    break;
                }

            foreach (string mv_key in MissingValueKeys)
                if (v.Metadata.ContainsKey(mv_key))
                {
                    missingValue = Convert.ToDouble(v.Metadata[mv_key]);
                    break;
                }

            MissingValue = missingValue;
            AddOffset = add_offset;
            ScaleFactor = scale_factor;
        }
    }
}


text:
const BaseException = global.InvalidArgumentException;
const ExceptionInterface = Jymfony.Component.Console.Exception.ExceptionInterface;

/**
 * @memberOf Jymfony.Component.Console.Exception
 */
export default class InvalidArgumentException extends mix(BaseException, ExceptionInterface) {
}


text:
// This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT

use Actionable;
use Bin;
use Button;
use ColorChooser;
use Container;
use Widget;
use ffi;
use gdk;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem::transmute;

glib_wrapper! {
    pub struct ColorButton(Object<ffi::GtkColorButton>): Button, Bin, Container, Widget, Actionable, ColorChooser;

    match fn {
        get_type => || ffi::gtk_color_button_get_type(),
    }
}

impl ColorButton {
    pub fn new() -> ColorButton {
        assert_initialized_main_thread!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_color_button_new()).downcast_unchecked()
        }
    }

    pub fn new_with_rgba(rgba: &gdk::RGBA) -> ColorButton {
        assert_initialized_main_thread!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_color_button_new_with_rgba(rgba.to_glib_none().0)).downcast_unchecked()
        }
    }
}

pub trait ColorButtonExt {
    fn get_title(&self) -> Option<String>;

    //fn set_color(&self, color: /*Ignored*/&gdk::Color);

    fn set_title(&self, title: &str);

    fn get_property_alpha(&self) -> u32;

    fn set_property_alpha(&self, alpha: u32);

    #[cfg(feature = "v3_20")]
    fn get_property_show_editor(&self) -> bool;

    #[cfg(feature = "v3_20")]
    fn set_property_show_editor(&self, show_editor: bool);

    fn connect_color_set<F: Fn(&Self) + 'static>(&self, f: F) -> u64;
}

impl<O: IsA<ColorButton> + IsA<glib::object::Object>> ColorButtonExt for O {
    fn get_title(&self) -> Option<String> {
        unsafe {
            from_glib_none(ffi::gtk_color_button_get_title(self.to_glib_none().0))
        }
    }

    //fn set_color(&self, color: /*Ignored*/&gdk::Color) {
    //    unsafe { TODO: call ffi::gtk_color_button_set_color() }
    //}

    fn set_title(&self, title: &str) {
        unsafe {
            ffi::gtk_color_button_set_title(self.to_glib_none().0, title.to_glib_none().0);
        }
    }

    fn get_property_alpha(&self) -> u32 {
        let mut value = Value::from(&0u32);
        unsafe {
            gobject_ffi::g_object_get_property(self.to_glib_none().0, "alpha".to_glib_none().0, value.to_glib_none_mut().0);
        }
        value.get().unwrap()
    }

    fn set_property_alpha(&self, alpha: u32) {
        unsafe {
            gobject_ffi::g_object_set_property(self.to_glib_none().0, "alpha".to_glib_none().0, Value::from(&alpha).to_glib_none().0);
        }
    }

    #[cfg(feature = "v3_20")]
    fn get_property_show_editor(&self) -> bool {
        let mut value = Value::from(&false);
        unsafe {
            gobject_ffi::g_object_get_property(self.to_glib_none().0, "show-editor".to_glib_none().0, value.to_glib_none_mut().0);
        }
        value.get().unwrap()
    }

    #[cfg(feature = "v3_20")]
    fn set_property_show_editor(&self, show_editor: bool) {
        unsafe {
            gobject_ffi::g_object_set_property(self.to_glib_none().0, "show-editor".to_glib_none().0, Value::from(&show_editor).to_glib_none().0);
        }
    }

    fn connect_color_set<F: Fn(&Self) + 'static>(&self, f: F) -> u64 {
        unsafe {
            let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
            connect(self.to_glib_none().0, "color-set",
                transmute(color_set_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
        }
    }
}

unsafe extern "C" fn color_set_trampoline<P>(this: *mut ffi::GtkColorButton, f: glib_ffi::gpointer)
where P: IsA<ColorButton> {
    callback_guard!();
    let f: &Box_<Fn(&P) + 'static> = transmute(f);
    f(&ColorButton::from_glib_none(this).downcast_unchecked())
}


text:
package net.voxelindustry.brokkgui.style.parser;

import net.voxelindustry.brokkgui.style.selector.IStyleSelector;
import net.voxelindustry.brokkgui.style.selector.StyleSelector;
import net.voxelindustry.brokkgui.style.selector.StyleSelectorHierarchic;
import net.voxelindustry.brokkgui.style.selector.StyleSelectorType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class StyleSelectorParserTest
{
    private StyleSelectorParser parser;

    @BeforeEach
    public void setup()
    {
        this.parser = new StyleSelectorParser();
    }

    @Test
    public void testSelectorClean()
    {
        String simpleTest = "button .class";

        assertThat(parser.cleanSelector(simpleTest)).isEqualTo("button>>.class");

        String trimTest = "button > .class";

        assertThat(parser.cleanSelector(trimTest)).isEqualTo("button>.class");

        String replaceAndTrim = "button >>  .class text";

        assertThat(parser.cleanSelector(replaceAndTrim)).isEqualTo("button>>.class>>text");
    }

    @Test
    public void testSelectorOr()
    {
        String simpleOr = "button , text";

        IStyleSelector[] selectors = parser.readSelectors(simpleOr);

        assertThat(selectors.length).isEqualTo(2);

        assertThat(selectors[0].match(new StyleSelector().add(StyleSelectorType.TYPE, "button"))).isTrue();
        assertThat(selectors[1].match(new StyleSelector().add(StyleSelectorType.TYPE, "text"))).isTrue();
    }

    @Test
    public void testStructurals()
    {
        String firstChild = "button:first-child";

        IStyleSelector[] selectors = parser.readSelectors(firstChild);

        assertThat(selectors.length).isEqualTo(1);

        assertThat(selectors[0].match(new StyleSelector().add(StyleSelectorType.TYPE, "button").add(StyleSelectorType.STRUCTURAL_PSEUDOCLASS, "first-child"))).isTrue();
    }

    @Test
    public void testSimpleHierarchic()
    {
        String simpleHierarchic = "button > text";
        StyleSelector parent = new StyleSelector().add(StyleSelectorType.TYPE, "button");
        StyleSelector child = new StyleSelector().add(StyleSelectorType.TYPE, "text");
        IStyleSelector[] selectors = parser.readSelectors(simpleHierarchic);

        assertThat(selectors.length).isEqualTo(1);

        assertThat(selectors[0]).isInstanceOf(StyleSelectorHierarchic.class);

        assertThat(((StyleSelectorHierarchic) selectors[0]).isDirectChild()).isTrue();
        assertThat(((StyleSelectorHierarchic) selectors[0]).getParentSelector().match(parent)).isTrue();
        assertThat(((StyleSelectorHierarchic) selectors[0]).getChildSelector().match(child)).isTrue();
    }

    @Test
    public void testTwoGenerationHierarchic()
    {
        String twoGenerationHierarchic = "pane button > text";
        StyleSelector grandparent = new StyleSelector().add(StyleSelectorType.TYPE, "pane");
        StyleSelector parent = new StyleSelector().add(StyleSelectorType.TYPE, "button");
        StyleSelector child = new StyleSelector().add(StyleSelectorType.TYPE, "text");

        IStyleSelector[] twoGenerationSelectors = parser.readSelectors(twoGenerationHierarchic);

        assertThat(twoGenerationSelectors[0]).isInstanceOf(StyleSelectorHierarchic.class);

        StyleSelectorHierarchic selector = (StyleSelectorHierarchic) twoGenerationSelectors[0];

        assertThat(selector.getParentSelector().match(new StyleSelectorHierarchic(grandparent, parent, false))).isTrue();
        assertThat(selector.isDirectChild()).isTrue();

        assertThat(selector.getChildSelector()).isInstanceOf(StyleSelector.class);
        assertThat(selector.getParentSelector()).isInstanceOf(StyleSelectorHierarchic.class);

        assertThat(((StyleSelectorHierarchic) selector.getParentSelector()).getParentSelector().match(grandparent)).isTrue();
    }
}


text:
@interface WControllerFactory : NSObject

+ (instancetype)instance ;

@end


text:
NodeJS Mirror API Utils
==========================

## WARNING

This library does not provide a stable API. It is in development and is very subject to change.

## About

This is a helper utility library for the Google Glass Mirror API. Here is how to use it with express:

    var mirror = require('mirror-utils');
    var authUtils = new mirror.Auth();
    var cardUtils = new mirror.Card();
    var contactUtils = new mirror.Contacts();
    var menuUtils = new mirror.Menu();

    app.get('/install', authUtils.install);
    app.get('/oauth2callback', function(req, res){
        // if we're able to grab the token, redirect the user back to the main page
        authUtils.getToken(req.query.code, function(data) {
            console.log('failure',data);
            res.end();
        }, function(oauth2Client, client) {
            console.log('success',oauth2Client, client);
            var timelineUtils = new mirror.Timeline(oauth2Client, client);
            var menu = menuUtils.buildSimpleDefault().build();
            var card = cardUtils.reset().id(123).title("test").text("hello").menus(menu).build();
            console.log('try to insert card',card);
            timelineUtils.insertCard(card, failure, success);
            res.end();
        });
    });

More documentation to come.

This is a work in progress.


text:
Veel botnets maken gebruik van het HTTP protocol omdat bijna elke firewall dit
verkeer door laat. Daar bovenop wordt dan hun eigen protocol geïmplementeerd.
Dit bestaat vaak uit het opvragen van een nieuwe opdracht door de cliënt zodat
de command server niet overbelast raakt.

##### Samenwerken met Jaap om een protocol samen te stellen tussen client en server
De basis API is bestaat uit het versturen van het versturen van de rijen van de
eerste matrix en kolommen van de tweede matrix. Dan vermenigvuldigt de client
elke rij met elke kolom en stuurte de resultaten daarvan terug.

##### Libraries uitzoeken voor gebruik in de client
Om vanuit Python HTTP requests te sturen naar een server is de requests library
het simpelst om te gebruiken. Het is ook ruimschoots uitgebreid genoeg voor de
features die wij nodig hebben. Voor het meten van het CPU gebruik is psutil de
meest gebruikelijk optie. Angezien we ook geen ingewikkelde metingen hoeven te
doen voor de CPU load heeft deze library genoeg functionaliteit.

### Week 3
##### Vermenigvuldigen van rijen en kolommen in de in de vorm van de API
Omdat de client en de server naast elkaar worden ontwikkeld werd de client eerst
geimplementeerd met een vaste datastructuur gebaseerd op de afgesproken API.
Bij het maken van die datastructuur bleek er wat onnodige informatie expcliciet
meegegeven te worden. Dit is uit de API gehaald en de datastructuur is toen
gebaseerd op de vernieuwde API.

##### Basis protocol naar server implementeren voor matrices
Het implementeren van het protocol was niet al te ingewikkeld. De requests
library voor Python is vrij simpel te gebruiken. In combinatie met de standaard
json module was het geen enkel probleem om json data te versturen naar de
server.

##### Client cpu load bepalen en sturen naar de server
De CPU load moet gemeten worden in een apparte thread van het main programma,
aangezien er anders niet gemeten kan worden met vastgesteld interval. Een
interval is nodig zodat de server op de hoogte gesteld kan worden van de staat
van de client.

##### Verminderen van de request overhead op de server
Nadat de communicatie tussen de client en server werkte bleek dat de elke
request toch een behoorlijke overhead had. Voor enige optimalisatie duurde het
versturen van het request ongeveer 5 keer zoveel tijd als de daadwerkelijke
die nodig was voor de client om zijn stuk matrix uit te rekenen. Dit hebben we
op een aantal verschillende manieren verminderd.

Een van de eerste dingen om de relatieve overhead te verminderen was veel meer
rijen en kolommen sturen per request.  De overhead per request gaat in theorie
lineair omhoog (r + k) en het werk dat de client kan uitvoeren gaat kwadratisch
omhoog (r * k). Dit hielp erg goed in de verhouding in tijd tussen de request en
en het werk van de client te verbeteren. Het rekenen duurde nu ongeveer
anderhalf keer zo lang als de tijd die nodig was om de request te versturen. Dit
was natuurlijk nog steeds niet goed genoeg, maar ondertussen liepen we tegen een
ander probleem aan. Hoewel de overhead relatief steeds beter werd naarmate er
meer data per keer werd verstuurd, werd uiteraard de absolute tijd voor die per
request nodig was steeds hoger. Dit liep al tegen de 5 seconden per request aan.
Dit was onacceptabel aangezien de server dan geen andere requests meer af kon
handelen in die tijd.

Er waren 2 grote posten waardoor die tijd zo op liep. Als eerste werd er zonder
goede reden een matrix weggeschreven naar de hardeschijf. De code voor het
wegschrijven van matrices was niet erg efficient, dus deze is verbetert en
verder wordt deze specifieke matrix ook niet meer weggeschreven.

De tweede post lag in de JSON serialisatie. Deze post is op twee verschillende
manieren vermindert. Allereerst is de structuur van de API aangepast. In plaats
van het sturen van rijen en kolommen als losse arrays, stuurt de server nu twee
2D arrays, A en B, respectievelijk bestaande uit de rijen van de eerste matrix
en de kolommen van de tweede matrix die de client met elkaar moet
vermenigvuldigen. Daarna was het een al een stukje sneler, maar het was nog niet
eigenlijk nog niet snel genoeg. We hebben getest waar het grootste probleem zat
bij de serialisatie en dat bleek het serialiseren van alle floats te zijn. Dit
bleek toen eigenlijk vrij onzinnig om uberhaupt te doen. Die floats die
geserialised werden stonden als strings in het matrix bestand. Bij het inladen
van een matrix werden ze omgezet naar floats en dan werden ze bij het
serialiseren weer omgezet naar strings. Daarna werden ze bij de client bij het
deserialiseren weer omgezet naar floats. We hebben het dus gewoon strings gelaten
en zijn ze pas bij de client expliciet gaan omzetten naar floats. Uiteindelijk
heeft dit alles ervoor gezorgd dat de requests minder dan een seconde server
tijd in beslag nemen.

### Week 4
- Verslag schrijven


text:
var through = require("through2");
var I18nliner = require("i18nliner");
var config = I18nliner.config;
var preprocess = require("./preprocess");
var hasTranslatableText = require("./hasTranslatableText")(config);

module.exports = function(file) {
  return through(function (buf, enc, next) {
    var source = buf.toString('utf8');
    if (hasTranslatableText(source))
      source = preprocess(source, config);
    this.push(source);
    next();
  });
};


text:
package uk.co.omegaprime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Utils {
    public static double[] floatsToDoubles(float[] floats) {
        final double[] doubles = new double[floats.length];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = floats[i];
        }
        return doubles;
    }

    public static float[] getExampleData() throws IOException {
        final float[] vod;
        try (BufferedReader r = new BufferedReader(new InputStreamReader(ConditionerTest.class.getResourceAsStream("Vodafone.csv")))) {
            final ArrayList<Float> floats = new ArrayList<Float>();
            String line;
            while ((line = r.readLine()) != null) {
                floats.add(Float.parseFloat(line));
            }

            vod = new float[floats.size()];
            for (int i = 0; i < floats.size(); i++) {
                vod[i] = floats.get(i);
            }
        }
        return vod;
    }

    static long skipAll(InputStream is) throws IOException {
        long skipped;
        long totalSkipped = 0;
        do {
            skipped = is.skip(1024 * 1024);
            if (skipped == 0) {
                if (is.read() >= 0) {
                    skipped = 1;
                }
            }
            totalSkipped += skipped;
        } while (skipped > 0);

        return totalSkipped;
    }
}


text:
/**
 * Created by jack on 16-4-21.
 */

import Vue from 'vue';
import Component from 'vue-class-component';
import throttle from 'lodash/throttle';

import './style.scss';
import * as DOMUtil from '@/common/util/dom';
import template from './template.html';

const DESKTOP_MODE = 'desktop';

@Component({
	props: ['navList', 'mode'],
	template,
})
class Navigation extends Vue {
	public mode: string;
	public isShowList: boolean = false;
	private isVisible: boolean = false;
	private isFixed: boolean = false;
	private navHeight: number = 0;
	private prevScrollTop: number = 0;
	private listener: () => void;

	/*
	 * lifesycle start
	 */
	protected mounted() {
		this.initNav(this.mode);
	}
	protected destroyed() {
		this.mode === DESKTOP_MODE && document.removeEventListener('scroll', this.listener);
	}
	/*
	 * lifesycle start
	 */

	/*
	 * methods start
	 */
	private initNav(mode = DESKTOP_MODE) {
		if (mode === DESKTOP_MODE) {
			this.navHeight = this.$el.clientHeight;

			this.listener = throttle(this.bodyScrollListener, 200);
			document.addEventListener('scroll', this.listener);
		}
	}
	private bodyScrollListener() {
		const currScrollTop = DOMUtil.getDocumentScrollTop();

		if (currScrollTop < this.prevScrollTop) {
			// if scrolling up...
			if (currScrollTop > 0 && this.isFixed) {
				this.isVisible = true;
			} else {
				// scroll to the top
				this.isVisible = false;
				this.isFixed = false;
			}
		} else if (currScrollTop > this.prevScrollTop) {
			// if scrolling down...
			this.isVisible = false;
			currScrollTop > this.navHeight && (this.isFixed = true);
		}

		this.prevScrollTop = currScrollTop;
	}
	private toggleNavShown() {
		this.isShowList = !this.isShowList;
	}
	/*
	 * methods end
	 */
}

export default Vue.component('navigation', Navigation);


text:
// ---------------------------------------------------------------------------------
//
//  Summary view - combines listview of codeTrack items with a status bar view
//
//  This view brings together 2 other views to create an overview of codeTracks.
//  One child view is a list of codetrack items and below that is a list footer
//  which provides feedback on collection status (e.g., total # of items).
//  So, this view does little work beyond creating/combining its child views.
//
//  The el for this view is a div with display:flex (i.e. it uses CSS flexbox).
//  This simplifies laying out child views and using available space: a footer
//  of fixed height is at bottom, with the list above it filling remaining space.
//
//  This view is a bit of an exploration, definitely non-standard. That's because
//  this view is reused -- that is, it's created once and never remove()'d, just
//  reparented and sometimes cached off-DOM (caching can happen when in singlePane
//  layout). In general Backbone views are created/destroyed as needed and their
//  render may be run many times. However, since this demo app displays this view
//  so much of the time (100% of the time in dualPane layout) I wanted to have it
//  persistent and just hide or reparent as necessary. Still, in most cases keeping
//  views around and reusing instead of recreating and/or rerendering them is
//  probably more trouble than it's worth.
//
//  Child view handling here is minimal, vastly simplified by the fact that this view
//  is created once per session and then reused, never re-rendered, and never remove()'d.
//  That means we don't need to worry about cleaning up child views to avoid memory leaks.
//  For more on this see the JSCT Overview post sections on Nesting Views and Zombie Views
//
// ---------------------------------------------------------------------------------------
/*global Backbone, jQuery */

(function ($) {

    'use strict';

    jsct.SummaryView = Backbone.View.extend({

        // el => no el or tagName specified here OR passed in via a constructor
        // parm so Backbone creates a default empty <div> for wrapper, el value

        className: "flexboxContainer",

        // Note: this id is just used to make div easier to recognize in devtools Elements view, otherwise not used
        id: "summaryView",

        template: _.template($('#summary-template').html()),

        initialize: function () {

            if (jsct.showDiags) {
                console.log("VIEW: Summary INITIALIZE() executing");
                console.info("%cNote: Summary view contains 2 child views which display 1) the list and 2) the list footer",
                    "color:#407cc9;font-weight:bold");
            }
            this.listenTo(jsct.application, 'change:filterIsActive', this.setFilterCue);
            // This view is rendered only once. However, while not needing more renders
            // it does need to update the global msgline whenever it's displayed...
            this.listenTo(jsct.application, 'change:currentState', this.refresh);
        },

        // This render is a bit unusual, run just once per session - for details see header commment above
        render: function () {

            if (jsct.showDiags) console.log("VIEW: Summary RENDER() executing");

            // Fill el with view's markup so we can work with its elements, but note this isn't on DOM yet
            this.$el.html(this.template());

            // --------------------------------------------------------------------------------------------
            // Generate child views and put them into <div> elements defined in Summary's template. Child
            // CodeTrackList is a list of all codeTrack items. Child StatusBar view is used as list footer.
            // NOTE: This demos 2 DIFFERENT METHODS of putting the child view in the DOM/document. In both
            // methods the child views are ignorant of their document context -- i.e. it's the parent view
            // that determines where the child views are inserted into the DOM/document. This keeps those
            // child views loosely coupled, maximizes flexibility for how/where the child views are used.
            // --------------------------------------------------------------------------------------------

            // METHOD 1: Summary view instantiates CodeTrackList with the child's el coming via the child's
            // tagName property (i.e., BB creates the element). The render() populates this el and then the
            // result (returned by render()) is html()'d into #listMain. Bottom line: the parent determines
            // where this child view is inserted into the DOM/document), child is ignorant of DOM context.
            this.$("#listMain").html(new jsct.CodeTrackList().render().el);

            // METHOD 2: Summary view passes to its StatusBar child an el value (a <div> defined in this
            // view's template and created at the start of this render()). As with Method 1, this approach
            // keeps the child view ignorant of its document context.  Since the parent provides the DOM
            // element for the child's el we need only a render() here, not any DOM manipulation.
            new jsct.StatusBar({el: this.$(".listFooter")}).render();

            // remind user when data is filtered
            this.setFilterCue();

            return this;
        },

        // If filter is active set visual cue (yellow border) to remind user they're viewing a data subset
        setFilterCue: function () {
            this.$el.toggleClass('filterActiveIndicator', jsct.application.get("filterIsActive"));
        },

        // this just updates the global message line with status info
        refresh: function () {
            if (jsct.application.get("currentState") === "list") {
                // passing empty string triggers default msg w/info on data status, appropriate for this view
                jsct.pubsub.trigger("setMsg", '');
            }
        }
    });
})(jQuery);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lavender.jsonutils</groupId>
    <artifactId>jsonutils</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jsonutils</name>
    <description>Java Library to find / apply JSON Patches according to RFC 6902</description>
    <url>https://github.com/ilavenders/jsonutils/</url>

    <scm>
        <connection>scm:git:https://github.com/ilavenders/jsonutils.git</connection>
        <developerConnection>scm:git:https://github.com/ilavenders/jsonutils.git</developerConnection>
        <tag>HEAD</tag>
        <url>https://github.com/ilavenders/jsonutils</url>
    </scm>
    <developers>
        <developer>
            <id></id>
            <name>Clarence Lawrence</name>
            <email></email>
        </developer>
    </developers>
    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <showDeprecation>true</showDeprecation>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.4</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.7</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>http://10.19.38.63:8081/nexus/content/repositories/releases/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <id>sign-artifacts</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                    <goals>deploy</goals>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <scope>test</scope>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <scope>test</scope>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>

    </dependencies>

    <distributionManagement>
        <repository>
            <id>nexus-releases</id>
            <name>ReleaseRepository</name>
            <url>http://10.19.38.63:8081/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>SnapshotRepository</name>
            <url>http://10.19.38.63:8081/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
</project>


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
Bot. Reg. 14: t. 1215. 1828

#### Original name
null

### Remarks
null


text:
<!doctype html>

    <title>Code coverage report for src/layer/tile/TileLayer.Canvas.js</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="content-language" content="en-gb">

        <link rel='stylesheet' href='../../../prettify.css'>

Code coverage report for src/layer/tile/TileLayer.Canvas.js

        Statements: 9.52% (2 / 21)

        Branches: 0% (0 / 4)

        Functions: 0% (0 / 9)

        Lines: 9.52% (2 / 21)

All files » src/layer/tile/ » TileLayer.Canvas.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

1

1

/*
 * L.TileLayer.Canvas is a class that you can use as a base for creating
 * dynamically drawn Canvas-based tile layers.
 */

L.TileLayer.Canvas = L.TileLayer.extend({
	options: {
		async: false
	},

	initialize: function (options) {
		L.setOptions(this, options);
	},

	redraw: function () {
		var tiles = this._tiles;

		for (var i in tiles) {
			if (tiles.hasOwnProperty(i)) {
				this._redrawTile(tiles[i]);
			}
		}
		return this;
	},

	_redrawTile: function (tile) {
		this.drawTile(tile, tile._tilePoint, this._map._zoom);
	},

	_createTileProto: function () {
		var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
		proto.width = proto.height = this.options.tileSize;
	},

	_createTile: function () {
		var tile = this._canvasProto.cloneNode(false);
		tile.onselectstart = tile.onmousemove = L.Util.falseFn;
		return tile;
	},

	_loadTile: function (tile, tilePoint) {
		tile._layer = this;
		tile._tilePoint = tilePoint;

		this._redrawTile(tile);

		if (!this.options.async) {
			this.tileDrawn(tile);
		}
	},

	drawTile: function (/*tile, tilePoint*/) {
		// override with rendering code
	},

	tileDrawn: function (tile) {
		this._tileOnLoad.call(tile);
	}
});

L.tileLayer.canvas = function (options) {
	return new L.TileLayer.Canvas(options);
};

Generated by istanbul at Thu Apr 04 2013 12:16:35 GMT+0300 (EEST)


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! CSS handling for the specified value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.org/css-backgrounds-3/#position

use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::fmt;
use style_traits::{ToCss, ParseError};
use values::computed::{CalcLengthOrPercentage, LengthOrPercentage as ComputedLengthOrPercentage};
use values::computed::{Context, Percentage, ToComputedValue};
use values::generics::position::Position as GenericPosition;
use values::specified::{AllowQuirks, LengthOrPercentage};
use values::specified::transform::OriginComponent;

/// The specified value of a CSS `<position>`
pub type Position = GenericPosition<HorizontalPosition, VerticalPosition>;

/// The specified value of a horizontal position.
pub type HorizontalPosition = PositionComponent<X>;

/// The specified value of a vertical position.
pub type VerticalPosition = PositionComponent<Y>;

/// The specified value of a component of a CSS `<position>`.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss)]
pub enum PositionComponent<S> {
    /// `center`
    Center,
    /// `<lop>`
    Length(LengthOrPercentage),
    /// `<side> <lop>?`
    Side(S, Option<LengthOrPercentage>),
}

define_css_keyword_enum! { X:
    "left" => Left,
    "right" => Right,
}
add_impls_for_keyword_enum!(X);

define_css_keyword_enum! { Y:
    "top" => Top,
    "bottom" => Bottom,
}
add_impls_for_keyword_enum!(Y);

impl Parse for Position {
    fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
        Self::parse_quirky(context, input, AllowQuirks::No)
    }
}

impl Position {
    /// Parses a `<position>`, with quirks.
    pub fn parse_quirky<'i, 't>(context: &ParserContext,
                                input: &mut Parser<'i, 't>,
                                allow_quirks: AllowQuirks)
                                -> Result<Self, ParseError<'i>> {
        match input.try(|i| PositionComponent::parse_quirky(context, i, allow_quirks)) {
            Ok(x_pos @ PositionComponent::Center) => {
                if let Ok(y_pos) = input.try(|i|
                    PositionComponent::parse_quirky(context, i, allow_quirks)) {
                    return Ok(Self::new(x_pos, y_pos));
                }
                let x_pos = input
                    .try(|i| PositionComponent::parse_quirky(context, i, allow_quirks))
                    .unwrap_or(x_pos);
                let y_pos = PositionComponent::Center;
                return Ok(Self::new(x_pos, y_pos));
            },
            Ok(PositionComponent::Side(x_keyword, lop)) => {
                if input.try(|i| i.expect_ident_matching("center")).is_ok() {
                    let x_pos = PositionComponent::Side(x_keyword, lop);
                    let y_pos = PositionComponent::Center;
                    return Ok(Self::new(x_pos, y_pos));
                }
                if let Ok(y_keyword) = input.try(Y::parse) {
                    let y_lop = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)).ok();
                    let x_pos = PositionComponent::Side(x_keyword, lop);
                    let y_pos = PositionComponent::Side(y_keyword, y_lop);
                    return Ok(Self::new(x_pos, y_pos));
                }
                let x_pos = PositionComponent::Side(x_keyword, None);
                let y_pos = lop.map_or(PositionComponent::Center, PositionComponent::Length);
                return Ok(Self::new(x_pos, y_pos));
            },
            Ok(x_pos @ PositionComponent::Length(_)) => {
                if let Ok(y_keyword) = input.try(Y::parse) {
                    let y_pos = PositionComponent::Side(y_keyword, None);
                    return Ok(Self::new(x_pos, y_pos));
                }
                if let Ok(y_lop) = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) {
                    let y_pos = PositionComponent::Length(y_lop);
                    return Ok(Self::new(x_pos, y_pos));
                }
                let y_pos = PositionComponent::Center;
                let _ = input.try(|i| i.expect_ident_matching("center"));
                return Ok(Self::new(x_pos, y_pos));
            },
            Err(_) => {},
        }
        let y_keyword = Y::parse(input)?;
        let lop_and_x_pos: Result<_, ParseError> = input.try(|i| {
            let y_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)).ok();
            if let Ok(x_keyword) = i.try(X::parse) {
                let x_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)).ok();
                let x_pos = PositionComponent::Side(x_keyword, x_lop);
                return Ok((y_lop, x_pos));
            };
            i.expect_ident_matching("center")?;
            let x_pos = PositionComponent::Center;
            Ok((y_lop, x_pos))
        });
        if let Ok((y_lop, x_pos)) = lop_and_x_pos {
            let y_pos = PositionComponent::Side(y_keyword, y_lop);
            return Ok(Self::new(x_pos, y_pos));
        }
        let x_pos = PositionComponent::Center;
        let y_pos = PositionComponent::Side(y_keyword, None);
        Ok(Self::new(x_pos, y_pos))
    }

    /// `center center`
    #[inline]
    pub fn center() -> Self {
        Self::new(PositionComponent::Center, PositionComponent::Center)
    }
}

impl ToCss for Position {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
        match (&self.horizontal, &self.vertical) {
            (x_pos @ &PositionComponent::Side(_, Some(_)), &PositionComponent::Length(ref y_lop)) => {
                x_pos.to_css(dest)?;
                dest.write_str(" top ")?;
                y_lop.to_css(dest)
            },
            (&PositionComponent::Length(ref x_lop), y_pos @ &PositionComponent::Side(_, Some(_))) => {
                dest.write_str("left ")?;
                x_lop.to_css(dest)?;
                dest.write_str(" ")?;
                y_pos.to_css(dest)
            },
            (x_pos, y_pos) => {
                x_pos.to_css(dest)?;
                dest.write_str(" ")?;
                y_pos.to_css(dest)
            },
        }
    }
}

impl<S: Parse> Parse for PositionComponent<S> {
    fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
        Self::parse_quirky(context, input, AllowQuirks::No)
    }
}

impl<S: Parse> PositionComponent<S> {
    /// Parses a component of a CSS position, with quirks.
    pub fn parse_quirky<'i, 't>(context: &ParserContext,
                                input: &mut Parser<'i, 't>,
                                allow_quirks: AllowQuirks)
                                -> Result<Self, ParseError<'i>> {
        if input.try(|i| i.expect_ident_matching("center")).is_ok() {
            return Ok(PositionComponent::Center);
        }
        if let Ok(lop) = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) {
            return Ok(PositionComponent::Length(lop));
        }
        let keyword = S::parse(context, input)?;
        let lop = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)).ok();
        Ok(PositionComponent::Side(keyword, lop))
    }
}

impl<S> PositionComponent<S> {
    /// `0%`
    pub fn zero() -> Self {
        PositionComponent::Length(LengthOrPercentage::Percentage(Percentage::zero()))
    }
}

impl<S: Side> ToComputedValue for PositionComponent<S> {
    type ComputedValue = ComputedLengthOrPercentage;

    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
        match *self {
            PositionComponent::Center => {
                ComputedLengthOrPercentage::Percentage(Percentage(0.5))
            },
            PositionComponent::Side(ref keyword, None) => {
                let p = Percentage(if keyword.is_start() { 0. } else { 1. });
                ComputedLengthOrPercentage::Percentage(p)
            },
            PositionComponent::Side(ref keyword, Some(ref length)) if !keyword.is_start() => {
                match length.to_computed_value(context) {
                    ComputedLengthOrPercentage::Length(length) => {
                        ComputedLengthOrPercentage::Calc(
                            CalcLengthOrPercentage::new(-length, Some(Percentage::hundred())))
                    },
                    ComputedLengthOrPercentage::Percentage(p) => {
                        ComputedLengthOrPercentage::Percentage(Percentage(1.0 - p.0))
                    },
                    ComputedLengthOrPercentage::Calc(calc) => {
                        let p = Percentage(1. - calc.percentage.map_or(0., |p| p.0));
                        let l = -calc.unclamped_length();
                        ComputedLengthOrPercentage::Calc(CalcLengthOrPercentage::new(l, Some(p)))
                    },
                }
            },
            PositionComponent::Side(_, Some(ref length)) |
            PositionComponent::Length(ref length) => {
                length.to_computed_value(context)
            },
        }
    }

    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
        PositionComponent::Length(ToComputedValue::from_computed_value(computed))
    }
}

impl<S: Side> PositionComponent<S> {
    /// The initial specified value of a position component, i.e. the start side.
    pub fn initial_specified_value() -> Self {
        PositionComponent::Side(S::start(), None)
    }
}

/// Represents a side, either horizontal or vertical, of a CSS position.
pub trait Side {
    /// Returns the start side.
    fn start() -> Self;

    /// Returns whether this side is the start side.
    fn is_start(&self) -> bool;
}

impl Side for X {
    #[inline]
    fn start() -> Self {
        X::Left
    }

    #[inline]
    fn is_start(&self) -> bool {
        *self == X::Left
    }
}

impl Side for Y {
    #[inline]
    fn start() -> Self {
        Y::Top
    }

    #[inline]
    fn is_start(&self) -> bool {
        *self == Y::Top
    }
}

/// The specified value of a legacy CSS `<position>`
/// Modern position syntax supports 3 and 4-value syntax. That means:
/// If three or four values are given, then each <percentage> or <length> represents an offset
/// and must be preceded by a keyword, which specifies from which edge the offset is given.
/// For example, `bottom 10px right 20px` represents a `10px` vertical
/// offset up from the bottom edge and a `20px` horizontal offset leftward from the right edge.
/// If three values are given, the missing offset is assumed to be zero.
/// But for some historical reasons we need to keep CSS Level 2 syntax which only supports up to
/// 2-value. This type represents this 2-value syntax.
pub type LegacyPosition = GenericPosition<LegacyHPosition, LegacyVPosition>;

/// The specified value of a horizontal position.
pub type LegacyHPosition = OriginComponent<X>;

/// The specified value of a vertical position.
pub type LegacyVPosition = OriginComponent<Y>;

impl Parse for LegacyPosition {
    fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
        Self::parse_quirky(context, input, AllowQuirks::No)
    }
}

impl LegacyPosition {
    /// Parses a `<position>`, with quirks.
    pub fn parse_quirky<'i, 't>(context: &ParserContext,
                                input: &mut Parser<'i, 't>,
                                allow_quirks: AllowQuirks)
                                -> Result<Self, ParseError<'i>> {
        match input.try(|i| OriginComponent::parse(context, i)) {
            Ok(x_pos @ OriginComponent::Center) => {
                if let Ok(y_pos) = input.try(|i|
                    OriginComponent::parse(context, i)) {
                    return Ok(Self::new(x_pos, y_pos));
                }
                let x_pos = input
                    .try(|i| OriginComponent::parse(context, i))
                    .unwrap_or(x_pos);
                let y_pos = OriginComponent::Center;
                return Ok(Self::new(x_pos, y_pos));
            },
            Ok(OriginComponent::Side(x_keyword)) => {
                if let Ok(y_keyword) = input.try(Y::parse) {
                    let x_pos = OriginComponent::Side(x_keyword);
                    let y_pos = OriginComponent::Side(y_keyword);
                    return Ok(Self::new(x_pos, y_pos));
                }
                let x_pos = OriginComponent::Side(x_keyword);
                if let Ok(y_lop) = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) {
                    return Ok(Self::new(x_pos, OriginComponent::Length(y_lop)))
                }
                let _ = input.try(|i| i.expect_ident_matching("center"));
                return Ok(Self::new(x_pos, OriginComponent::Center));
            },
            Ok(x_pos @ OriginComponent::Length(_)) => {
                if let Ok(y_keyword) = input.try(Y::parse) {
                    let y_pos = OriginComponent::Side(y_keyword);
                    return Ok(Self::new(x_pos, y_pos));
                }
                if let Ok(y_lop) = input.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks)) {
                    let y_pos = OriginComponent::Length(y_lop);
                    return Ok(Self::new(x_pos, y_pos));
                }
                let _ = input.try(|i| i.expect_ident_matching("center"));
                return Ok(Self::new(x_pos, OriginComponent::Center));
            },
            Err(_) => {},
        }
        let y_keyword = Y::parse(input)?;
        let x_pos: Result<_, ParseError> = input.try(|i| {
            if let Ok(x_keyword) = i.try(X::parse) {
                let x_pos = OriginComponent::Side(x_keyword);
                return Ok(x_pos);
            }
            i.expect_ident_matching("center")?;
            Ok(OriginComponent::Center)
        });
        if let Ok(x_pos) = x_pos {
            let y_pos = OriginComponent::Side(y_keyword);
            return Ok(Self::new(x_pos, y_pos));
        }
        let x_pos = OriginComponent::Center;
        let y_pos = OriginComponent::Side(y_keyword);
        Ok(Self::new(x_pos, y_pos))
    }

    /// `center center`
    #[inline]
    pub fn center() -> Self {
        Self::new(OriginComponent::Center, OriginComponent::Center)
    }
}

impl ToCss for LegacyPosition {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
        self.horizontal.to_css(dest)?;
        dest.write_str(" ")?;
        self.vertical.to_css(dest)
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="HiPay_FullserviceMagento::css/hipay.css"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="HiPay\FullserviceMagento\Block\Redirect\Pending" name="redirect.pending" template="redirect/pending.phtml" cacheable="false" />
        </referenceContainer>
    </body>
</page>


text:
class StaticPagesController < ApplicationController
  def home
  end

  def background
  end

  def criteria
  end
end


text:
<?php
/*\
 | ------------------------------------------------------
 | @file : Resolver.php
 | @author : Fabien Beaujean
 | @description : Trait path resolver
 | @version : 3.0
 | ------------------------------------------------------
\*/

namespace Gcs\Framework\Core\General;

use Gcs\Framework\Core\Config\Config;
use Gcs\Framework\Core\Exception\MissingConfigException;
use Gcs\Framework\Core\Http\Request\Request;

trait Resolver {

    /**
     * when you want to use an image, file only, this method is used to resolve the right path
     * the method override resolve()
     * @access public
     * @param $type string : type of the config
     * @param $data string : ".gcs/template/" "template"
     * @param $php  boolean : because method return path, the framework wants to know if you want the html path or the php path
     * @return string
     * @since 3.0
     * @package Gcs\Framework\Core\General
     */

    protected function path($type, $data = '', $php = false) {
        if ($php == true) {
            return $this->resolve($type, $data);
        }
        else {
            return Config::config()['user']['framework']['folder'] . $this->resolve($type, $data);
        }
    }

    /**
     * when you want to use a lang, route, image, template, this method is used to resolve the right path
     * the method use the instance of \Gcs\Framework\Core\Config\Config
     * @access public
     * @param $type string : type of the config
     * @param $data string : ".Gcs.lang" ".Gcs/template/" "template"
     * @throws MissingConfigException
     * @return mixed
     * @since 3.0
     * @package Gcs\Framework\Core\General
     */

    protected function resolve($type, $data) {
        return self::resolveStatic($type, $data);
    }

    /**
     * when you want to use a lang, route, image, template, this method is used to resolve the right path
     * the method use the instance of \Gcs\Framework\Core\Config\Config
     * @access public
     * @param $type string : type of the config
     * @param $data string : ".gcs.lang" ".gcs/template/" "template"
     * @throws MissingConfigException
     * @return mixed
     * @since 3.0
     * @package Gcs\Framework\Core\General
     */

    protected static function resolveStatic($type, $data) {
        $request = Request::instance();
        $config = Config::instance();

        if ($type == RESOLVE_ROUTE || $type == RESOLVE_LANG) {
            if (preg_match('#^((\.)([a-zA-Z0-9_-]+)(\.)(.+))#', $data, $matches)) {
                $src = $matches[3];
                $data = preg_replace('#^(\.)(' . preg_quote($src) . ')(\.)#isU', '', $data);
            }
            else {
                $src = $request->src;
            }

            return [$config->config[$type][$src], $data];
        }
        else {
            if (preg_match('#^((\.)([^(\/)]+)([(\/)]*)(.*))#', $data, $matches)) {
                $src = $matches[3];
                $data = $matches[5];
            }
            else {
                if ($request->src != '') {
                    $src = $request->src;
                }
                else {
                    $src = 'app';
                }
            }

            if ($src == 'vendor') {
                return VENDOR_PATH . $data;
            }
            else {
                if (!isset($config->config[$type][$src])) {
                    throw new MissingConfigException('The section "' . $type . '/' . $src . '" does not exist in configuration');
                }
            }

            return $config->config[$type][$src] . $data;
        }
    }
}