text:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$suit = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")

. $here.Replace("\spec\ps_specs", "\ChefExtensionHandler\bin\$suit")

describe "#Read-JsonFile" {
  it "returns correct values " {
    $handlerSettingsFileName = "testhandlerSettingsFileName"
    mock Get-HandlerSettingsFileName {return $handlerSettingsFileName}
    $handlerSettings = @{"protectedSettings" = "testprotectedSettings"; "protectedSettingsCertThumbprint" = "testprotectedSettingsCertThumbprint"; "publicSettings" = @{"client_rb"= "testclientrb"; "runList" = "testrunlist"}}
    $handlerEnvironment = @{"logFolder" = "testlogFolder"; "statusFolder" = "teststatusFolder"; "heartbeatFile" = "testheartbeatFile" }
    mock Get-HandlerSettings {return $handlerSettings}
    mock Get-HandlerEnvironment {return $handlerEnvironment}

    $json_handlerSettingsFileName, $json_statusFolder = Read-JsonFile

    $json_handlerSettingsFileName | Should Be $handlerSettingsFileName
    $json_statusFolder | Should Be $handlerEnvironment.statusFolder
  }
}

describe "#Read-JsonFileUsingRuby" {
  it "returns correct values" {
    $handlerSettingsFilePath = "testhandlerSettingsFilePath"
    mock Get-HandlerSettingsFilePath { return $handlerSettingsFilePath }

    $handlerEnvironmentFilePath = "testhandlerEnvironmentFilePath"
    mock Get-HandlerEnvironmentFilePath { return $handlerEnvironmentFilePath }

    $handlerEnvironment = @{"logFolder" = "testlogFolder"; "statusFolder" = "teststatusFolder"; "heartbeatFile" = "testheartbeatFile" }

    mock Get-JsonValueUsingRuby {return $handlerEnvironment.statusFolder } -ParameterFilter { $json_handlerEnvironmentFileName -eq $handlerEnvironmentFilePath -and $args[0] -eq "handlerEnvironment" -and $args[1] -eq "statusFolder" }

    $json_handlerSettingsFileName, $json_statusFolder = Read-JsonFileUsingRuby

    $json_handlerSettingsFileName | Should Be $handlerSettingsFilePath
    $json_statusFolder | Should Be $handlerEnvironment.statusFolder
  }
}

describe "#Get-HandlerSettings" {
  it "returns handlerSettings" {
    mock Get-HandlerSettingsFileName
    $runtimeSettingsJson = @{"runtimeSettings" = @(@{"handlerSettings" = "testhandlerSettings"})}
    mock Read-JsonFromFile { return $runtimeSettingsJson}

    $handlerSettings = Get-HandlerSettings
    $handlerSettings | Should Be $runtimeSettingsJson.runtimeSettings[0].handlerSettings
    Assert-MockCalled  Get-HandlerSettingsFileName -Times 1
  }
}

describe "#Write-ChefStatus" {
  it "write status to file" {
    # PS 2.0 not supports ConvertTo-Json. Added this empty function for PS 2.0, So test can run on PS 2.0 as well.
    function ConvertTo-Json {}

    $json_handlerSettingsFileName = "0.settings"
    $json_statusFolder = $env:tmp
    $testStatusFile = "$json_statusFolder\\0.status"
    mock Get-PowershellVersion {return 3}
    mock ConvertTo-Json {return @{ "version"="1.0";"timestampUTC"="2014-04-23T04:03:54Z"; "status" = "teststatus"}}
    mock Get-Date {return "2014-04-23T09:41:13Z"}
    mock Out-File
    $operation = "installing-chef"
    $statusType = "transitioning"
    $message = "installing Chef"
    Write-ChefStatus ($operation, $statusType, $message)
    Assert-MockCalled ConvertTo-Json -Times 1
    Assert-MockCalled Get-Date -Times 1
    Assert-MockCalled Out-File -Times 1 -ParameterFilter { $filePath -eq $testStatusFile }
  }
}

describe "#Update-ChefExtensionRegistry" {
  context "when registry entry exists" {
    it "Update the value" {
      $testPath = "HKLM:\Software\Chef\AzureExtension"
      $testvalue = "X"
      mock Test-Path {return $true }
      mock New-Item
      mock New-ItemProperty
      mock Get-ItemProperty {return @{"Status" = "Update"}}

      Update-ChefExtensionRegistry $testvalue

      Assert-MockCalled New-Item -Times 0
      Assert-MockCalled Test-Path -Times 1 -ParameterFilter {$Path -eq $testPath -and $PathType -eq "Container"}
      Assert-MockCalled New-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath -and $Name -eq "Status" -and $Value -eq $testvalue}
      Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath}
    }
  }

  context "when registry entry not exists" {
    it "Add new registry entry" {
      $testPath = "HKLM:\Software\Chef\AzureExtension"
      $testvalue = "X"
      mock Test-Path {return $false }
      mock New-Item
      mock New-ItemProperty
      mock Get-ItemProperty {return @{"Status" = "Update"}}

      Update-ChefExtensionRegistry $testvalue

      Assert-MockCalled New-Item -Times 1 -ParameterFilter {$Path -eq $testPath -and $Name -eq "Status" -and $Value -eq $testvalue}
      Assert-MockCalled Test-Path -Times 1 -ParameterFilter {$Path -eq $testPath -and $PathType -eq "Container"}
      Assert-MockCalled New-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath -and $Name -eq "Status" -and $Value -eq $testvalue}
      Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath}
    }
  }
}

describe "#Test-ChefExtensionRegistry" {
  context "when registry entry exists" {
    it "return true" {
      $testPath = "HKLM:\Software\Chef\AzureExtension"
      $testvalue = "updated"
      $testName = "Status"

      mock Test-Path {return $true }
      mock Get-ItemProperty {return @{"Status" = "updated"}}

      $result = Test-ChefExtensionRegistry

      $result | Should Be $true
      Assert-MockCalled Test-Path -Times 1 -ParameterFilter {$Path -eq $testPath -and $PathType -eq "Container"}
      Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath}
    }
  }

  context "when registry entry not exists" {
    it "return false" {
      $testPath = "HKLM:\Software\Chef\AzureExtension"
      $testvalue = "updated"
      $testName = "Status"

      mock Test-Path {return $false }
      mock Get-ItemProperty {return @{"Status" = "updated"}}

      $result = Test-ChefExtensionRegistry

      $result | Should Be $false
      Assert-MockCalled Test-Path -Times 1 -ParameterFilter {$Path -eq $testPath -and $PathType -eq "Container"}
      Assert-MockCalled Get-ItemProperty -Times 0
    }
  }

  context "when registry entry exists and its status value not updated" {
    it "return false" {
      $testPath = "HKLM:\Software\Chef\AzureExtension"
      $testvalue = "updated"
      $testName = "Status"

      mock Test-Path {return $true }
      mock Get-ItemProperty {return @{"Status" = ""}}

      $result = Test-ChefExtensionRegistry

      $result | Should Be $false
      Assert-MockCalled Test-Path -Times 1 -ParameterFilter {$Path -eq $testPath -and $PathType -eq "Container"}
      Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter {$Path -eq $testPath}
    }
  }
}

describe "#Get-deleteChefConfigSetting" {
  context "when deleteChefConfig is set to false and powershell version is 3 and call from update is false" {
    it "returns deleteChefConfig false " {
      mock Get-PowershellVersion { return 3 }
      $calledFromUpdate = false

      $json_handlerSettings = @{"protectedSettings" = "testprotectedSettings"; "protectedSettingsCertThumbprint" = "testprotectedSettingsCertThumbprint"; "publicSettings" = @{"client_rb"= "testclientrb"; "runList" = "testrunlist"; "deleteChefConfig" = "false"}}
      mock Get-HandlerSettings {return $json_handlerSettings}

      $result = Get-deleteChefConfigSetting

      $result | Should Be "false"

      Assert-MockCalled Get-HandlerSettings -Times 1
    }
  }

  context "when deleteChefConfig is set to true and powershell version is 3 and call from update is false" {
    it "returns deleteChefConfig true " {
      mock Get-PowershellVersion { return 3 }
      $calledFromUpdate = false

      $json_handlerSettings = @{"protectedSettings" = "testprotectedSettings"; "protectedSettingsCertThumbprint" = "testprotectedSettingsCertThumbprint"; "publicSettings" = @{"client_rb"= "testclientrb"; "runList" = "testrunlist"; "deleteChefConfig" = "true"}}
      mock Get-HandlerSettings {return $json_handlerSettings}

      $result = Get-deleteChefConfigSetting

      $result | Should Be "true"

      Assert-MockCalled Get-HandlerSettings -Times 1
    }
  }
}


text:
ActiveAdmin.register Staff do

  # See permitted parameters documentation:
  # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
  #
  # permit_params :list, :of, :attributes, :on, :model
  #
  # or
  #
  menu parent: "Blog"
  permit_params do
    permitted = [:email, :password]
    #permitted << :other if current_user.admin?
    permitted
  end

end

redpajama_set_name: RedPajamaGithub


text:
# run

    Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

    Run a command in a new container

      -a, --attach=[]            Attach to STDIN, STDOUT or STDERR
      --add-host=[]              Add a custom host-to-IP mapping (host:ip)
      --blkio-weight=0           Block IO weight (relative weight)
      -c, --cpu-shares=0         CPU shares (relative weight)
      --cap-add=[]               Add Linux capabilities
      --cap-drop=[]              Drop Linux capabilities
      --cidfile=""               Write the container ID to the file
      --cpuset-cpus=""           CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems=""           Memory nodes (MEMs) in which to allow execution (0-3, 0,1)
      --cpu-period=0             Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota=0              Limit the CPU CFS (Completely Fair Scheduler) quota
      -d, --detach=false         Run container in background and print container ID
      --device=[]                Add a host device to the container
      --dns=[]                   Set custom DNS servers
      --dns-search=[]            Set custom DNS search domains
      -e, --env=[]               Set environment variables
      --entrypoint=""            Overwrite the default ENTRYPOINT of the image
      --env-file=[]              Read in a file of environment variables
      --expose=[]                Expose a port or a range of ports
      -h, --hostname=""          Container host name
      --help=false               Print usage
      -i, --interactive=false    Keep STDIN open even if not attached
      --ipc=""                   IPC namespace to use
      --link=[]                  Add link to another container
      --log-driver=""            Logging driver for container
      --log-opt=[]               Log driver specific options
      --lxc-conf=[]              Add custom lxc options
      -m, --memory=""            Memory limit
      -l, --label=[]             Set metadata on the container (e.g., --label=com.example.key=value)
      --label-file=[]            Read in a file of labels (EOL delimited)
      --mac-address=""           Container MAC address (e.g. 92:d0:c6:0a:29:33)
      --memory-swap=""           Total memory (memory + swap), '-1' to disable swap
      --name=""                  Assign a name to the container
      --net="bridge"             Set the Network mode for the container
      --oom-kill-disable=false   Whether to disable OOM Killer for the container or not
      -P, --publish-all=false    Publish all exposed ports to random ports
      -p, --publish=[]           Publish a container's port(s) to the host
      --pid=""                   PID namespace to use
      --uts=""                   UTS namespace to use
      --privileged=false         Give extended privileges to this container
      --read-only=false          Mount the container's root filesystem as read only
      --restart="no"             Restart policy (no, on-failure[:max-retry], always)
      --rm=false                 Automatically remove the container when it exits
      --security-opt=[]          Security Options
      --sig-proxy=true           Proxy received signals to the process
      -t, --tty=false            Allocate a pseudo-TTY
      -u, --user=""              Username or UID (format: <name|uid>[:<group|gid>])
      -v, --volume=[]            Bind mount a volume
      --volumes-from=[]          Mount volumes from the specified container(s)
      -w, --workdir=""           Working directory inside the container

The `docker run` command first `creates` a writeable container layer over the
specified image, and then `starts` it using the specified command. That is,
`docker run` is equivalent to the API `/containers/create` then
`/containers/(id)/start`. A stopped container can be restarted with all its
previous changes intact using `docker start`. See `docker ps -a` to view a list
of all containers.

There is detailed information about `docker run` in the [Docker run reference](
/reference/run/).

The `docker run` command can be used in combination with `docker commit` to
[*change the command that a container runs*](#commit-an-existing-container).

See the [Docker User Guide](/userguide/dockerlinks/) for more detailed
information about the `--expose`, `-p`, `-P` and `--link` parameters,
and linking containers.

## Examples

    $ docker run --name test -it debian
    $$ exit 13
    exit
    $ echo $?
    13
    $ docker ps -a | grep test
    275c44472aeb        debian:7            "/bin/bash"         26 seconds ago      Exited (13) 17 seconds ago                         test

In this example, we are running `bash` interactively in the `debian:latest` image, and giving
the container the name `test`. We then quit `bash` by running `exit 13`, which means `bash`
will have an exit code of `13`. This is then passed on to the caller of `docker run`, and
is recorded in the `test` container metadata.

    $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"

This will create a container and print `test` to the console. The `cidfile`
flag makes Docker attempt to create a new file and write the container ID to it.
If the file exists already, Docker will return an error. Docker will close this
file when `docker run` exits.

    $ docker run -t -i --rm ubuntu bash
    root@bc338942ef20:/# mount -t tmpfs none /mnt
    mount: permission denied

This will *not* work, because by default, most potentially dangerous kernel
capabilities are dropped; including `cap_sys_admin` (which is required to mount
filesystems). However, the `--privileged` flag will allow it to run:

    $ docker run --privileged ubuntu bash
    root@50e3f57e16e6:/# mount -t tmpfs none /mnt
    root@50e3f57e16e6:/# df -h
    Filesystem      Size  Used Avail Use% Mounted on
    none            1.9G     0  1.9G   0% /mnt

The `--privileged` flag gives *all* capabilities to the container, and it also
lifts all the limitations enforced by the `device` cgroup controller. In other
words, the container can then do almost everything that the host can do. This
flag exists to allow special use-cases, like running Docker within Docker.

    $ docker  run -w /path/to/dir/ -i -t  ubuntu pwd

The `-w` lets the command being executed inside directory given, here
`/path/to/dir/`. If the path does not exists it is created inside the container.

    $ docker  run  -v `pwd`:`pwd` -w `pwd` -i -t  ubuntu pwd

The `-v` flag mounts the current working directory into the container. The `-w`
lets the command being executed inside the current working directory, by
changing into the directory to the value returned by `pwd`. So this
combination executes the command using the container, but inside the
current working directory.

    $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash

When the host directory of a bind-mounted volume doesn't exist, Docker
will automatically create this directory on the host for you. In the
example above, Docker will create the `/doesnt/exist`
folder before starting your container.

    $ docker run --read-only -v /icanwrite busybox touch /icanwrite here

Volumes can be used in combination with `--read-only` to control where
a container writes files. The `--read-only` flag mounts the container's root
filesystem as read only prohibiting writes to locations other than the
specified volumes for the container.

    $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v ./static-docker:/usr/bin/docker busybox sh

By bind-mounting the docker unix socket and statically linked docker
binary (such as that provided by [https://get.docker.com](
https://get.docker.com)), you give the container the full access to create and
manipulate the host's Docker daemon.

    $ docker run -p 127.0.0.1:80:8080 ubuntu bash

This binds port `8080` of the container to port `80` on `127.0.0.1` of
the host machine. The [Docker User Guide](/userguide/dockerlinks/)
explains in detail how to manipulate ports in Docker.

    $ docker run --expose 80 ubuntu bash

This exposes port `80` of the container for use within a link without
publishing the port to the host system's interfaces. The [Docker User
Guide](/userguide/dockerlinks) explains in detail how to manipulate
ports in Docker.

    $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash

This sets environmental variables in the container. For illustration all three
flags are shown here. Where `-e`, `--env` take an environment variable and
value, or if no `=` is provided, then that variable's current value is passed
through (i.e. `$MYVAR1` from the host is set to `$MYVAR1` in the container).
When no `=` is provided and that variable is not defined in the client's
environment then that variable will be removed from the container's list of
environment variables.
All three flags, `-e`, `--env` and `--env-file` can be repeated.

Regardless of the order of these three flags, the `--env-file` are processed
first, and then `-e`, `--env` flags. This way, the `-e` or `--env` will
override variables as needed.

    $ cat ./env.list
    TEST_FOO=BAR
    $ docker run --env TEST_FOO="This is a test" --env-file ./env.list busybox env | grep TEST_FOO
    TEST_FOO=This is a test

The `--env-file` flag takes a filename as an argument and expects each line
to be in the `VAR=VAL` format, mimicking the argument passed to `--env`. Comment
lines need only be prefixed with `#`

An example of a file passed with `--env-file`

    $ cat ./env.list
    TEST_FOO=BAR

    # this is a comment
    TEST_APP_DEST_HOST=10.10.0.127
    TEST_APP_DEST_PORT=8888

    # pass through this variable from the caller
    TEST_PASSTHROUGH
    $ sudo TEST_PASSTHROUGH=howdy docker run --env-file ./env.list busybox env
    HOME=/
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    HOSTNAME=5198e0745561
    TEST_FOO=BAR
    TEST_APP_DEST_HOST=10.10.0.127
    TEST_APP_DEST_PORT=8888
    TEST_PASSTHROUGH=howdy

    $ docker run --name console -t -i ubuntu bash

A label is a a `key=value` pair that applies metadata to a container. To label a container with two labels:

    $ docker run -l my-label --label com.example.foo=bar ubuntu bash

The `my-label` key doesn't specify a value so the label defaults to an empty
string(`""`). To add multiple labels, repeat the label flag (`-l` or `--label`).

The `key=value` must be unique to avoid overwriting the label value. If you
specify labels with identical keys but different values, each subsequent value
overwrites the previous. Docker uses the last `key=value` you supply.

Use the `--label-file` flag to load multiple labels from a file. Delimit each
label in the file with an EOL mark. The example below loads labels from a
labels file in the current directory:

    $ docker run --label-file ./labels ubuntu bash

The label-file format is similar to the format for loading environment
variables. (Unlike environment variables, labels are not visible to processes
running inside a container.) The following example illustrates a label-file
format:

    com.example.label1="a label"

    # this is a comment
    com.example.label2=another\ label
    com.example.label3

You can load multiple label-files by supplying multiple  `--label-file` flags.

For additional information on working with labels, see [*Labels - custom
metadata in Docker*](/userguide/labels-custom-metadata/) in the Docker User
Guide.

    $ docker run --link /redis:redis --name console ubuntu bash

The `--link` flag will link the container named `/redis` into the newly
created container with the alias `redis`. The new container can access the
network and environment of the `redis` container via environment variables.
The `--link` flag will also just accept the form `<name or id>` in which case
the alias will match the name. For instance, you could have written the previous
example as:

    $ docker run --link redis --name console ubuntu bash

The `--name` flag will assign the name `console` to the newly created
container.

    $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd

The `--volumes-from` flag mounts all the defined volumes from the referenced
containers. Containers can be specified by repetitions of the `--volumes-from`
argument. The container ID may be optionally suffixed with `:ro` or `:rw` to
mount the volumes in read-only or read-write mode, respectively. By default,
the volumes are mounted in the same mode (read write or read only) as
the reference container.

Labeling systems like SELinux require that proper labels are placed on volume
content mounted into a container. Without a label, the security system might
prevent the processes running inside the container from using the content. By
default, Docker does not change the labels set by the OS.

To change the label in the container context, you can add either of two suffixes
`:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file
objects on the shared volumes. The `z` option tells Docker that two containers
share the volume content. As a result, Docker labels the content with a shared
content label. Shared volume labels allow all containers to read/write content.
The `Z` option tells Docker to label the content with a private unshared label.
Only the current container can use a private volume.

The `-a` flag tells `docker run` to bind to the container's `STDIN`, `STDOUT`
or `STDERR`. This makes it possible to manipulate the output and input as
needed.

    $ echo "test" | docker run -i -a stdin ubuntu cat -

This pipes data into a container and prints the container's ID by attaching
only to the container's `STDIN`.

    $ docker run -a stderr ubuntu echo test

This isn't going to print anything unless there's an error because we've
only attached to the `STDERR` of the container. The container's logs
still store what's been written to `STDERR` and `STDOUT`.

    $ cat somefile | docker run -i -a stdin mybuilder dobuild

This is how piping a file into a container could be done for a build.
The container's ID will be printed after the build is done and the build
logs could be retrieved using `docker logs`. This is
useful if you need to pipe a file or something else into a container and
retrieve the container's ID once the container has finished running.

    $ docker run --device=/dev/sdc:/dev/xvdc --device=/dev/sdd --device=/dev/zero:/dev/nulo -i -t ubuntu ls -l /dev/{xvdc,sdd,nulo}
    brw-rw---- 1 root disk 8, 2 Feb  9 16:05 /dev/xvdc
    brw-rw---- 1 root disk 8, 3 Feb  9 16:05 /dev/sdd
    crw-rw-rw- 1 root root 1, 5 Feb  9 16:05 /dev/nulo

It is often necessary to directly expose devices to a container. The `--device`
option enables that. For example, a specific block storage device or loop
device or audio device can be added to an otherwise unprivileged container
(without the `--privileged` flag) and have the application directly access it.

By default, the container will be able to `read`, `write` and `mknod` these devices.
This can be overridden using a third `:rwm` set of options to each `--device`
flag:

    $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdc

    Command (m for help): q
    $ docker run --device=/dev/sda:/dev/xvdc:ro --rm -it ubuntu fdisk  /dev/xvdc
    You will not be able to write the partition table.

    Command (m for help): q

    $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk  /dev/xvdc

    Command (m for help): q

    $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk  /dev/xvdc
    fdisk: unable to open /dev/xvdc: Operation not permitted

> **Note:**
> `--device` cannot be safely used with ephemeral devices. Block devices
> that may be removed should not be added to untrusted containers with
> `--device`.

**A complete example:**

    $ docker run -d --name static static-web-files sh
    $ docker run -d --expose=8098 --name riak riakserver
    $ docker run -d -m 100m -e DEVELOPMENT=1 -e BRANCH=example-code -v $(pwd):/app/bin:ro --name app appserver
    $ docker run -d -p 1443:443 --dns=10.0.0.1 --dns-search=dev.org -v /var/log/httpd --volumes-from static --link riak --link app -h www.sven.dev.org --name web webserver
    $ docker run -t -i --rm --volumes-from web -w /var/log/httpd busybox tail -f access.log

This example shows five containers that might be set up to test a web
application change:

1. Start a pre-prepared volume image `static-web-files` (in the background)
   that has CSS, image and static HTML in it, (with a `VOLUME` instruction in
   the Dockerfile to allow the web server to use those files);
2. Start a pre-prepared `riakserver` image, give the container name `riak` and
   expose port `8098` to any containers that link to it;
3. Start the `appserver` image, restricting its memory usage to 100MB, setting
   two environment variables `DEVELOPMENT` and `BRANCH` and bind-mounting the
   current directory (`$(pwd)`) in the container in read-only mode as `/app/bin`;
4. Start the `webserver`, mapping port `443` in the container to port `1443` on
   the Docker server, setting the DNS server to `10.0.0.1` and DNS search
   domain to `dev.org`, creating a volume to put the log files into (so we can
   access it from another container), then importing the files from the volume
   exposed by the `static` container, and linking to all exposed ports from
   `riak` and `app`. Lastly, we set the hostname to `web.sven.dev.org` so its
   consistent with the pre-generated SSL certificate;
5. Finally, we create a container that runs `tail -f access.log` using the logs
   volume from the `web` container, setting the workdir to `/var/log/httpd`. The
   `--rm` option means that when the container exits, the container's layer is
   removed.

## Restart policies

Use Docker's `--restart` to specify a container's *restart policy*. A restart
policy controls whether the Docker daemon restarts a container after exit.
Docker supports the following restart policies:

      Policy
      Result

      no

        Do not automatically restart the container when it exits. This is the
        default.

          on-failure[:max-retries]

        Restart only if the container exits with a non-zero exit status.
        Optionally, limit the number of restart retries the Docker
        daemon attempts.

      always

        Always restart the container regardless of the exit status.
        When you specify always, the Docker daemon will try to restart
        the container indefinitely.

    $ docker run --restart=always redis

This will run the `redis` container with a restart policy of **always**
so that if the container exits, Docker will restart it.

More detailed information on restart policies can be found in the
[Restart Policies (--restart)](/reference/run/#restart-policies-restart)
section of the Docker run reference page.

## Adding entries to a container hosts file

You can add other hosts into a container's `/etc/hosts` file by using one or
more `--add-host` flags. This example adds a static address for a host named
`docker`:

    $ docker run --add-host=docker:10.180.0.1 --rm -it debian
    $$ ping docker
    PING docker (10.180.0.1): 48 data bytes
    56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms
    56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms
    ^C--- docker ping statistics ---
    2 packets transmitted, 2 packets received, 0% packet loss
    round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms

Sometimes you need to connect to the Docker host from within your
container. To enable this, pass the Docker host's IP address to
the container using the `--add-host` flag. To find the host's address,
use the `ip addr show` command.

The flags you pass to `ip addr show` depend on whether you are
using IPv4 or IPv6 networking in your containers. Use the following
flags for IPv4 address retrieval for a network device named `eth0`:

    $ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1`
    $ docker run  --add-host=docker:${HOSTIP} --rm -it debian

For IPv6 use the `-6` flag instead of the `-4` flag. For other network
devices, replace `eth0` with the correct device name (for example `docker0`
for the bridge device).

### Setting ulimits in a container

Since setting `ulimit` settings in a container requires extra privileges not
available in the default container, you can set these using the `--ulimit` flag.
`--ulimit` is specified with a soft and hard limit as such:
`<type>=<soft limit>[:<hard limit>]`, for example:

    $ docker run --ulimit nofile=1024:1024 --rm debian ulimit -n
    1024

> **Note:**
> If you do not provide a `hard limit`, the `soft limit` will be used
> for both values. If no `ulimits` are set, they will be inherited from
> the default `ulimits` set on the daemon.  `as` option is disabled now.
> In other words, the following script is not supported:
> `$ docker run -it --ulimit as=1024 fedora /bin/bash`

The values are sent to the appropriate `syscall` as they are set.
Docker doesn't perform any byte conversion. Take this into account when setting the values.


text:
import superagent from 'superagent';
import config from '../config';
import cookie from 'react-cookie';

const methods = ['get', 'post', 'put', 'patch', 'del'];

export function formatUrl(path) {
  const adjustedPath = path[0] !== '/' ? `/${path}` : path;

  if (__SERVER__) {
    // Prepend host and port of the API server to the path.
    // return 'http://' + config.apiHost + ':' + config.apiPort + adjustedPath;
    return `${config.apiHost}:${config.apiPort}${adjustedPath}`;
  }
  // Prepend `/api` to relative URL, to proxy to API server.
  return `/api${adjustedPath}`;
}

export function getClientCookie() {
  return cookie.load('authToken', { path: '/' });
}

export default class ApiClient {
  constructor(req) {
    methods.forEach((method) =>
      this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {

        const request = superagent[method](formatUrl(path));

        const authToken = (__SERVER__) ? req.cookies.authToken : getClientCookie();

        console.log('authToken', authToken)

        if (params) {
          request.query(params);
        }

        if (authToken && path !== '/signin' && path !== '/signup') {
          request.set('Authorization', `Bearer ${authToken}`);
        }

        if (data) {
          request.send(data);
        }

        request.end((err, { body } = {}) => {
          if (err) {
            console.log("ERRORRR", err)
            reject(body || err);
          } else {
            console.log("PASH", path)
            if (path === '/token/validate' && authToken) {
              console.log("IFFFFFF")
              resolve(authToken);
            } else {
              resolve(body);
            }
          }
        });
      }));
  }
  /*
   * There's a V8 bug where, when using Babel, exporting classes with only
   * constructors sometimes fails. Until it's patched, this is a solution to
   * "ApiClient is not defined" from issue #14.
   * https://github.com/erikras/react-redux-universal-hot-example/issues/14
   *
   * Relevant Babel bug (but they claim it's V8): https://phabricator.babeljs.io/T2455
   *
   * Remove it at your own risk.
   */
  empty() {}
}


text:
import {createUseStyles} from 'react-jss';

// TODO(alanorozco): Share these across components.
export const fillStretch = {
  'position': 'relative',
  'width': '100%',
  'height': '100%',
};

export const fillContentOverlay = {
  'position': 'absolute',
  'left': 0,
  'right': 0,
  'bottom': 0,
  'top': 0,
};

const JSS = {
  fillStretch,
  fillContentOverlay,
};

// useStyles gets replaced for AMP builds via `babel-plugin-transform-jss`.
// eslint-disable-next-line local/no-export-side-effect
export const useStyles = createUseStyles(JSS);


text:
"""Command-line configuration utilities."""

import logging
import os
import optparse

from kasko.process import ImportSelenium

_LOGGER = logging.getLogger(os.path.basename(__file__))

def GenerateOptionParser():
  """Generates a default OptionParser."""

  """Parses the command-line and returns an options structure."""
  self_dir = os.path.dirname(__file__)
  src_dir = os.path.abspath(os.path.join(self_dir, '..', '..', '..', '..',
                                         '..'))

  option_parser = optparse.OptionParser()
  option_parser.add_option('--chrome', dest='chrome', type='string',
      default=os.path.join(src_dir, 'out', 'Release', 'chrome.exe'),
      help='Path to chrome.exe. Defaults to $SRC/out/Release/chrome.exe')
  option_parser.add_option('--chromedriver', dest='chromedriver',
      type='string', help='Path to the chromedriver.exe. By default will look '
      'alongside chrome.exe.')
  option_parser.add_option('--keep-temp-dirs', action='store_true',
      default=False, help='Prevents temporary directories from being deleted.')
  option_parser.add_option('--quiet', dest='log_level', action='store_const',
      default=logging.INFO, const=logging.ERROR,
      help='Disables all output except for errors.')
  option_parser.add_option('--user-data-dir', dest='user_data_dir',
      type='string', help='User data directory to use. Defaults to using a '
      'temporary one.')
  option_parser.add_option('--verbose', dest='log_level', action='store_const',
      default=logging.INFO, const=logging.DEBUG,
      help='Enables verbose logging.')
  option_parser.add_option('--webdriver', type='string',
      default=os.path.join(src_dir, 'third_party', 'webdriver', 'pylib'),
      help='Specifies the directory where the python installation of webdriver '
           '(selenium) can be found. Specify an empty string to use the system '
           'installation. Defaults to $SRC/third_party/webdriver/pylib')

  return option_parser

def ParseCommandLine(option_parser=None):
  if not option_parser:
    option_parser = GenerateOptionParser()

  options, args = option_parser.parse_args()
  if args:
    option_parser.error('Unexpected arguments: %s' % args)

  # Validate chrome.exe exists.
  if not os.path.isfile(options.chrome):
    option_parser.error('chrome.exe not found')

  # Use default chromedriver.exe if necessary, and validate it exists.
  if not options.chromedriver:
    options.chromedriver = os.path.join(os.path.dirname(options.chrome),
                                        'chromedriver.exe')
  if not os.path.isfile(options.chromedriver):
    option_parser.error('chromedriver.exe not found')

  # If specified, ensure the webdriver parameters is a directory.
  if options.webdriver and not os.path.isdir(options.webdriver):
    option_parser.error('Invalid webdriver directory.')

  # Configure logging.
  logging.basicConfig(level=options.log_level)

  _LOGGER.debug('Using chrome path: %s', options.chrome)
  _LOGGER.debug('Using chromedriver path: %s', options.chromedriver)
  _LOGGER.debug('Using webdriver path: %s', options.webdriver)

  # Import webdriver and selenium.
  ImportSelenium(options.webdriver)

  return options


text:
require.config({
	// The shim config allows us to configure dependencies for
	// scripts that do not call define() to register a module
	shim: {
		underscore: {
			exports: '_'
		},
		backbone: {
			deps: [
				'underscore',
				'jquery'
			],
			exports: 'Backbone'
		},
		backboneLocalstorage: {
			deps: ['backbone'],
			exports: 'Store'
		}
	},
	paths: {
		jquery: 'lib/jquery',
		underscore: 'lib/underscore',
		backbone: 'lib/backbone/backbone',
		backboneLocalstorage: 'lib/backbone/backbone.localStorage',
		text: 'lib/require/text',
        tplin: 'lib/require/tplin'
	}
});

require([
	'views/app',
	'routers/router'
], function( AppView, Workspace ) {
	// Initialize routing and start Backbone.history()
	new Workspace();
	Backbone.history.start();

	// Initialize the application view
	new AppView();
});


text: require('../lib/cli').run(process.argv.slice(2));


text:
#nullable disable
using System;
using PasPasPas.Globals.Runtime;
using PasPasPas.Globals.Types;

namespace PasPasPas.Typings.Operators {

    /// <summary>
    ///     string operators
    /// </summary>
    public class StringOperator : OperatorBase {

        private static void Register(ITypeRegistry registry, OperatorKind kind)
            => registry.RegisterOperator(new StringOperator(kind, 2));

        /// <summary>
        ///     register known operators
        /// </summary>
        /// <param name="typeRegistry">type registry</param>
        public static void RegisterOperators(ITypeRegistry typeRegistry)
            => Register(typeRegistry, OperatorKind.ConcatOperator);

        /// <summary>
        ///     create a new string operator
        /// </summary>
        /// <param name="withKind">operator kind</param>
        /// <param name="arity">operator arity</param>
        public StringOperator(OperatorKind withKind, int arity) : base(withKind, arity) { }

        /// <summary>
        ///     get the operator name
        /// </summary>
        public override string Name {
            get {
                switch (Kind) {
                    case OperatorKind.ConcatOperator:
                        return KnownNames.Plus;
                }
                throw new InvalidOperationException();
            }
        }

        /// <summary>
        ///     evaluate a binary operator
        /// </summary>
        /// <param name="input"></param>
        /// <param name="currentUnit">current unit</param>
        /// <returns></returns>
        protected override ITypeSymbol EvaluateBinaryOperator(ISignature input, IUnitType currentUnit) {
            var left = input[0];
            var right = input[1];
            var operations = Runtime.GetStringOperators(left, right);

            if (operations == null)
                return Invalid;

            if (Kind == OperatorKind.ConcatOperator)
                return EvaluateConcatOperator(left, right, operations);

            return Invalid;
        }

        private ITypeSymbol EvaluateConcatOperator(ITypeSymbol left, ITypeSymbol right, IStringOperations operations) {
            if (left.IsConstant(out var leftValue) && right.IsConstant(out var rightValue))
                return operations.Concat(leftValue, rightValue);

            var leftType = left.TypeDefinition;
            var rightType = right.TypeDefinition;

            if (leftType is IStringType leftString && leftString.Kind == StringTypeKind.UnicodeString)
                return leftType.Reference;

            if (rightType is IStringType rightString && rightString.Kind == StringTypeKind.UnicodeString)
                return rightType.Reference;

            if (leftType is ICharType leftChar && leftChar.Kind == CharTypeKind.WideChar)
                return SystemUnit.UnicodeStringType.Reference;

            if (rightType is ICharType rightChar && rightChar.Kind == CharTypeKind.WideChar)
                return SystemUnit.UnicodeStringType.Reference;

            return SystemUnit.AnsiStringType.Reference;
        }
    }
}


text:
using MongoDB.Driver;

namespace FileAuditManager.Data
{
    abstract class MongoRepositoryBase
    {
        private readonly IMongoClient MongoClient;
        protected readonly IMongoDatabase MongoDatabase;

        protected MongoRepositoryBase(MongoUrl mongoUrl, IMongoClient mongoClient)
        {
            MongoClient = mongoClient;
            MongoDatabase = MongoClient.GetDatabase(mongoUrl.DatabaseName);
        }
    }
}


text:
import unittest
from kilogram.dataset.dbpedia import DBPediaOntology
from kilogram.entity_types.prediction import NgramTypePredictor
from kilogram import NgramService

class TestTyping(unittest.TestCase):
    ngram_predictor = None

    def setUp(self):
        NgramService.configure(hbase_host=('diufpc304', 9090), subst_table='typogram')
        dbpedia_ontology = DBPediaOntology('fixtures/dbpedia_2015-04.owl')
        self.ngram_predictor = NgramTypePredictor('typogram', dbpedia_ontology)

    def test_main(self):
        print self.ngram_predictor.predict_types("I went NONE NONE NONE".split())
        print self.ngram_predictor.predict_types_features("I went NONE NONE NONE".split())


text:
<?php

  use osCommerce\OM\Core\HTML;
  use osCommerce\OM\Core\OSCOM;

  $Qzones = $OSCOM_PDO->query('select zone_id, zone_name from :table_zones where zone_id in ("' . implode('", "', array_unique(array_filter($_POST['batch'], 'is_numeric'))) . '") order by zone_name');
  $Qzones->execute();

  $names_string = '';

  while ( $Qzones->fetch() ) {
    $names_string .= HTML::hiddenField('batch[]', $Qzones->valueInt('zone_id')) . '' . $Qzones->valueProtected('zone_name') . ', ';
  }

  if ( !empty($names_string) ) {
    $names_string = substr($names_string, 0, -2);
  }
?>

<?php echo $OSCOM_Template->getIcon(32) . HTML::link(OSCOM::getLink(), $OSCOM_Template->getPageTitle()); ?>

<?php
  if ( $OSCOM_MessageStack->exists() ) {
    echo $OSCOM_MessageStack->get();
  }
?>

<?php echo HTML::icon('trash.png') . ' ' . OSCOM::getDef('action_heading_batch_delete_zones'); ?>

  <form name="cDeleteBatch" class="dataForm" action="<?php echo OSCOM::getLink(null, null, 'BatchDeleteZones&Process&id=' . $_GET['id']); ?>" method="post">

<?php echo OSCOM::getDef('introduction_batch_delete_zones'); ?>

<?php echo $names_string; ?>

<?php echo HTML::button(array('priority' => 'primary', 'icon' => 'trash', 'title' => OSCOM::getDef('button_delete'))) . ' ' . HTML::button(array('href' => OSCOM::getLink(null, null, 'id=' . $_GET['id']), 'priority' => 'secondary', 'icon' => 'close', 'title' => OSCOM::getDef('button_cancel'))); ?>

  </form>


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

SYNOPSIS

DESCRIPTION

META CHARACTERS

EXPORTS

 and

POSIX FLAGS

DIAGNOSTICS

NOTES

SEE ALSO

AUTHOR

NAME

File::Glob - Perl extension for BSD glob routine

SYNOPSIS

  use File::Glob ':bsd_glob';

  @list = bsd_glob('*.[ch]');
  $homedir = bsd_glob('~gnat', GLOB_TILDE | GLOB_ERR);

  if (GLOB_ERROR) {
    # an error occurred reading $homedir
  }

  ## override the core glob (CORE::glob() does this automatically
  ## by default anyway, since v5.6.0)
  use File::Glob ':globally';
  my @sources = <*.{c,h,y}>;

  ## override the core glob, forcing case sensitivity
  use File::Glob qw(:globally :case);
  my @sources = <*.{c,h,y}>;

  ## override the core glob forcing case insensitivity
  use File::Glob qw(:globally :nocase);
  my @sources = <*.{c,h,y}>;

  ## glob on all files in home directory
  use File::Glob ':globally';
  my @sources = <~gnat/*>;

DESCRIPTION

The glob angle-bracket operator <> is a pathname generator that implements the rules for file name pattern matching used by Unix-like shells such as the Bourne shell or C shell.

File::Glob::bsd_glob() implements the FreeBSD glob(3) routine, which is a superset of the POSIX glob() (described in IEEE Std 1003.2 "POSIX.2"). bsd_glob() takes a mandatory pattern argument, and an optional flags argument, and returns a list of filenames matching the pattern, with interpretation of the pattern modified by the flags variable.

Since v5.6.0, Perl's CORE::glob() is implemented in terms of bsd_glob(). Note that they don't share the same prototype--CORE::glob() only accepts a single argument. Due to historical reasons, CORE::glob() will also split its argument on whitespace, treating it as multiple patterns, whereas bsd_glob() considers them as one pattern. But see :bsd_glob under "EXPORTS", below.

META CHARACTERS

  \       Quote the next metacharacter
  []      Character class
  {}      Multiple pattern
  *       Match any string of characters
  ?       Match any single character
  ~       User name home directory

The metanotation a{b,c,d}e
 is a shorthand for abe ace ade. Left to right order is preserved, with results of matches being sorted separately at a low level to preserve this order. As a special case {
, }, and {}
 are passed undisturbed.

EXPORTS

See also the "POSIX FLAGS" below, which can be exported individually.

:bsd_glob

The :bsd_glob export tag exports bsd_glob() and the constants listed below. It also overrides glob() in the calling package with one that behaves like bsd_glob() with regard to spaces (the space is treated as part of a file name), but supports iteration in scalar context; i.e., it preserves the core function's feature of returning the next item each time it is called.

:glob

The :glob tag, now discouraged, is the old version of :bsd_glob. It exports the same constants and functions, but its glob() override does not support iteration; it returns the last file name in scalar context. That means this will loop forever:

    use File::Glob ':glob';
    while (my $file = <* copy.txt>) {
        ...
    }

bsd_glob

This function, which is included in the two export tags listed above, takes one or two arguments. The first is the glob pattern. The second is a set of flags ORed together. The available flags are listed below under "POSIX FLAGS". If the second argument is omitted, GLOB_CSH (or GLOB_CSH|GLOB_NOCASE on VMS and DOSish systems) is used by default.

:nocase and :case

These two export tags globally modify the default flags that bsd_glob() and, except on VMS, Perl's built-in glob operator use. GLOB_NOCASE is turned on or off, respectively.

csh_glob

The csh_glob() function can also be exported, but you should not use it directly unless you really know what you are doing. It splits the pattern into words and feeds each one to bsd_glob(). Perl's own glob() function uses this internally.

POSIX FLAGS

The POSIX defined flags for bsd_glob() are:

GLOB_ERR

Force bsd_glob() to return an error when it encounters a directory it cannot open or read. Ordinarily bsd_glob() continues to find matches.

GLOB_LIMIT

Make bsd_glob() return an error (GLOB_NOSPACE) when the pattern expands to a size bigger than the system constant ARG_MAX (usually found in limits.h). If your system does not define this constant, bsd_glob() uses sysconf(_SC_ARG_MAX) or _POSIX_ARG_MAX where available (in that order). You can inspect these values using the standard POSIX extension.

GLOB_MARK

Each pathname that is a directory that matches the pattern has a slash appended.

GLOB_NOCASE

By default, file names are assumed to be case sensitive; this flag makes bsd_glob() treat case differences as not significant.

GLOB_NOCHECK

If the pattern does not match any pathname, then bsd_glob() returns a list consisting of only the pattern. If GLOB_QUOTE is set, its effect is present in the pattern returned.

GLOB_NOSORT

By default, the pathnames are sorted in ascending ASCII order; this flag prevents that sorting (speeding up bsd_glob()).

The FreeBSD extensions to the POSIX standard are the following flags:

GLOB_BRACE

Pre-process the string to expand {pat,pat,...}
 strings like csh(1). The pattern '{}' is left unexpanded for historical reasons (and csh(1) does the same thing to ease typing of find(1) patterns).

GLOB_NOMAGIC

Same as GLOB_NOCHECK but it only returns the pattern if it does not contain any of the special characters "*", "?" or "[". NOMAGIC is provided to simplify implementing the historic csh(1) globbing behaviour and should probably not be used anywhere else.

GLOB_QUOTE

Use the backslash ('\') character for quoting: every occurrence of a backslash followed by a character in the pattern is replaced by that character, avoiding any special interpretation of the character. (But see below for exceptions on DOSISH systems).

GLOB_TILDE

Expand patterns that start with '~' to user name home directories.

GLOB_CSH

For convenience, GLOB_CSH is a synonym for GLOB_BRACE | GLOB_NOMAGIC | GLOB_QUOTE | GLOB_TILDE | GLOB_ALPHASORT.

The POSIX provided GLOB_APPEND, GLOB_DOOFFS, and the FreeBSD extensions GLOB_ALTDIRFUNC, and GLOB_MAGCHAR flags have not been implemented in the Perl version because they involve more complex interaction with the underlying C structures.

The following flag has been added in the Perl implementation for csh compatibility:

GLOB_ALPHASORT

If GLOB_NOSORT is not in effect, sort filenames is alphabetical order (case does not matter) rather than in ASCII order.

DIAGNOSTICS

bsd_glob() returns a list of matching paths, possibly zero length. If an error occurred, &File::Glob::GLOB_ERROR will be non-zero and $! will be set. &File::Glob::GLOB_ERROR is guaranteed to be zero if no error occurred, or one of the following values otherwise:

GLOB_NOSPACE

An attempt to allocate memory failed.

GLOB_ABEND

The glob was stopped because an error was encountered.

In the case where bsd_glob() has found some matching paths, but is interrupted by an error, it will return a list of filenames and set &File::Glob::ERROR.

Note that bsd_glob() deviates from POSIX and FreeBSD glob(3) behaviour by not considering ENOENT and ENOTDIR as errors - bsd_glob() will continue processing despite those errors, unless the GLOB_ERR flag is set.

Be aware that all filenames returned from File::Glob are tainted.

NOTES

If you want to use multiple patterns, e.g. bsd_glob("a* b*"), you should probably throw them in a set as in bsd_glob("{a*,b*}")
. This is because the argument to bsd_glob() isn't subjected to parsing by the C shell. Remember that you can use a backslash to escape things.

On DOSISH systems, backslash is a valid directory separator character. In this case, use of backslash as a quoting character (via GLOB_QUOTE) interferes with the use of backslash as a directory separator. The best (simplest, most portable) solution is to use forward slashes for directory separators, and backslashes for quoting. However, this does not match "normal practice" on these systems. As a concession to user expectation, therefore, backslashes (under GLOB_QUOTE) only quote the glob metacharacters '[', ']', '{', '}', '-', '~', and backslash itself. All other backslashes are passed through unchanged.

Win32 users should use the real slash. If you really want to use backslashes, consider using Sarathy's File::DosGlob, which comes with the standard Perl distribution.

SEE ALSO

"glob" in perlfunc, glob(3)

AUTHOR

The Perl interface was written by Nathan Torkington <gnat@frii.com>, and is released under the artistic license. Further modifications were made by Greg Bacon <gbacon@cs.uah.edu>, Gurusamy Sarathy <gsar@activestate.com>, and Thomas Wegner <wegner_thomas@yahoo.com>. The C glob code has the following copyright:

    Copyright (c) 1989, 1993 The Regents of the University of California.
    All rights reserved.

    This code is derived from software contributed to Berkeley by
    Guido van Rossum.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. Neither the name of the University nor the names of its contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.


text:
package shapeless

import org.junit.Test
import org.junit.Assert._

import shapeless.test._
import shapeless.test.illTyped
import shapeless.testutil.assertTypedEquals

package SingletonTypeTestsDefns {
  class ValueTest(val x: Int) extends AnyVal
}

class SingletonTypesTests {
  import SingletonTypeTestsDefns._
  import syntax.singleton._

  val wTrue = Witness(true)
  type True = wTrue.T
  val wFalse = Witness(false)
  type False = wFalse.T

  val w0 = Witness(0)
  type _0 = w0.T
  val w1 = Witness(1)
  type _1 = w1.T
  val w2 = Witness(2)
  type _2 = w2.T
  val w3 = Witness(3)
  type _3 = w3.T

  val wFoo = Witness('foo)
  type Foo = wFoo.T
  val wBar = Witness('bar)
  type Bar = wBar.T

  @Test
  def testRefine {
    val sTrue = true.narrow
    val sFalse = false.narrow

    sameTyped(sTrue)(sTrue)
    sameTyped(sTrue)(true)

    illTyped("""
      sameTyped(sTrue)(sFalse)
      sameTyped(sTrue)(false)
    """)

    val s13 = 13.narrow
    val s23 = 23.narrow

    sameTyped(s13)(s13)
    sameTyped(s13)(13)

    illTyped("""
      sameTyped(s13)(s23)
      sameTyped(s13)(23)
    """)

    val sFoo = "foo".narrow
    val sBar = "bar".narrow

    sameTyped(sFoo)(sFoo)
    sameTyped(sFoo)("foo")

    illTyped("""
      sameTyped(sFoo)(sBar)
      sameTyped(sFoo)("bar")
    """)

    val sFooSym = 'foo.narrow
    val sBarSym = 'bar.narrow

    sameTyped(sFooSym)(sFooSym)
    sameTyped(sFooSym)('foo)

    illTyped("""
      sameTyped(sFooSym)(sBarSym)
      sameTyped(sFooSym)('bar)
    """)
  }

  trait Show[T] {
    def show: String
  }

  object Show {
    implicit val showTrue  = new Show[True] { def show = "true" }
    implicit val showFalse = new Show[False] { def show = "false" }

    implicit val showOne   = new Show[_1] { def show = "One" }
    implicit val showTwo   = new Show[_2] { def show = "Two" }
    implicit val showThree = new Show[_3] { def show = "Three" }

    implicit val showFoo   = new Show[Foo] { def show = "'foo" }
    implicit val showBar   = new Show[Bar] { def show = "'bar" }
  }

  def show[T](t: T)(implicit s: Show[T]) = s.show

  @Test
  def testRefinedTypeClass {
    val sTrue = show(true.narrow)
    assertEquals("true", sTrue)

    val sFalse = show(false.narrow)
    assertEquals("false", sFalse)

    val sOne = show(1.narrow)
    assertEquals("One", sOne)

    val sTwo = show(2.narrow)
    assertEquals("Two", sTwo)

    val sThree = show(3.narrow)
    assertEquals("Three", sThree)

    illTyped("""
      show(0.narrow)
    """)

    val sFoo = show('foo.narrow)
    assertEquals("'foo", sFoo)

    val sBar = show('bar.narrow)
    assertEquals("'bar", sBar)
  }

  trait LiteralShow[T] {
    def show: String
  }

  object LiteralShow {
    implicit val showTrue  = new LiteralShow[Witness.`true`.T] { def show = "true" }
    implicit val showFalse = new LiteralShow[Witness.`false`.T] { def show = "false" }

    implicit val showOne   = new LiteralShow[Witness.`1`.T] { def show = "One" }
    implicit val showTwo   = new LiteralShow[Witness.`2`.T] { def show = "Two" }
    implicit val showThree = new LiteralShow[Witness.`3`.T] { def show = "Three" }

    implicit val showFoo   = new LiteralShow[Witness.`'foo`.T] { def show = "'foo" }
    implicit val showBar   = new LiteralShow[Witness.`'bar`.T] { def show = "'bar" }
  }

  def literalShow[T](t: T)(implicit s: LiteralShow[T]) = s.show

  @Test
  def testRefinedLiteralTypeClass {
    val sTrue = literalShow(true.narrow)
    assertEquals("true", sTrue)

    val sFalse = literalShow(false.narrow)
    assertEquals("false", sFalse)

    val sOne = literalShow(1.narrow)
    assertEquals("One", sOne)

    val sTwo = literalShow(2.narrow)
    assertEquals("Two", sTwo)

    val sThree = literalShow(3.narrow)
    assertEquals("Three", sThree)

    illTyped("""
      literalShow(0.narrow)
    """)

    val sFoo = literalShow('foo.narrow)
    assertEquals("'foo", sFoo)

    val sBar = literalShow('bar.narrow)
    assertEquals("'bar", sBar)
  }

  trait LiteralsShow[-T] {
    def show: String
  }

  object LiteralsShow {
    implicit val showTrueFalse        = new LiteralsShow[HList.`true, false`.T] { def show = "true, false" }
    implicit val showOneOrTwoOrThree  = new LiteralsShow[Coproduct.`1, 2, 3`.T] { def show = "One | Two | Three" }
    implicit val showFooBar           = new LiteralsShow[HList.`'foo, 'bar`.T] { def show = "'foo, 'bar" }
  }

  def literalsShow[T](t: T)(implicit s: LiteralsShow[T]) = s.show

  @Test
  def testRefinedLiteralsTypeClass {
    val sTrueFalse = literalsShow(true.narrow :: false.narrow :: HNil)
    assertEquals("true, false", sTrueFalse)

    val sOne = literalsShow(Inl(1.narrow))
    assertEquals("One | Two | Three", sOne)

    val sTwo = literalsShow(Inr(Inl(2.narrow)))
    assertEquals("One | Two | Three", sTwo)

    val sThree = literalsShow(Inr(Inr(Inl(3.narrow))))
    assertEquals("One | Two | Three", sThree)

    illTyped("""
      literalsShow(true :: false :: HNil)
    """)

    val sFooBar = literalsShow('foo.narrow :: 'bar.narrow :: HNil)
    assertEquals("'foo, 'bar", sFooBar)
  }

  @Test
  def testWitness {
    val wTrue = Witness(true)
    val wFalse = Witness(false)

    sameTyped(wTrue)(wTrue)

    illTyped("""
      sameTyped(wTrue)(wFalse)
    """)

    val w13 = Witness(13)
    val w23 = Witness(23)

    sameTyped(w13)(w13)

    illTyped("""
      sameTyped(w13)(w23)
    """)

    val wFoo = Witness("foo")
    val wBar = Witness("bar")

    sameTyped(wFoo)(wFoo)

    illTyped("""
      sameTyped(wFoo)(wBar)
    """)

    val wFooSym = Witness('foo)
    val wBarSym = Witness('bar)

    sameTyped(wFooSym)(wFooSym)

    illTyped("""
      sameTyped(wFooSym)(wBarSym)
    """)
  }

  def convert(w: Witness): Witness.Aux[w.T] = w

  def boundedConvert2[B](w: Witness.Lt[B]): Witness.Aux[w.T] = w

  def testSingletonWitness {
    trait Bound
    object Foo extends Bound
    val bar = "bar"
    val wFoo = Witness(Foo)
    val wBar = Witness(bar)

    // Note: Further tests in SingletonTypes211Tests

    val cFoo = convert(Foo)
    val cBar = convert(bar)

    sameTyped(cFoo)(Witness(Foo))
    sameTyped(cBar)(Witness(bar))

    val bcFoo = boundedConvert2[Bound](Foo)
    val bcBar = boundedConvert2[String](bar)

    sameTyped(bcFoo)(Witness(Foo))
    sameTyped(bcBar)(Witness(bar))
  }

  @Test
  def testWitnessConversion {
    val cTrue = convert(true)
    val cFalse = convert(false)

    sameTyped(cTrue)(Witness(true))
    sameTyped(cFalse)(Witness(false))

    illTyped("""
      sameTyped(cTrue)(Witness(false))
    """)
    illTyped("""
      sameTyped(cFalse)(Witness(true))
    """)

    val c13 = convert(13)
    val c23 = convert(23)

    sameTyped(c13)(Witness(13))
    sameTyped(c23)(Witness(23))

    illTyped("""
      sameTyped(c13)(Witness(23))
    """)
    illTyped("""
      sameTyped(c23)(Witness(13))
    """)

    val cFoo = convert("foo")
    val cBar = convert("bar")

    sameTyped(cFoo)(Witness("foo"))
    sameTyped(cBar)(Witness("bar"))

    illTyped("""
      sameTyped(cFoo)(Witness("bar"))
    """)
    illTyped("""
      sameTyped(cBar)(Witness("foo"))
    """)

    val cFooSym = convert('foo)
    val cBarSym = convert('bar)

    sameTyped(cFooSym)(Witness('foo))
    sameTyped(cBarSym)(Witness('bar))

    illTyped("""
      sameTyped(cFooSym)(Witness('bar))
    """)
    illTyped("""
      sameTyped(cBarSym)(Witness('foo))
    """)
  }

  def boundedConvert(w: Witness.Lt[Int]): Witness.Aux[w.T] = w

  @Test
  def testBoundedWitnessConversion {
    val c13 = boundedConvert(13)
    sameTyped(c13)(Witness(13))
    illTyped("""
      sameTyped(c13)(Witness(23))
    """)

    illTyped("""
      boundedConvert(true)
    """)

    illTyped("""
      boundedConvert("foo")
    """)

    illTyped("""
      boundedConvert('foo)
    """)
  }

  def showLiteral(t: Witness)(implicit s: Show[t.T]) = s.show

  @Test
  def testLiteralTypeClass {
    val sTrue = showLiteral(true)
    assertEquals("true", sTrue)

    val sFalse = showLiteral(false)
    assertEquals("false", sFalse)

    val sOne = showLiteral(1)
    assertEquals("One", sOne)

    val sTwo = showLiteral(2)
    assertEquals("Two", sTwo)

    val sThree = showLiteral(3)
    assertEquals("Three", sThree)

    val sFooSym = showLiteral('foo)
    assertEquals("'foo", sFooSym)

    val sBarSym = showLiteral('bar)
    assertEquals("'bar", sBarSym)

    illTyped("""
      showLiteral(0)
    """)
  }

  trait ShowWitness[T] {
    def show: String
  }

  object ShowWitness {
    implicit def showWitness[T](implicit w: Witness.Aux[T]) =
      new ShowWitness[T] {
        def show = w.value.toString
      }
  }

  def showWitness(w: Witness)(implicit s: ShowWitness[w.T]) = s.show

  @Test
  def testWitnessTypeClass {
    val sTrue = showWitness(true)
    assertEquals("true", sTrue)

    val sFalse = showWitness(false)
    assertEquals("false", sFalse)

    val sOne = showWitness(1)
    assertEquals("1", sOne)

    val sTwo = showWitness(2)
    assertEquals("2", sTwo)

    val sThree = showWitness(3)
    assertEquals("3", sThree)

    val sFooSym = showWitness('foo)
    assertEquals("'foo", sFooSym)

    val sBarSym = showWitness('bar)
    assertEquals("'bar", sBarSym)
  }

  def showWitnessWith(w: WitnessWith[Show]) = w.instance.show

  @Test
  def testWitnessWith {
    val sTrue = showWitnessWith(true)
    assertEquals("true", sTrue)

    val sFalse = showWitnessWith(false)
    assertEquals("false", sFalse)

    val sOne = showWitnessWith(1)
    assertEquals("One", sOne)

    val sTwo = showWitnessWith(2)
    assertEquals("Two", sTwo)

    val sThree = showWitnessWith(3)
    assertEquals("Three", sThree)

    val sFooSym = showWitnessWith('foo)
    assertEquals("'foo", sFooSym)

    val sBarSym = showWitnessWith('bar)
    assertEquals("'bar", sBarSym)
  }

  trait Rel[T] {
    type Out
  }

  object Rel {
    implicit def relTrue:  Rel[True]  { type Out = Int  } = new Rel[True]  { type Out = Int }
    implicit def relFalse: Rel[False] { type Out = String } = new Rel[False] { type Out = String }
  }

  def check(w: WitnessWith[Rel])(v: w.instance.Out) = v

  @Test
  def testWitnessWithOut {
    val relTrue = check(true)(23)
    typed[Int](relTrue)

    val relFalse = check(false)("foo")
    typed[String](relFalse)

    illTyped("""
      check(true)("foo")
    """)

    illTyped("""
      check(false)(23)
    """)

    illTyped("""
      check(23)(23)
    """)
  }

  @Test
  def testValueClass {
    val x = new ValueTest(5)
    illTyped("""
    val wX = Witness(x)
    """)
  }

  @Test
  def primitiveWiden {
    {
      val w = Widen[Witness.`2`.T]
      illTyped(" w(3) ", "type mismatch;.*")
      val n = w(2)
      val n0: Int = n
      illTyped(" val n1: Witness.`2`.T = n ", "type mismatch;.*")

      assertTypedEquals[Int](2, n)
    }

    {
      val w = Widen[Witness.`true`.T]
      illTyped(" w(false) ", "type mismatch;.*")
      val b = w(true)
      val b0: Boolean = b
      illTyped(" val b1: Witness.`true`.T = b ", "type mismatch;.*")

      assertTypedEquals[Boolean](true, b)
    }

    {
      val w = Widen[Witness.`"ab"`.T]
      illTyped(""" w("s") """, "type mismatch;.*")
      val s = w("ab")
      val s0: String = s
      illTyped(""" val s1: Witness.`"ab"`.T = s """, "type mismatch;.*")

      assertTypedEquals[String]("ab", s)
    }
  }

  @Test
  def symbolWiden {
    // Masks shapeless.syntax.singleton.narrowSymbol.
    // Having it in scope makes the illTyped tests fail in an unexpected way.
    def narrowSymbol = ???

    val w = Widen[Witness.`'ab`.T]
    illTyped(" w('s.narrow) ", "type mismatch;.*")
    val s = w('ab.narrow)
    val s0: Symbol = s
    illTyped(" val s1: Witness.`'ab`.T = s ", "type mismatch;.*")

    assertTypedEquals[Symbol]('ab, s)
  }

  @Test
  def aliasWiden {
    type T = Witness.`2`.T
    val w = Widen[T]
    illTyped(" w(3) ", "type mismatch;.*")
    val n = w(2)
    val n0: Int = n
    illTyped(" val n1: Witness.`2`.T = n ", "type mismatch;.*")

    assertTypedEquals[Int](2, n)
  }

  trait B
  case object A extends B

  @Test
  def singletonWiden {
    illTyped(" Widen[A.type] ", "could not find implicit value for parameter widen:.*")
  }

}

package SingletonTypeTestsAux {
  class Wrapper {
    sealed trait Sealed
    object Sealed {
      case object A extends Sealed
    }

    implicitly[Witness.Aux[Sealed.A.type]]
  }
}


text:
<?php

if ( ! defined('EXT'))
{
	exit('Invalid file request');
}

class Monica {

	/* --------------------------------------------------------------
	 * PUBLIC PROPERTIES
	 * ------------------------------------------------------------ */

	/**
	 * The extension name.
	 *
	 * @access  public
	 * @var     string
	 */
	public $name = 'Monica';

	/**
	 * The extension version.
	 *
	 * @access  public
	 * @var     string
	 */
	public $version = '0.1.0';

	/**
	 * The extension description.
	 *
	 * @access  public
	 * @var     string
	 */
	public $description = 'Super-simple site name replacement.';

	/**
	 * The documentation URL.
	 *
	 * @access  public
	 * @var     string
	 */
	public $docs_url = 'http://experienceinternet.co.uk/software/';

	/**
	 * Does this extension have custom settings?
	 *
	 * @access  public
	 * @var     string
	 */
	public $settings_exist = 'y';

	/**
	 * The extension settings.
	 *
	 * @access  public
	 * @var     array
	 */
	public $settings = array();

	/* --------------------------------------------------------------
	 * PRIVATE PROPERTIES
	 * ------------------------------------------------------------ */

	/**
	 * The class name.
	 *
	 * @access	private
	 * @var 	string
	 */
	private $_class_name = '';

	/* --------------------------------------------------------------
	 * PUBLIC METHODS
	 * ------------------------------------------------------------ */

	/**
	 * Constructor
	 *
	 * @access  public
	 * @param   array|string    $settings     Associative array or empty string.
	 */
	public function __construct($settings = '')
	{
		$this->_class_name = get_class($this);
		$this->settings = $settings;
	}

	/**
	 * Activates the extension.
	 *
	 * @access  public
	 */
	public function activate_extension()
	{
		global $DB;

		$hooks = array(
			array(
				'hook'		=> 'show_full_control_panel_end',
				'method'	=> 'show_full_control_panel_end',
				'priority'	=> 10
			)
		);

		foreach ($hooks AS $hook)
		{
			$sql[] = $DB->insert_string('exp_extensions', array(
						'class'        => $this->_class_name,
						'enabled'      => 'y',
						'extension_id' => '',
						'hook'         => $hook['hook'],
						'method'       => $hook['method'],
						'priority'     => $hook['priority'],
						'settings'     => '',
						'version'      => $this->version
					));
		}

		foreach ($sql AS $query)
		{
			$DB->query($query);
		}
	}

	/**
	 * Disables the extension, and deletes settings from the database.
	 *
	 * @access  public
	 */
	public function disable_extension()
	{
		global $DB;

		$DB->query("DELETE FROM exp_extensions WHERE class = '{$this->_class_name}'");
	}

	/**
	 * Displays the settings form.
	 *
	 * @access	public
	 * @return	array
	 */
	public function settings()
	{
		return array('suffix' => '');
	}

	/**
	 * Handles the 'show_full_control_panel_end' hook.
	 *
	 * @access	public
	 * @see		http://expressionengine.com/developers/extension_hooks/show_full_control_panel_end/
	 * @param	string		$out	The HTML to output.
	 * @return	string
	 */
	public function show_full_control_panel_end($out = '')
	{
		global $EXT, $PREFS;

		if ($EXT->last_call !== FALSE)
		{
			$out = $EXT->last_call;
		}

		$patterns = array();
		$replacements = array();

		// The site title.
		$patterns[] = "/(
).*?(<\/div>)/is";
		$replacements[] = '$1' .$PREFS->ini('site_name') .'' .
			(isset($this->settings['suffix'])
				? '  |  ' .$this->settings['suffix'] .'$2'
				: '$2');

		// CSS.
		$patterns[] = '/<\/head>/i';
		$replacements[] = <<<CSS

CSS;

		return preg_replace($patterns, $replacements, $out);
	}

	/**
	 * Updates the extension.
	 *
	 * @access  public
	 * @param   string    $current    The current version of the extension (or an empty string).
	 * @return  bool      FALSE if the extension is not installed, or is the current version.
	 */
	public function update_extension($current='')
	{
		global $DB;

		if ($current == '' OR $current == $this->version)
		{
			return FALSE;
		}

		if ($current < $this->version)
		{
			$DB->query("UPDATE exp_extensions
				SET version = '" . $DB->escape_str($this->version) . "'
				WHERE class = '{$this->_class_name}'");
		}
	}

	/* --------------------------------------------------------------
	 * PRIVATE METHODS
	 * ------------------------------------------------------------ */

}

/**
 * End of file ext.monica.php
 */


text:
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.test.utils import override_settings

from cms.api import assign_user_to_page, create_page
from cms.cache.permissions import (
    clear_user_permission_cache, get_permission_cache, set_permission_cache,
)
from cms.models import Page
from cms.models.permissionmodels import (
    ACCESS_PAGE_AND_DESCENDANTS, GlobalPagePermission,
)
from cms.test_utils.testcases import URL_CMS_PAGE_ADD, CMSTestCase
from cms.utils.page_permissions import (
    get_change_id_list, user_can_add_subpage, user_can_publish_page,
    user_can_view_page,
)

@override_settings(
    CMS_PERMISSION=True,
    CMS_CACHE_DURATIONS={
        'menus': 60,
        'content': 60,
        'permissions': 60,
    },
)
class PermissionCacheTests(CMSTestCase):

    def setUp(self):
        self.user_super = self._create_user("super", is_staff=True,
                                            is_superuser=True)
        self.user_normal = self._create_user("randomuser", is_staff=True,
                                             add_default_permissions=True)
        self.home_page = create_page("home", "nav_playground.html", "en",
                                     created_by=self.user_super)

    def test_basic_permissions(self):
        """
        Test basic permissions cache get / set / clear low-level api
        """
        cached_permissions = get_permission_cache(self.user_normal, "change_page")
        self.assertIsNone(cached_permissions)

        set_permission_cache(self.user_normal, "change_page", [self.home_page.id])
        cached_permissions = get_permission_cache(self.user_normal, "change_page")
        self.assertEqual(cached_permissions, [self.home_page.id])

        clear_user_permission_cache(self.user_normal)
        cached_permissions = get_permission_cache(self.user_normal, "change_page")
        self.assertIsNone(cached_permissions)

    def test_permission_manager(self):
        """
        Test page permission manager working on a subpage
        """
        page_b = create_page("page_b", "nav_playground.html", "en",
                             created_by=self.user_super)
        assign_user_to_page(page_b, self.user_normal, can_view=True,
                            can_change=True)
        cached_permissions = get_permission_cache(self.user_normal, "change_page")
        self.assertIsNone(cached_permissions)

        live_permissions = get_change_id_list(self.user_normal, Site.objects.get_current())
        cached_permissions_permissions = get_permission_cache(self.user_normal,
                                                              "change_page")
        self.assertEqual(live_permissions, [page_b.id])
        self.assertEqual(cached_permissions_permissions, live_permissions)

    def test_cached_permission_precedence(self):
        # refs - https://github.com/divio/django-cms/issues/6335
        # cached page permissions should not override global permissions
        page = create_page(
            "test page",
            "nav_playground.html",
            "en",
            created_by=self.user_super,
        )
        page_permission = GlobalPagePermission.objects.create(
            can_change=True,
            can_publish=True,
            user=self.user_normal,
        )
        page_permission.sites.add(Site.objects.get_current())
        set_permission_cache(self.user_normal, "publish_page", [])

        can_publish = user_can_publish_page(
            self.user_normal,
            page,
            Site.objects.get_current(),
        )
        self.assertTrue(can_publish)

    def test_visibility_after_move_page(self):
        superuser = self.get_superuser()
        user1 = self._create_user("user1", is_staff=True, is_superuser=False)

        visible = create_page("visible", "nav_playground.html", "en", published=True)
        visible_child = create_page("visible_child", "nav_playground.html", "en", parent=visible, published=True)
        invisible_for_user1 = create_page("invisible", "nav_playground.html", "en", published=True)

        assign_user_to_page(visible, user1, grant_on=ACCESS_PAGE_AND_DESCENDANTS, can_view=True)
        assign_user_to_page(invisible_for_user1, superuser, grant_on=ACCESS_PAGE_AND_DESCENDANTS, can_view=True)

        with self.login_user_context(user1):
            response = self.client.get(visible_child.get_public_object().get_absolute_url())
            self.assertEqual(response.status_code, 200)

            response = self.client.get(invisible_for_user1.get_public_object().get_absolute_url())
            self.assertEqual(response.status_code, 404)

        with self.login_user_context(superuser):
            move_url = self.get_admin_url(Page, 'move_page', visible_child.pk)
            response = self.client.post(move_url, {
                'id': visible_child.pk,
                'position': 0,
                'target': invisible_for_user1.pk,
            })
            self.assertEqual(response.status_code, 200)
            visible_child = visible_child.reload()
            self.assertEqual(visible_child.parent_page.pk, invisible_for_user1.pk)

        # Ignore cached_func
        User = get_user_model()
        user1 = User.objects.get(pk=user1.pk)
        self.assertFalse(user_can_view_page(user=user1, page=visible_child))

    def test_add_page_twice(self):
        user1 = self._create_user("user1", is_staff=True, is_superuser=False, add_default_permissions=True)

        home = create_page("home", "nav_playground.html", "en", published=True)
        home.set_as_homepage()
        assign_user_to_page(home, user1, grant_on=ACCESS_PAGE_AND_DESCENDANTS, can_add=True, can_change=True, can_publish=True)

        with self.login_user_context(user1):
            response = self.client.post(f'{URL_CMS_PAGE_ADD}?parent_node={home.node.pk}', self.get_new_page_data(parent_id=home.node.pk))
            self.assertEqual(response.status_code, 302)

        child = home.reload().get_child_pages().first()
        self.assertIsNotNone(child)

        # Ignore cached_func
        User = get_user_model()
        user1 = User.objects.get(pk=user1.pk)
        self.assertTrue(user_can_add_subpage(user1, child))