text:
this method _requires_ a password.

*This function is not binary safe.*

###  `process:group_set(groupname) → status`

Set the group under which the child process will run. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

*This function is not binary safe.*

###  `process:cmdtype_set(type) → status`

Set what type of command the child process will execute. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned. The
argument <tt>*type*</tt> must be one of:

 - `'shellcmd'`: Use the shell to invoke the program
 - `'shellcmd/env'`: Use the shell to invoke the program, replicating our environment
 - `'program'`: Invoke the program directly, without copying the environment
 - `'program/env'`: Invoke the program directly, replicating our environment
 - `'program/env/path'`: Find program in `$PATH`, replicating our environment

###  `process:env_set(environment) → status`

Set the environment variables of the child process to the key/value pairs in
the table <tt>*environment*</tt>. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt>
followed by an error message is returned.

Please note that the environment table is ignored for the command types
`'shellcmd/env'`, `'program/env'` and `'program/env/path'` (set using the
[process:cmdtype\_set()](#process:cmdtype_set) method).

*This function is not binary safe.*

###  `process:dir_set(path) → status`

Set which directory the child process should start executing in. On success
<tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

By default child processes inherit this directory from their parent process
at the moment when the [process:exec()](#process:exec) call is made. To find out the
current directory see the [apr.filepath\_get()](#apr.filepath_get) function.

*This function is not binary safe.*

###  `process:detach_set(detach) → status`

Determine if the child should start in detached state. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned. Default
is no.

###  `process:error_check_set(enabled) → nothing`

Specify that [process:exec()](#process:exec) should do whatever it can to report failures
directly, rather than find out in the child that something is wrong. This
leads to extra overhead in the calling process, but it may help you handle
these errors more gracefully.

Note that this option is only useful on platforms where [fork()][fork] is
used.

[fork]: http://linux.die.net/man/2/fork

###  `process:io_set(stdin, stdout, stderr) → status`

Determine if the child process should be linked to its parent through one or
more pipes. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an
error message is returned.

Each argument gives the blocking mode of a pipe, which can be one of the
following strings:

 - `'none'`: Don't create a pipe
 - `'full-block'`: Create a pipe that blocks until the child process writes to the pipe or dies
 - `'full-nonblock'`: Create a pipe that doesn't block
 - `'parent-block'`: Create a pipe that only blocks on the parent's end
 - `'child-block'`: Create a pipe that only blocks on the child's end

*Once the child process has been started* with [process:exec()](#process:exec), the pipes
can be accessed with the methods [process:in\_get()](#process:in_get), [process:out\_get()](#process:out_get)
and [process:err\_get()](#process:err_get).

Here's an example that executes the external command `tr a-z A-Z` to
translate some characters to uppercase:

    > p = apr.proc_create 'tr'
    > p:cmdtype_set('shellcmd/env')
    > p:io_set('child-block', 'parent-block', 'none')
    > p:exec{'a-z', 'A-Z'}
    > input = p:in_get()
    > output = p:out_get()
    > input:write('Testing, 1, 2, 3\n')
    > input:close()
    > print(output:read())
    TESTING, 1, 2, 3
    > output:close()
    > p:wait(true)

###  `process:in_set(child_in [, parent_in]) → status`

Initialize the [standard input pipe] [stdin] of the child process to an
existing pipe or a pair of pipes. This can be useful if you have already
opened a pipe (or multiple files) that you wish to use, perhaps persistently
across multiple process invocations - such as a log file. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned. Here's
a basic example that connects two processes using an anonymous pipe:

    -- Create a gzip process to decompress the Lua source code archive.
    gzip = apr.proc_create 'gunzip'
    gzip:cmdtype_set 'shellcmd/env'
    gzip:in_set(apr.file_open('lua-5.1.4.tar.gz', 'rb'))

    -- Create a tar process to list the files in the decompressed archive.
    tar = apr.proc_create 'tar'
    tar:cmdtype_set 'shellcmd/env'
    tar:out_set(apr.pipe_open_stdout())

    -- Connect the two processes using an anonymous pipe.
    input, output = assert(apr.pipe_create())
    gzip:out_set(output)
    tar:in_set(input)

    -- Start the pipeline by executing both processes.
    gzip:exec()
    tar:exec{'-t'}

[stdin]: http://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29

###  `process:out_set(child_out [, parent_out]) → status`

Initialize the [standard output pipe] [stdout] of the child process to an
existing pipe or a pair of pipes. This can be useful if you have already
opened a pipe (or multiple files) that you wish to use, perhaps persistently
across multiple process invocations - such as a log file. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

[stdout]: http://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29

###  `process:err_set(child_err [, parent_err]) → status`

Initialize the [standard error pipe] [stderr] of the child process to an
existing pipe or a pair of pipes. This can be useful if you have already
opened a pipe (or multiple files) that you wish to use, perhaps persistently
across multiple process invocations - such as a log file. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

[stderr]: http://en.wikipedia.org/wiki/Standard_streams#Standard_error_.28stderr.29

###  `process:in_get() → pipe`

Get the parent end of the standard input pipe (a writable pipe).

###  `process:out_get() → pipe`

Get the parent end of the standard output pipe (a readable pipe).

###  `process:err_get() → pipe`

Get the parent end of the standard error pipe (a readable pipe).

###  `process:exec([args]) → status`

Create the child process and execute a program or shell command inside it.
On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned. If the <tt>*args*</tt> array is given the contained strings become the
command line arguments to the child process. The [program name] [progname]
for the child process defaults to the name passed into [apr.proc\_create()](#apr.proc_create),
but you can change it by setting `args[0]`.

[progname]: http://en.wikipedia.org/wiki/BusyBox#Single_binary

*This function is not binary safe.*

###  `process:wait(how) → done [, why, code]`

Wait for the child process to die. If <tt>*how*</tt> is <tt>*true*</tt> the call blocks until the
process dies, otherwise the call returns immediately regardless of if the
process is dead or not. The first return value is <tt>*false*</tt> if the process isn't
dead yet. If it's <tt>*true*</tt> the process died and two more return values are
available. The second return value is the reason the process died, which is
one of:

 - `'exit'`: Process exited normally
 - `'signal'`: Process exited due to a signal
 - `'signal/core'`: Process exited and dumped [a core file] [coredump]

The third return value is the exit code of the process. If an error occurs a
<tt>*nil*</tt> followed by an error message is returned.

[coredump]: http://en.wikipedia.org/wiki/Core_dump

###  `process:kill(how) → status`

Terminate a running child process. On success <tt>*true*</tt> is returned, otherwise a
<tt>*nil*</tt> followed by an error message is returned. The parameter <tt>*how*</tt> must be one
of:

 - `'never'`: The process is never sent any signals
 - `'always'`: The process is sent the [SIGKILL] [sigkill] signal when its
   Lua userdata is garbage collected
 - `'timeout'`: Send the [SIGTERM] [sigterm] signal, wait for 3 seconds,
   then send the [SIGKILL] [sigkill] signal
 - `'wait'`: Wait forever for the process to complete
 - `'once'`: Send the [SIGTERM] [sigterm] signal and then wait

[sigkill]: http://en.wikipedia.org/wiki/SIGKILL
[sigterm]: http://en.wikipedia.org/wiki/SIGTERM

## Shared memory

[Shared memory] [shm] is memory that may be simultaneously accessed by
multiple programs with an intent to provide communication among them. The
Lua/APR binding represents shared memory as file objects through the
[shm:read()](#shm:read), [shm:write()](#shm:write) and [shm:seek()](#shm:seek) methods.

[shm]: http://en.wikipedia.org/wiki/Shared_memory

###  `apr.shm_create(filename, size) → shm object`

Create and make accessible a shared memory segment. The <tt>*filename*</tt> argument
is the file to use for shared memory on platforms that require it. The <tt>*size*</tt>
argument is the desired size of the segment.

A note about anonymous vs. named shared memory segments: Not all platforms
support anonymous shared memory segments, but in some cases it is preferred
over other types of shared memory implementations. Passing a <tt>*nil*</tt> <tt>*filename*</tt>
parameter to this function will cause the subsystem to use anonymous shared
memory segments. If such a system is not available, the error `'ENOTIMPL'`
is returned as the third return value (the first and second being <tt>*nil*</tt> and an
error message string).

*This function is not binary safe.*

###  `apr.shm_attach(filename) → shm object`

Attach to a shared memory segment that was created by another process. The
<tt>*filename*</tt> argument is the file used to create the original segment (this
must match the original filename). On success a shared memory object is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

*This function is not binary safe.*

###  `apr.shm_remove(filename) → status`

Remove the named resource associated with a shared memory segment,
preventing attachments to the resource, but not destroying it. On success
<tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

This function is only supported on platforms which support name-based shared
memory segments, and will return the error code `'ENOTIMPL'` on platforms
without such support. Removing the file while the shared memory is in use is
not entirely portable, caller may use this to enhance obscurity of the
resource, but be prepared for the the call to fail, and for concurrent
attempts to create a resource of the same name to also fail.

Note that the named resource is also removed when a shared memory object
created by [apr.shm\_create()](#apr.shm_create) is garbage collected.

*This function is not binary safe.*

###  `shm:read([format, ...]) → mixed value, ...`

_This function implements the interface of the [file:read()] [fread] function described in the Lua 5.1 reference manual. Here is the description from the reference manual:_

Read from shared memory, according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or <tt>*nil*</tt> if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below).

The available formats are:

 - `'*n'`: reads a number; this is the only format that returns a number instead of a string
 - `'*a'`: reads all data from the shared memory, starting at the current position. On end of input, it returns the empty string
 - `'*l'`: reads the next line (skipping the end of line), returning <tt>*nil*</tt> on end of input (this is the default format)
 - `number`: reads a string with up to this number of characters, returning <tt>*nil*</tt> on end of input. If number is zero, it reads nothing and returns an empty string, or <tt>*nil*</tt> on end of input

[fread]: http://www.lua.org/manual/5.1/manual.html#pdf-file:read

###  `shm:write(value [, ...]) → status`

_This function implements the interface of the [file:write()] [fwrite] function described in the Lua 5.1 reference manual. Here is the description from the reference manual:_

Write the value of each argument to shared memory. The arguments must be strings or numbers. To write other values, use [tostring()](http://www.lua.org/manual/5.1/manual.html#pdf-tostring) or [string.format()](http://www.lua.org/manual/5.1/manual.html#pdf-string.format) before this function.

[fwrite]: http://www.lua.org/manual/5.1/manual.html#pdf-file:write

###  `shm:seek([whence [, offset]]) → offset`

_This function implements the interface of the [file:seek()] [fseek] function described in the Lua 5.1 reference manual. Here is the description from the reference manual:_

Sets and gets the shared memory position, measured from the beginning of the shared memory, to
the position given by <tt>*offset*</tt> plus a base specified by the string <tt>*whence*</tt>, as
follows:

 - `'set'`:  base is position 0 (beginning of the shared memory)
 - `'cur'`:  base is current position
 - `'end'`:  base is end of shared memory

In case of success, function `seek` returns the final shared memory position, measured
in bytes from the beginning of the shared memory. If this function fails, it returns
<tt>*nil*</tt>, plus a string describing the error.

The default value for <tt>*whence*</tt> is `'cur'`, and for offset is 0. Therefore, the
call [shm:seek()](#shm:seek) returns the current shared memory position, without changing it; the
call `shm:seek('set')` sets the position to the beginning of the shared memory (and
returns 0); and the call `shm:seek('end')` sets the position to the end of the
shared memory, and returns its size.

[fseek]: http://www.lua.org/manual/5.1/manual.html#pdf-file:seek

###  `shm:detach() → status`

Detach from a shared memory segment without destroying it. On success <tt>*true*</tt>
is returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

###  `shm:destroy() → status`

Destroy a shared memory segment and associated memory. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned. Note
that this will be done automatically when the shared memory object is
garbage collected and has not already been destroyed.

## Signal handling

[Signals] [signals] provide a limited form of inter-process communication.
On UNIX they are for example used to communicate to [daemons] [daemons] that
they should reload their configuration or stop gracefully. This module works
on Linux and most if not all UNIX systems but it's not very useful on
Windows, because [Windows has poor support for signals] [msdn_signals]:

> `SIGINT` is not supported for any Win32 application, including Windows
> 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs, Win32
> operating systems generate a new thread to specifically handle that
> interrupt. This can cause a single-thread application such as UNIX,
> to become multithreaded, resulting in unexpected behavior.
> ...
> The `SIGILL`, `SIGSEGV`, and `SIGTERM` signals are not generated under
> Windows NT. They are included for ANSI compatibility. Thus you can set
> signal handlers for these signals with signal(), and you can also
> explicitly generate these signals by calling raise().

The following signal related functionality is not exposed by the Lua/APR
binding because the Apache Portable Runtime doesn't wrap the required
functions:

 - APR doesn't expose [kill()] [kill] except through [process:kill()](#process:kill) which
   only supports two signals (`SIGTERM` and `SIGKILL`) which means users of
   the Lua/APR binding cannot send arbitrary signals to processes (use
   [luaposix] [lposix] instead)

 - APR doesn't expose [alarm()][alarm] and Windows doesn't support it which
   means the `SIGALRM` signal is useless (use [lalarm] [lalarm] instead)

[signals]: http://en.wikipedia.org/wiki/Signal_(computing)
[daemons]: http://en.wikipedia.org/wiki/Daemon_(computing)
[msdn_signals]: http://msdn.microsoft.com/en-us/library/xdkz3x12(v=vs.71).aspx
[kill]: http://linux.die.net/man/3/kill
[lposix]: http://luaforge.net/projects/luaposix/
[alarm]: http://linux.die.net/man/3/alarm
[lalarm]: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lalarm

###  `apr.signal(name [, handler]) → status`

Set the signal handler function for a given signal. The argument <tt>*name*</tt> must
be a string with the name of the signal to handle ([apr.signal\_names()](#apr.signal_names)
returns a table of available names on your platform). The argument <tt>*handler*</tt>
must be of type function, unless it is <tt>*nil*</tt> in which case default handling
is restored for the given signal. On success <tt>*true*</tt> is returned, otherwise a
<tt>*nil*</tt> followed by an error message is returned.

###  `apr.signal_raise(name) → status`

Send a signal to *the current process*. The result is <tt>*true*</tt> when the call
succeeded, <tt>*false*</tt> otherwise. This function is useful to test your own signal
handlers:

    > = apr.signal('SIGSEGV', function() print 'almost crashed :-)' end)
    true
    > = apr.signal_raise('SIGSEGV')
    almost crashed :-)
    true
    > = apr.signal('SIGSEGV', nil)
    true
    > = apr.signal_raise('SIGSEGV')
    zsh: segmentation fault  lua

###  `apr.signal_block(name) → status`

Block the delivery of a particular signal. On success <tt>*true*</tt> is returned,
otherwise a <tt>*nil*</tt> followed by an error message is returned.

###  `apr.signal_unblock(name) → status`

Enable the delivery of a particular signal. On success <tt>*true*</tt> is returned,
otherwise a <tt>*nil*</tt> followed by an error message is returned.

###  `apr.signal_names() → names`

Return a table with available signal names on your platform. The keys of the
table are the names of the signals and the values are the integer codes
associated with the signals.

As the previous paragraph implies the result of this function can differ
depending on your operating system and processor architecture. For example
on my Ubuntu Linux 10.04 installation I get these results:

    > signals = {}
    > for k, v in pairs(apr.signal_names()) do
    >>  table.insert(signals, { name = k, value = v })
    >> end
    > table.sort(signals, function(a, b)
    >>  return a.value > end)
    > for _, s in ipairs(signals) do
    >>  print(string.format('% 2i: %s', s.value, s.name))
    >> end
     1: SIGHUP
     2: SIGINT
     3: SIGQUIT
     4: SIGILL
     5: SIGTRAP
     6: SIGIOT
     6: SIGABRT
     7: SIGBUS
     8: SIGFPE
     9: SIGKILL
    10: SIGUSR1
    11: SIGSEGV
    12: SIGUSR2
    13: SIGPIPE
    14: SIGALRM
    15: SIGTERM
    16: SIGSTKFLT
    17: SIGCHLD
    17: SIGCLD
    18: SIGCONT
    19: SIGSTOP
    20: SIGTSTP
    21: SIGTTIN
    22: SIGTTOU
    23: SIGURG
    24: SIGXCPU
    25: SIGXFSZ
    26: SIGVTALRM
    27: SIGPROF
    28: SIGWINCH
    29: SIGPOLL
    29: SIGIO
    30: SIGPWR
    31: SIGSYS

After creating the above table I was surprised to see several numbers which
have two names in the above output, but after looking up the names it turns
out that these are just synonyms.

Note that just because a signal is included in this table doesn't
necessarily mean the signal is usable from Lua! For example [SIGALRM]
[sigalrm] is only useful when you can call the alarm() function defined by
[POSIX][posix] but that function isn't exposed by the Apache Portable
Runtime (you can use [lalarm] [lalarm] instead in this case).

[sigalrm]: http://en.wikipedia.org/wiki/SIGALRM
[posix]: http://en.wikipedia.org/wiki/POSIX

## String routines

###  `apr.strnatcmp(left, right) → status`

Do a [natural order comparison] [natsort] of two strings. Returns <tt>*true*</tt> when
the <tt>*left*</tt> string is less than the <tt>*right*</tt> string, <tt>*false*</tt> otherwise. This
function can be used as a callback for Lua's standard library function
[table.sort()](http://www.lua.org/manual/5.1/manual.html#pdf-table.sort).

    > -- the canonical example:
    > list = { 'rfc1.txt', 'rfc2086.txt', 'rfc822.txt' }
    > -- collate order:
    > table.sort(list)
    > for _, name in ipairs(list) do print(name) end
    rfc1.txt
    rfc2086.txt
    rfc822.txt
    > -- natural order:
    > table.sort(list, apr.strnatcmp)
    > for _, name in ipairs(list) do print(name) end
    rfc1.txt
    rfc822.txt
    rfc2086.txt

[natsort]: http://sourcefrog.net/projects/natsort/

*This function is not binary safe.*

###  `apr.strnatcasecmp(left, right) → status`

Like [apr.strnatcmp()](#apr.strnatcmp), but ignores the case of the strings.

*This function is not binary safe.*

###  `apr.strfsize(number [, padding]) → readable`

Format a binary size positive <tt>*number*</tt> to a compacted human readable string.
If the optional <tt>*padding*</tt> argument evaluates to <tt>*true*</tt> the resulting string
will be padded with spaces to make it four characters wide, otherwise no
padding will be applied.

    > = apr.strfsize(1024)
    '1.0K'
    > = apr.strfsize(1024 ^ 2)
    '1.0M'
    > = apr.strfsize(1024 ^ 3)
    '1.0G'

Here's a simplified implementation of the [UNIX] [unix] command `ls -l
--human-readable` which makes use of the <tt>*padding*</tt> argument to nicely line up
 the fields following the size:

    function ls(dirpath)
      local directory = assert(apr.dir_open(dirpath))
      for info in directory:entries() do
        io.write(info.protection, ' ')
        io.write(info.user, ' ')
        io.write(info.group, ' ')
        io.write(apr.strfsize(info.size, true), ' ')
        io.write(apr.time_format('%Y-%m-%d %H:%I', info.ctime), ' ')
        io.write(info.name, '\n')
      end
      assert(directory:close())
    end

This is what the result looks like for the [source code directory] [srcdir]
of the Lua/APR project:

    > ls 'lua-apr/src'
    rw-r--r-- peter peter 5.4K 2011-01-02 22:10 apr.lua
    rw-r--r-- peter peter 4.7K 2011-01-02 06:06 base64.c
    rw-r--r-- peter peter  11K 2010-10-27 13:01 buffer.c
    rw-r--r-- peter peter  13K 2011-01-02 21:09 crypt.c
    rw-r--r-- peter peter 2.8K 2010-12-31 01:01 date.c
    rw-r--r-- peter peter 9.4K 2011-01-01 16:04 dbm.c
    rw-r--r-- peter peter 2.5K 2010-09-25 23:11 env.c
    rw-r--r-- peter peter  17K 2011-01-02 22:10 errno.c
    rw-r--r-- peter peter  10K 2011-01-02 22:10 filepath.c
    rw-r--r-- peter peter 1.9K 2011-01-02 04:04 fnmatch.c
    rw-r--r-- peter peter  12K 2010-12-31 01:01 io_dir.c
    rw-r--r-- peter peter  25K 2011-01-02 04:04 io_file.c
    rw-r--r-- peter peter  17K 2010-12-31 01:01 io_net.c
    rw-r--r-- peter peter 4.6K 2011-01-02 22:10 io_pipe.c
    rw-r--r-- peter peter  11K 2011-01-02 11:11 lua_apr.c
    rw-r--r-- peter peter 9.0K 2011-01-02 11:11 lua_apr.h
    rw-r--r-- peter peter 6.9K 2010-12-29 14:02 permissions.c
    rw-r--r-- peter peter  26K 2011-01-02 22:10 proc.c
    rw-r--r-- peter peter 866  2010-10-23 00:12 refpool.c
    rw-r--r-- peter peter 4.8K 2010-12-29 14:02 stat.c
    rw-r--r-- peter peter 3.5K 2011-01-02 22:10 str.c
    rw-r--r-- peter peter 9.8K 2010-12-31 01:01 time.c
    rw-r--r-- peter peter 4.7K 2010-09-25 23:11 uri.c
    rw-r--r-- peter peter 2.5K 2010-09-25 23:11 user.c
    rw-r--r-- peter peter 2.9K 2010-10-22 19:07 uuid.c
    rw-r--r-- peter peter 3.8K 2011-01-02 04:04 xlate.c

Note: It seems that [apr.strfsize()](#apr.strfsize) doesn't support terabyte range sizes.

[srcdir]: https://github.com/xolox/lua-apr/tree/master/src

###  `apr.tokenize_to_argv(cmdline) → arguments`

Convert the string <tt>*cmdline*</tt> to a table of arguments. On success the table of
arguments is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

*This function is not binary safe.*

## Multi threading

This is an experimental multi threading module that makes it possible to
execute Lua functions in dedicated [Lua states] [Lua_state] and [operating
system threads] [threading]. When you create a thread you can pass it any
number of arguments and when a thread exits it can return any number of
return values. For details about supported Lua values see the documentation
of the [serialization](#serialization) module.

Please consider the following issues when using this module:

 - When you pass a userdata object to another thread you shouldn't use it
   from the original thread after that, because the Lua/APR binding doesn't
   protect object access with a thread safe lock. This will probably be
   fixed in the near future (hey, I said it was experimental)

 - When you start a thread and let it get garbage collected without having
   called [thread:join()](#thread:join), the thread will be joined for you (because
   failing to do so while the main thread is terminating can crash the
   process)

[Lua_state]: http://www.lua.org/manual/5.1/manual.html#lua_State
[threading]: http://en.wikipedia.org/wiki/Thread_%28computer_science%29
[libc]: http://en.wikipedia.org/wiki/C_standard_library

###  `apr.thread(f [, ...]) → thread`

Execute the Lua function <tt>*f*</tt> in a dedicated Lua state and operating system
thread. Any extra arguments are passed onto the function. On success a
thread object is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned. You can use [thread:join()](#thread:join) to wait for the thread to finish and
get the return values of the thread function.

*This function is binary safe.*

###  `apr.thread_yield() → nothing`

Force the current thread to yield the processor. This causes the currently
executing thread to temporarily pause and allow other threads to execute.

###  `thread:status() → status`

Returns a string describing the state of the thread:

 - `'running'`: the thread is currently running
 - `'done'`: the thread terminated successfully
 - `'error'`: the thread encountered an error

###  `thread:join() → status [, result, ...]`

Block until a thread stops executing and return its result. If the thread
terminated with an error a <tt>*nil*</tt> followed by an error message is returned,
otherwise <tt>*true*</tt> is returned, followed by any return values of the thread
function.

*This function is binary safe.*

## Thread queues

The valid types that can be transported through thread queues are documented
under the [serialization](#serialization) module. The example of a [multi
threaded webserver](#example_multi_threaded_webserver) uses a thread queue
to pass sockets between the main server thread and several worker threads.

###  `apr.thread_queue([capacity]) → queue`

Create a [FIFO] [fifo] [queue] [wp:queue]. The optional argument <tt>*capacity*</tt>
controls the maximum size of the queue and defaults to 1. On success the
queue object is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

The capacity of a thread queue cannot be changed after construction.

[wp:fifo]: http://en.wikipedia.org/wiki/FIFO
[wp:queue]: http://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29

###  `queue:push(value [, ...]) → status`

Add a tuple of one or more Lua values to the queue. This call will block if
the queue is full. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by
an error message and error code is returned:

 - `'EINTR'`: the blocking was interrupted (try again)
 - `'EOF'`: the queue has been terminated

*This function is binary safe.*

###  `queue:pop() → value [, ...]`

Get one or more Lua values from the queue. This call will block if the queue
is empty. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error
message and error code is returned:

 - `'EINTR'`: the blocking was interrupted (try again)
 - `'EOF'`: the queue has been terminated

*This function is binary safe.*

###  `queue:trypush(value [, ...]) → status`

Add a tuple of one or more Lua values to the queue. This call doesn't block
if the queue is full. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed
by an error message and error code is returned:

 - `'EINTR'`: the blocking was interrupted (try again)
 - `'EAGAIN'`: the queue is full
 - `'EOF'`: the queue has been terminated

*This function is binary safe.*

###  `queue:trypop() → value [, ...]`

Get a tuple of Lua values from the queue. This call doesn't block if the
queue is empty. On success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an
error message and error code is returned:

 - `'EINTR'`: the blocking was interrupted (try again)
 - `'EAGAIN'`: the queue is empty
 - `'EOF'`: the queue has been terminated

*This function is binary safe.*

###  `queue:interrupt() → status`

Interrupt all the threads blocking on this queue. On success <tt>*true*</tt> is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

###  `queue:terminate() → status`

Terminate the queue, sending an interrupt to all the blocking threads. On
success <tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

###  `queue:close() → status`

Close the handle <tt>*queue*</tt> and (if no other threads are using the queue)
destroy the queue and release the associated memory. This function always
returns <tt>*true*</tt> (it cannot fail).

This will be done automatically when the <tt>*queue*</tt> object is garbage collected
which means you don't need to call this unless you want to reclaim memory as
soon as possible.

## Time routines

Lua represents dates as numbers though the meaning of these numbers is not
specified. The manual does state (in the documentation for [os.time()](http://www.lua.org/manual/5.1/manual.html#pdf-os.time)) that
on [POSIX] [posix], Windows and some other systems these numbers count the
number of seconds since some given start time called the epoch. This epoch
is 00:00:00 January 1, 1970 [UTC] [utc]. The Apache Portable Runtime
[represents] [apr_time_t] dates as the number of microseconds since that
same epoch. As a compromise between the two units Lua/APR uses seconds but
supports sub-second resolution in the decimal part of floating point numbers
(see [this thread] [2007-03] on [lua-l] [lua-l] for discussion about the
API).

[posix]: http://en.wikipedia.org/wiki/POSIX
[apr_time_t]: http://apr.apache.org/docs/apr/trunk/group__apr__time.html#gdb4bde16055748190eae190c55aa02bb
[2007-03]: http://lua-users.org/lists/lua-l/2007-03/threads.html#00309
[lua-l]: http://lua-users.org/lists/lua-l/

###  `apr.sleep(seconds) → nothing`

Sleep for the specified number of <tt>*seconds*</tt>. Sub-second resolution is
supported so you can for example give 0.5 to sleep for half a second. This
function may sleep for longer than the specified time because of platform
limitations.

###  `apr.time_now() → time`

Get the current time as the number of seconds since 00:00:00 January 1, 1970
[UTC] [utc]. If Lua is compiled with floating point support then more
precision will be available in the decimal part of the returned number.

###  `apr.time_explode([time [, timezone]]) → components`

Convert the numeric value <tt>*time*</tt> (current time if none given) to its human
readable components. If <tt>*timezone*</tt> isn't given or evaluates to <tt>*false*</tt> the
local timezone is used. If its a number then this number is used as the
offset in seconds from [GMT] [gmt]. The value <tt>*true*</tt> is treated the same as 0,
i.e. GMT. On success the table of components is returned, otherwise a <tt>*nil*</tt>
followed by an error message is returned. The resulting table contains the
following fields:

 - `usec` is the number of microseconds past `sec`
 - `sec` is the number of seconds past `min` (0-61)
 - `min` is the number of minutes past `hour` (0-59)
 - `hour` is the number of hours past midnight (0-23)
 - `day` is the day of the month (1-31)
 - `month` is the month of the year (0-11).
 - `year` is the year since 1900
 - `wday` is the number of days since Sunday (0-6)
 - `yday` is the number of days since January 1 (0-365)
 - `gmtoff` is the number of seconds east of [UTC] [utc]
 - `isdst` is <tt>*true*</tt> when [daylight saving time] [dst] is in effect

All of these fields are numbers except for `isdst` which is a boolean.
Here's an example of the output returned by [apr.time\_explode()](#apr.time_explode):

    > -- Note that numeric dates are always in UTC while tables with
    > -- date components are in the local timezone by default.
    > components = apr.time_explode(1032030336.18671)
    > = components
    {
     usec = 186710,
     sec = 36,
     min = 5,
     hour = 21,
     day = 14,
     month = 9,
     year = 2002,
     wday = 7,
     yday = 257,
     gmtoff = 7200, -- my local timezone
     isdst = true,
    }
    > -- To convert a table of date components back into a number
    > -- you can use the apr.time_implode() function as follows:
    > = apr.time_implode(components)
<PHONE_NUMBER>.18671

[gmt]: http://en.wikipedia.org/wiki/Greenwich_Mean_Time
[utc]: http://en.wikipedia.org/wiki/Coordinated_Universal_Time
[dst]: http://en.wikipedia.org/wiki/Daylight_saving_time

###  `apr.time_implode(components) → time`

Convert a table of time <tt>*components*</tt> to its numeric value. On success the
time is returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.
See [apr.time\_explode()](#apr.time_explode) for a list of supported components.

###  `apr.time_format(format [, time]) → formatted`

Format <tt>*time*</tt> (current time if none given) according to string <tt>*format*</tt>. On
success the formatted time is returned, otherwise a <tt>*nil*</tt> followed by an error
message is returned. The two special formats `'ctime'` and `'rfc822'` result
in a fixed length string of 24 or 29 characters in length. The <tt>*time*</tt>
argument may be either a number or a table with components like those
returned by [apr.time\_explode()](#apr.time_explode).

    > = apr.time_format('%Y-%m-%d %H:%I:%S', apr.time_now())
    '2010-09-25 17:05:08'
    > = apr.time_format('ctime', apr.time_now())
    'Sat Sep 25 17:26:22 2010'
    > = apr.time_format('rfc822', apr.time_now())
    'Sat, 25 Sep 2010 15:26:36 GMT'

*This function is not binary safe.*

## Uniform resource identifier parsing

###  `apr.uri_parse(uri) → components`

Parse the [Uniform Resource Identifier] [uri] <tt>*uri*</tt>. On success a table of
components is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned. The table of components can have the following fields, all
strings:

 - `scheme` is the part of the URI before `://` (as in `http`, `ftp`, etc.)
 - `user` is the user name, as in `scheme://user:pass@host:port/`
 - `password` is the password, as in `scheme://user:pass@host:port/`
 - `hostinfo` is the combined `[user[:password]@]hostname[:port]`
 - `hostname` is the host name or IP address
 - `port` is the port number
 - `path` is the request path (`/` if only `scheme://hostname` was given)
 - `query` is everything after a `?` in the path, if present
 - `fragment` is the trailing `#fragment` string, if present

[uri]: http://en.wikipedia.org/wiki/Uniform_Resource_Identifier

*This function is not binary safe.*

###  `apr.uri_unparse(components [, option]) → uri`

Convert a table of [URI] [uri] <tt>*components*</tt> into a URI string. On success the
URI string is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned. The list of fields in the <tt>*components*</tt> table is available in the
documentation for [apr.uri\_parse()](#apr.uri_parse). The argument <tt>*option*</tt> may be one of the
following:

 - `hostinfo` to unparse the components `[user[:password]@]hostname[:port]`
 - `pathinfo` to unparse the components `path[?query[#fragment]]`

*This function is not binary safe.*

###  `apr.uri_port_of_scheme(scheme) → port`

Return the default port for the given [URI] [uri] <tt>*scheme*</tt> string. [Since at
least APR 1.2.8] [uri_ports] the following schemes are supported: `acap`,
`ftp`, `gopher`, `http`, `https`, `imap`, `ldap`, `nfs`, `nntp`, `pop`,
`prospero`, `rtsp`, `sip`, `snews`, `ssh`, `telnet`, `tip`, `wais`,
`z39.50r` and `z39.50s`.

[uri_ports]: http://svn.apache.org/viewvc/apr/apr/trunk/uri/apr_uri.c?view=markup#l43

## User/group identification

###  `apr.user_get() → username, groupname`

Get the username and groupname of the calling process. On success the
username and groupname are returned, otherwise a <tt>*nil*</tt> followed by an error
message is returned.

*This function is not binary safe.*

###  `apr.user_homepath_get(username) → homepath`

Get the [home directory] [home] for the named user. On success the directory
pathname is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

[home]: http://en.wikipedia.org/wiki/Home_directory

*This function is not binary safe.*

## Universally unique identifiers

[Universally unique identifiers] [uuid] are a standard for generating unique
strings that are specific to the machine on which they are generated and/or
the time at which they are generated. They can be used as primary keys in
databases and are used to uniquely identify file system types and instances
on modern operating systems. This is what a standard format UUID looks like:

    > = apr.uuid_format(apr.uuid_get())
    '0ad5d4a4-591e-41f7-8be4-07d7961a8079'

[uuid]: http://en.wikipedia.org/wiki/Universally_unique_identifier

###  `apr.uuid_get() → binary`

Generate and return a UUID as a binary string of 16 bytes.

###  `apr.uuid_format(binary) → formatted`

Format a UUID of 16 bytes following the standard format of 32 hexadecimal
digits, displayed in 5 groups separated by hyphens, in the form `8-4-4-4-12`
for a total of 36 characters, like `f5dc3464-6c8f-654e-a407-b15b7a30f038`.
On success the formatted UUID is returned, otherwise a <tt>*nil*</tt> followed by an
error message is returned.

###  `apr.uuid_parse(formatted) → binary`

Parse a standard format UUID and return its 16-byte equivalent. On success
the parsed UUID is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

## Character encoding translation

###  `apr.xlate(input, from, to) → translated`

Translate a string of text from one [character encoding] [charenc] to
another. The <tt>*from*</tt> and <tt>*to*</tt> arguments are strings identifying the source and
target character encoding. The special value `'locale'` indicates the
character set of the [current locale] [locale]. On success the translated
string is returned, otherwise a <tt>*nil*</tt> followed by an error message is
returned.

Which character encodings are supported by [apr.xlate()](#apr.xlate) is system dependent
because APR can use both the system's [iconv] [iconv] implementation and the
bundled library [apr-iconv] [apr_iconv]. To get a list of valid character
encoding names you can look through the [apr-iconv/ccs] [iconv_ccs] and
[apr-iconv/ces] [iconv_ces] directories (those are links to the web
interface of the apr-iconv repository).

[charenc]: http://en.wikipedia.org/wiki/Character_encoding
[locale]: http://en.wikipedia.org/wiki/Locale
[iconv]: http://en.wikipedia.org/wiki/Iconv
[apr_iconv]: http://apr.apache.org/docs/apr-iconv/trunk/group__apr__iconv.html
[iconv_ccs]: http://svn.apache.org/viewvc/apr/apr-iconv/trunk/ccs/
[iconv_ces]: http://svn.apache.org/viewvc/apr/apr-iconv/trunk/ces/

*This function is binary safe.*

## XML parsing

This module enables parsing of [XML] [xml] documents. Unlike [LuaExpat]
[lxp] the parsers returned by [apr.xml()](#apr.xml) don't use callbacks, instead they
parse XML into a [document object model] [dom] which is then exposed to Lua.
Because of this you can't use [apr.xml()](#apr.xml) for incremental parsing. To parse
an XML document you follow these steps:

1. Create an XML parser object by calling [apr.xml()](#apr.xml)
2. Parse the document by calling [xml\_parser:feed()](#xml_parser:feed) repeatedly until the
   full document has been parsed
3. Signal to the parser that the full document has been parsed by calling
   [xml\_parser:done()](#xml_parser:done)
4. Get the parse information by calling [xml\_parser:getinfo()](#xml_parser:getinfo)

Right now the only way to get the parse information is by calling
[xml\_parser:getinfo()](#xml_parser:getinfo) which converts the information to a Lua table
following the [Lua object model] [lom] defined by [LuaExpat] [lxp]. The Lua
object model is a mapping of XML to Lua tables that's not 100% complete
(e.g. it doesn't include namespaces) but makes it a lot easier to deal with
XML in Lua.

In the future this module might expose the full XML parse tree to Lua as
userdata objects, so that Lua has access to all parse information. This
would also make it possible to expose the [apr\_xml\_to\_text()]
[xml_to_text] function.

[xml]: http://en.wikipedia.org/wiki/XML
[lxp]: http://www.keplerproject.org/luaexpat/
[lom]: http://www.keplerproject.org/luaexpat/lom.html
[dom]: http://en.wikipedia.org/wiki/XML#Document_Object_Model_.28DOM.29
[xml_to_text]: http://apr.apache.org/docs/apr/trunk/group___a_p_r___util___x_m_l.html#g4485edce130dc1e9a3da3a633a75ffb3

###  `apr.xml([filename]) → xml_parser`

Create an XML parser. If the optional string <tt>*filename*</tt> is given, the file
pointed to by <tt>*filename*</tt> will be parsed. On success the parser object is
returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

*This function is not binary safe.*

###  `xml_parser:feed(input) → status`

Feed the string <tt>*input*</tt> into the XML parser. On success <tt>*true*</tt> is returned,
otherwise a <tt>*nil*</tt> followed by an error message is returned.

*This function is binary safe.*

###  `xml_parser:done() → status`

Terminate the parsing and save the resulting parse information. On success
<tt>*true*</tt> is returned, otherwise a <tt>*nil*</tt> followed by an error message is returned.

###  `xml_parser:geterror() → message`

Fetch additional error information from the parser after one of its methods
has failed.

###  `xml_parser:getinfo() → table`

Convert the parse information to a Lua table following the
[Lua Object Model] [lom] defined by [LuaExpat] [lxp].

###  `xml_parser:close() → status`

Close the XML parser and destroy any parse information. This will be done
automatically when the <tt>*xml_parser*</tt> object is garbage collected which means
you don't need to call this unless you want to reclaim memory as soon as
possible (e.g. because you just parsed a large XML document).

## Serialization

The Lua/APR binding contains a serialization function based on the [Metalua
table-to-source serializer] [metalua_serializer] extended to support
function upvalues and userdata objects created by the Lua/APR binding. The
following Lua values can be serialized:

 - strings, numbers, booleans, <tt>*nil*</tt> (scalars)
 - Lua functions (including upvalues)
 - userdata objects created by the Lua/APR binding
 - tables thereof. There is no restriction on keys; recursive and shared
   sub-tables are handled correctly.

Restrictions:

 - *Metatables and environments aren't saved*;
   this might or might not be what you want.

 - *If multiple functions share a scalar upvalue they will each get their
   own copy.* Because it is impossible to join upvalues of multiple
   functions in Lua 5.1 this won't be fixed any time soon.

The following functions in the Lua/APR binding internally use serialization
to transfer Lua functions and other values between operating system threads:

 - [apr.thread()](#apr.thread) and [thread:wait()](#thread:wait)
 - [queue:push()](#queue:push) and [queue:pop()](#queue:pop)
 - [queue:try\_push()](#queue:try_push) and [queue:try\_pop()](#queue:try_pop)

[metalua_serializer]: https://github.com/fab13n/metalua/blob/master/src/lib/serialize.lua

###  `apr.serialize(...) → string`

Serialize any number of Lua values (a tuple) into a source code string. When
passed to [apr.unserialize()](#apr.unserialize) this string results in a tuple of values that
is structurally identical to the original tuple.

###  `apr.unserialize(string) → ...`

Unserialize a source code string into one or more Lua values.

###  `apr.ref(object) → uuid`

Prepare the Lua/APR userdata <tt>*object*</tt> so that it can be referenced from
another Lua state in the same operating system process and associate a
[UUID] [uuid] with the object. The UUID is returned as a string. When you
pass this UUID to [apr.deref()](#apr.deref) you'll get the same object back. This only
works once, but of course you're free to generate another UUID for the same
object.

[uuid]: http://en.wikipedia.org/wiki/Universally_unique_identifier

###  `apr.deref(uuid) → object`

Convert a UUID that was previously returned by [apr.ref()](#apr.ref) into a userdata
object and return the object. You can only dereference a UUID once, but of
course you're free to generate another UUID for the same object.

## Miscellaneous functions

###  `apr.platform_get() → name`

Get the name of the platform for which the Lua/APR binding was compiled.
Returns one of the following strings:

 - `'UNIX'`
 - `'WIN32'`
 - `'NETWARE'`
 - `'OS2'`

Please note that the labels returned by [apr.platform\_get()](#apr.platform_get) don't imply
that these platforms are fully supported; the author of the Lua/APR binding
doesn't have NETWARE and OS2 environments available for testing.

###  `apr.version_get() → versions_table`

Get the versions of the libraries used by the Lua/APR binding.
Returns a table with one or more of the following fields:

 - **apr**: The version of the Apache Portable Runtime library. This field
   is always available.

 - **aprutil**: The version of the APR utility library. This field is only
   available when Lua/APR is compiled against APR and APR-util 1.x because
   in version 2.x the utility library has been absorbed back into the APR
   library; there is no longer a distinction between the APR core and APR
   utility libraries.

 - **apreq**: The version of the HTTP request parsing library. This field is
   only available when the libapreq2 library is installed.

Each field is a string containing three numbers separated by dots. These
numbers have the following meaning:

1. Major [API] [api] changes that can cause compatibility problems between
   the Lua/APR binding and APR library

2. Minor API changes that shouldn't impact existing functionality in the
   Lua/APR binding

3. Used exclusively for bug fixes

This function can be useful when you want to know whether a certain bug fix
has been applied to APR and/or APR-util or if you want to report a bug in
APR, APR-util or the Lua/APR binding.

If you're looking for the version of the Lua/APR binding you can use the
`apr._VERSION` string, but note that Lua/APR currently does not adhere to
the above versioning rules.

[api]: http://en.wikipedia.org/wiki/Application_programming_interface

###  `apr.os_default_encoding() → name`

Get the name of the system default character set as a string.

###  `apr.os_locale_encoding() → name`

Get the name of the current locale character set as a string. If the current
locale's data cannot be retrieved on this system, the name of the system
default character set is returned instead.

###  `apr.type(object) → name`

Return the type of a userdata object created by the Lua/APR binding. If
<tt>*object*</tt> is of a known type one of the following strings will be returned,
otherwise nothing is returned:

 - `'file'`
 - `'directory'`
 - `'socket'`
 - `'thread'`
 - `'process'`
 - `'dbm'`
 - `'database driver'`
 - `'prepared statement'`
 - `'result set'`
 - `'memcache client'`
 - `'memcache server'`
 - `'md5 context'`
 - `'sha1 context'`
 - `'xml parser'`

## File system permissions

The Apache Portable Runtime represents file system permissions somewhat
similar to those of [UNIX] [unix]. There are three categories of
permissions: the user, the group and everyone else (the world). Each
category supports read and write permission bits while the meaning of the
third permission bit differs between categories.

[unix]: http://en.wikipedia.org/wiki/Unix

### How Lua/APR presents permissions

The Lua/APR binding uses a string of 9 characters to represent file system
permissions such as those returned by [apr.stat()](#apr.stat). Here's an example:

    > = apr.stat('.', 'protection')
    'rwxr-xr-x'

This is the syntax of these permissions strings:

 - Character 1: `r` if the user has read permissions, `-` otherwise
 - Character 2: `w` if the user has write permissions, `-` otherwise
 - Character 3: `x` if the user has execute permissions, `S` if the user
   has set user id permissions or `s` if the user has both permissions
 - Characters 4..6: the same respective permissions for the group
 - Characters 7..8: the same respective permissions for the world
 - Character 9: `x` if the world has execute permissions, `T` if the world
   has sticky permissions or `t` if the world has both permissions

As an example, `rwxrwx---` means the user and group have full permissions
while the world has none. Another example: `r-xr-xr-x` means no-one has
write permissions.

### How you can request permissions

When you need to request file system permissions for an operation like
[reading](#apr.file_open) or [copying](#apr.file_copy) a file there are two
string formats you can use. The first format is a string of nine characters
that lists each permission explicitly. This is the format documented above.

The second format is very flexible and is one of the formats accepted by the
Linux command line program [chmod] [chmod]. The permissions are split in
three groups with a one-letter code: user is `u`, group is `g` and world is
`o` (for "others"). One or more permissions can then be assigned to one or
more of these groups. Here's an example that requests read permission for
user, group and others: `ugo=r`. Now when you also need write permission for
user and group, you can use `ugo=r,ug=w`.

[chmod]: http://en.wikipedia.org/wiki/chmod

## Error handling

Most functions in the Lua/APR binding follow the Lua idiom of returning <tt>*nil*</tt>
followed by an error message string. These functions also return a third
argument which is the symbolic name of the error (or the error code in case
a symbolic name cannot be determined). The following symbolic names are
currently defined (there's actually a lot more but they shouldn't be
relevant when working in Lua):

 - `'ENOSTAT'`: APR was unable to perform a stat on the file
 - `'EBADDATE'`: APR was given an invalid date
 - `'EINVALSOCK'`: APR was given an invalid socket
 - `'ENOPROC'`: APR was not given a process structure
 - `'ENOTIME'`: APR was not given a time structure
 - `'ENODIR'`: APR was not given a directory structure
 - `'ENOTHREAD'`: APR was not given a thread structure
 - `'EBADIP'`: the specified IP address is invalid
 - `'EBADMASK'`: the specified netmask is invalid
 - `'EDSOOPEN'`: APR was unable to open the DSO object
 - `'EABSOLUTE'`: the given path was absolute
 - `'ERELATIVE'`: the given path was relative
 - `'EINCOMPLETE'`: the given path was neither relative nor absolute
 - `'EABOVEROOT'`: the given path was above the root path
 - `'EBADPATH'`: the given path was bad
 - `'EPATHWILD'`: the given path contained wildcards
 - `'ESYMNOTFOUND'`: could not find the requested symbol
 - `'EPROC_UNKNOWN'`: the given process was not recognized by APR
 - `'ENOTENOUGHENTROPY'`: APR could not gather enough [entropy] [entropy] to continue
 - `'TIMEUP'`: the operation did not finish before the timeout
 - `'INCOMPLETE'`: the operation was incomplete although some processing was performed and the results are partially valid
 - `'EOF'`: APR has encountered the end of the file
 - `'ENOTIMPL'`: the APR function has not been implemented on this platform, either because nobody has gotten to it yet, or the function is impossible on this platform
 - `'EMISMATCH'`: two passwords do not match
 - `'EACCES'`: permission denied
 - `'EEXIST'`: file exists
 - `'ENAMETOOLONG'`: path name is too long
 - `'ENOENT'`: no such file or directory
 - `'ENOTDIR'`: not a directory
 - `'ENOSPC'`: no space left on device
 - `'ENOMEM'`: not enough memory
 - `'EMFILE'`: too many open files
 - `'ENFILE'`: file table overflow
 - `'EBADF'`: bad file number
 - `'EINVAL'`: invalid argument
 - `'ESPIPE'`: illegal seek
 - `'EAGAIN'`: operation would block
 - `'EINTR'`: interrupted system call
 - `'ENOTSOCK'`: socket operation on a non-socket
 - `'ECONNREFUSED'`: connection refused
 - `'EINPROGRESS'`: operation now in progress
 - `'ECONNABORTED'`: software caused connection abort
 - `'ECONNRESET'`: connection Reset by peer
 - `'ETIMEDOUT'`: operation timed out (deprecated)
 - `'EHOSTUNREACH'`: no route to host
 - `'ENETUNREACH'`: network is unreachable
 - `'EFTYPE'`: inappropriate file type or format
 - `'EPIPE'`: broken pipe
 - `'EXDEV'`: cross device link
 - `'ENOTEMPTY'`: directory not empty
 - `'EAFNOSUPPORT'`: address family not supported

Note that the error descriptions above were copied verbatim from [apr_errno.h] [errno].

[entropy]: http://en.wikipedia.org/wiki/Entropy_%28computing%29
[errno]: http://svn.apache.org/viewvc/apr/apr/trunk/include/apr_errno.h?view=markup

## Example: HTTP client

The following Lua script implements a minimal [HTTP client] [http] which can
be used to download a given [URL] [url] on the command line (comparable to
[wget] [wget] and [curl] [curl]):

    $ FILE=lua-5.1.4.tar.gz
    $ URL=http://www.lua.org/ftp/$FILE
    $ time curl -s $URL > $FILE
    0,01s user 0,02s system 6% cpu 0,465 total
    $ time lua examples/download.lua $URL > $FILE
    0,03s user 0,02s system 9% cpu 0,549 total

Note that this script and Lua/APR in general are a bit handicapped in that
they don't support [HTTPS] [https] because the Apache Portable Runtime does
not support encrypted network communication.

[url]: http://en.wikipedia.org/wiki/Uniform_Resource_Locator
[wget]: http://en.wikipedia.org/wiki/wget
[curl]: http://en.wikipedia.org/wiki/cURL
[https]: http://en.wikipedia.org/wiki/HTTPS

    local apr = require 'apr'

    -- Report errors without stack traces.
    local function assert(...)
      local status, message = ...
      if not status then
        io.stderr:write('Error: ', message or '(no message)', '\n')
        os.exit(1)
      end
      return ...
    end

    local function getpage(url)
      local components = assert(apr.uri_parse(url))
      assert(components.scheme == 'http', "invalid protocol!")
      local port = assert(components.port or apr.uri_port_of_scheme(components.scheme))
      local socket = assert(apr.socket_create())
      assert(socket:connect(components.hostname, port))
      local pathinfo = assert(apr.uri_unparse(components, 'pathinfo'))
      assert(socket:write('GET ', pathinfo, ' HTTP/1.0\r\n',
                          'Host: ', components.hostname, '\r\n',
                          '\r\n'))
      local statusline = assert(socket:read(), 'HTTP response missing status line!')
      local protocol, statuscode, reason = assert(statusline:match '^(%S+)%s+(%S+)%s+(.-)$')
      local redirect = statuscode:find '^30[123]$'
      for line in socket:lines() do
        local name, value = line:match '^(%S+):%s+(.-)\r?$'
        if name and value then
          if redirect and name:lower() == 'location' then
            io.stderr:write("Following redirect to ", value, " ..\n")
            return getpage(value)
          end
        else
          return (assert(socket:read '*a', 'HTTP response missing body?!'))
        end
      end
      if statuscode ~= '200' then error(reason) end
    end

    local usage = "Please provide a URL to download as argument"
    io.write(getpage(assert(arg and arg[1], usage)))

    -- vim: ts=2 sw=2 et

## Example: Single threaded webserver

The following script implements a minimalistic webserver on top of Lua/APR
[network sockets] [socket_module]. It should work out of the box on Windows
and UNIX, although you might get a prompt from your firewall. Once the server
is running you can open <http://localhost:8080> in your web browser to see
the server in action. Because the server is single threaded I was curious how
bad it would perform, so I tested it with [ApacheBench] [ab]:

    $ lua examples/webserver.lua &
    $ ab -qt5 http://localhost:8080/ | grep 'Requests per second\|Transfer rate'
    Requests per second:    3672.19 [#/sec] (mean)
    Transfer rate:          2201.88 [Kbytes/sec] received

That's not too bad for 40 lines of code! For more complex webservers see the
[multi threaded] [threaded_server] and [asynchronous] [async_server]
webserver examples.

*Note that all benchmarks are run on my Compaq Presario CQ60 laptop (which
features an Intel Core 2 Duo T5800 processor clocked at 2 GHz and 3 GB of
RAM) and that the Lua/APR binding was compiled without debugging symbols.*

[socket_module]: #network_i_o_handling
[ab]: http://en.wikipedia.org/wiki/ApacheBench
[threaded_server]: #example_multi_threaded_webserver
[async_server]: #example_asynchronous_webserver

    local port_number = tonumber(arg[1]) or 8080
    local bind_address = arg[2] or '*'

    -- Load the Lua/APR binding.
    local apr = require 'apr'

    -- Initialize the server socket.
    local server = assert(apr.socket_create())
    assert(server:bind(bind_address, port_number))
    assert(server:listen(1))
    print("Running webserver on http://" .. bind_address .. ":" .. port_number .. " ..")

    -- Wait for clients to serve.
    local visitor = 1
    local template = [[

        <title>Hello from Lua/APR!</title>

Hello from Lua/APR!

You are visitor number %010i.

The headers provided by your web browser:

%s

    ]]
    while true do
      local status, message = pcall(function()
        local client = assert(server:accept())
        -- Read the HTTP request so that the client can receive data.
        local request = assert(client:read(), "Failed to receive request from client!")
        local method, location, protocol = assert(request:match '^(%w+)%s+(%S+)%s+(%S+)')
        local headers = {}
        for line in client:lines() do
          local name, value = line:match '^(%S+):%s+(.-)$'
          if not name then break end
          table.insert(headers, '
' .. name .. ':

' .. value .. '
')
        end
        -- Generate the HTTP response.
        table.sort(headers)
        content = template:format(visitor, table.concat(headers))
        client:write(protocol, ' 200 OK\r\n',
                     'Content-Type: text/html\r\n',
                     'Content-Length: ' .. #content .. '\r\n',
                     'Connection: close\r\n',
                     '\r\n',
                     content)
        assert(client:close())
        visitor = visitor + 1
      end)
      if not status then
        print('Error while serving request:', message)
      end
    end

    -- vim: ts=2 sw=2 et

## Example: Multi threaded webserver

Thanks to the [multi threading] [threading_module] and [thread queue]
[thread_queues] modules in the Apache Portable Runtime it is possible to
improve the performance of the [single threaded webserver] [simple_server]
from the previous example. Here is a benchmark of the multi threaded code
listed below (again using [ApacheBench] [ab], but now with the `-c`
argument):

    $ CONCURRENCY=4
    $ lua examples/threaded-webserver.lua $CONCURRENCY &
    $ ab -qt5 -c$CONCURRENCY http://localhost:8080/ | grep 'Requests per second\|Transfer rate'
    Requests per second:    9210.72 [#/sec] (mean)
    Transfer rate:          5594.79 [Kbytes/sec] received

Comparing these numbers to the benchmark of the [single threaded webserver]
[simple_server] we can see that the number of requests per second went from
3670 to 9210, more than doubling the throughput of the webserver on a dual
core processor. If you want to know how we can make it even faster, have a
look at the [asynchronous webserver] [async_server] example.

[threading_module]: #multi_threading
[thread_queues]: #thread_queues
[simple_server]: #example_single_threaded_webserver
[ab]: http://en.wikipedia.org/wiki/ApacheBench
[thread_pool]: http://en.wikipedia.org/wiki/Thread_pool_pattern
[async_server]: #example_asynchronous_webserver

    local num_threads = tonumber(arg[1]) or 2
    local port_number = tonumber(arg[2]) or 8080

    local template = [[

        <title>Hello from Lua/APR!</title>

Hello from Lua/APR!

This web page was served by worker %i.

The headers provided by your web browser:

%s

    ]]

    -- Load the Lua/APR binding.
    local apr = require 'apr'

    -- Initialize the server socket.
    local server = assert(apr.socket_create())
    assert(server:bind('*', port_number))
    assert(server:listen(num_threads * 2))
    print("Running webserver with " .. num_threads .. " client threads on http://localhost:" .. port_number .. " ..")

    -- Create the thread queue (used to pass sockets between threads).
    local queue = apr.thread_queue(num_threads)

    -- Define the function to execute in each child thread.
    function worker(thread_id, queue, template)
      pcall(require, 'luarocks.require')
      local apr = require 'apr'
      while true do
        local client, msg, code = queue:pop()
        assert(client or code == 'EINTR', msg)
        if client then
          local status, message = pcall(function()
            local request = assert(client:read(), "Failed to receive request from client!")
            local method, location, protocol = assert(request:match '^(%w+)%s+(%S+)%s+(%S+)')
            local headers = {}
            for line in client:lines() do
              local name, value = line:match '^(%S+):%s+(.-)$'
              if not name then
                break
              end
              table.insert(headers, '
' .. name .. ':

' .. value .. '
')
            end
            table.sort(headers)
            local content = template:format(thread_id, table.concat(headers))
            client:write(protocol, ' 200 OK\r\n',
                         'Content-Type: text/html\r\n',
                         'Content-Length: ' .. #content .. '\r\n',
                         'Connection: close\r\n',
                         '\r\n',
                         content)
            assert(client:close())
          end)
          if not status then
            print('Error while serving request:', message)
          end
        end
      end
    end

    -- Create the child threads and keep them around in a table (so that they are
    -- not garbage collected while we are still using them).
    local pool = {}
    for i = 1, num_threads do
      table.insert(pool, apr.thread(worker, i, queue, template))
    end

    -- Enter the accept() loop in the parent thread.
    while true do
      local status, message = pcall(function()
        local client = assert(server:accept())
        assert(queue:push(client))
      end)
      if not status then
        print('Error while serving request:', message)
      end
    end

    -- vim: ts=2 sw=2 et

## Example: Asynchronous webserver

We can do even better than the performance of the multi threaded webserver by
using the [APR pollset module] [pollset_module]. The following webserver uses
asynchronous network communication to process requests from multiple clients
'in parallel' without using multiple threads or processes. Here is a
benchmark of the asynchronous code listed below (again using [ApacheBench]
[ab] with the `-c` argument):

    $ CONCURRENCY=4
    $ POLLSET_SIZE=10
    $ lua examples/async-webserver.lua $POLLSET_SIZE 8080 cheat &
    $ ab -qt5 -c$CONCURRENCY http://localhost:8080/ | grep 'Requests per second\|Transfer rate'
    Requests per second:    11312.64 [#/sec] (mean)
    Transfer rate:          6219.74 [Kbytes/sec] received

The [single threaded webserver] [simple_server] handled 3670 requests per
second, the [multi threaded webserver] [threaded_server] handled 9210
requests per second and the asynchronous webserver below can handle 11310
requests per second. Actually in the above benchmark I may have cheated a bit
(depending on whether your goal is correct usage or performance). When I
started writing this asynchronous server example I didn't bother to add
writable sockets to the pollset, instead I handled the request and response
once the client socket was reported as readable by the pollset. Later on I
changed the code to handle writing using the pollset and I noticed that the
performance dropped. This is probably because the example is so contrived.
Anyway here's the performance without cheating:

    $ lua examples/async-webserver.lua $POLLSET_SIZE 8080 &
    $ ab -qt5 -c$CONCURRENCY http://localhost:8888/ | grep 'Requests per second\|Transfer rate'
    Requests per second:    9867.17 [#/sec] (mean)
    Transfer rate:          5425.03 [Kbytes/sec] received

Now follows the implementation of the asynchronous webserver example:

[pollset_module]: #pollset
[ab]: http://en.wikipedia.org/wiki/ApacheBench
[simple_server]: #example_single_threaded_webserver
[threaded_server]: #example_multi_threaded_webserver

    local pollset_size = tonumber(arg[1]) or 10
    local port_number = tonumber(arg[2]) or 8080
    local cheat = arg[3] == 'cheat' -- cheat to make it faster?

    local template = [[

        <title>Hello from Lua/APR!</title>

Hello from Lua/APR!

The headers provided by your web browser:

%s

    ]]

    -- Load the Lua/APR binding.
    local apr = require 'apr'

    -- Initialize the server socket.
    local server = assert(apr.socket_create())
    assert(server:bind('*', port_number))
    assert(server:listen(pollset_size))

    -- Create the pollset.
    local pollset = assert(apr.pollset(pollset_size))
    assert(pollset:add(server, 'input'))

    -- Use a table indexed with socket objects to keep track of "sessions".
    local sessions = setmetatable({}, {__mode='k'})

    -- Enter the I/O loop.
    print("Running webserver on http://localhost:" .. port_number .. " ..")
    while true do
      local readable, writable = assert(pollset:poll(-1))
      -- Process requests.
      for _, socket in ipairs(readable) do
        if socket == server then
          local client = assert(server:accept())
          assert(pollset:add(client, 'input'))
        else
          local request = assert(socket:read(), "Failed to receive request from client!")
          local method, location, protocol = assert(request:match '^(%w+)%s+(%S+)%s+(%S+)')
          local headers = {}
          for line in socket:lines() do
            local name, value = line:match '^(%S+):%s+(.-)$'
            if not name then
              break
            end
            table.insert(headers, '
' .. name .. ':

' .. value .. '
')
          end
          table.sort(headers)
          local content = template:format(table.concat(headers))
          assert(socket:write(
            protocol, ' 200 OK\r\n',
            'Content-Type: text/html\r\n',
            'Content-Length: ', #content, '\r\n',
            'Connection: close\r\n',
            '\r\n'))
          if cheat then
            assert(socket:write(content))
            assert(pollset:remove(socket))
            assert(socket:close())
          else
            sessions[socket] = content
            assert(pollset:remove(socket))
            assert(pollset:add(socket, 'output'))
          end
        end
      end
      if not cheat then
        -- Process responses.
        for _, socket in ipairs(writable) do
          assert(socket:write(sessions[socket]))
          -- I don't like that when I switch the order of these
          -- calls, it breaks... Seems like a fairly big gotcha.
          assert(pollset:remove(socket))
          assert(socket:close())
        end
      end
    end

    -- vim: ts=2 sw=2 et

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
Raspbian Docker
=========

This role installs Docker on Raspbian operating systems following the official procedure at [Get Docker CE for Debian](https://docs.docker.com/install/linux/docker-ce/debian/#upgrade-docker-ce-1).

Requirements
------------

Raspbian 9 (stretch) or later. It hasn't been tested with older versions, but that doesn't necessarily mean it can't work. Indeed, it should work with some older Raspbian versions.

Role Variables
--------------

This role has only two variables:
- **docker_version**: Optional. This is the Docker version you wish to install. If it's not specified, the latest version will be installed.
- **docker_users**: Optional. A list of users that are to be added to the `docker` group in order for them to be able to run docker commands without sudo privileges. Please check the [Docker Daemon attack surface](https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface) documentation for understanding the risks of adding users to the `docker` group.

Dependencies
------------

None.

Example Playbook
----------------

    - hosts: docker-servers
      roles:
         - { role: igvaquero18.raspbian-docker, docker_users: [ignacio] }

License
-------

BSD

Author Information
------------------

Ignacio Vaquero Guisasola.

DevOps Engineer at ING Spain.

[ivaqueroguisasola@gmail.com](mailto:ivaqueroguisasola@gmail.com).

repository: robertcrisan/raspbian-docker

repo_name: robertcrisan/raspbian-docker


text:
---
sidebar_position: 2
sidebar_label: "Store multiple puzzles"
title: "Store multiple crossword puzzles using a specialized collection in NEAR called a LookupMap"
---

import bookPagination from '/docs/assets/crosswords/paging-through-hashes-swing--pierced_staggg.near--pierced_stag.jpg';
import guardsAroundContract from '/docs/assets/crosswords/guards-contract-permissions--connoisseur_dane.near--connoisseurdane.png';

# Using collections

As mentioned in the previous chapter, the [online Rust Book](https://doc.rust-lang.org/stable/book) is a great reference for folks getting started with Rust, but there are concepts that differ when we're dealing with the blockchain. One of these differences is the use of collections.

The reference-level documentation of the Rust SDK explains this concept well:

:::note  Motivation for specialized collections
>Collections that offer an alternative to standard containers from [Rust's] std::collections::* by **utilizing the underlying blockchain trie storage more efficiently**.

>For example, the following smart contract does not work with state efficiently, because **it will load the entire HashMap at the beginning of the contract call**, and will save it entirely at the end, in cases when there is state modification. **This is fine for small number of elements, but very inefficient for large numbers**.

— [NEAR SDK reference documentation](https://docs.rs/near-sdk/latest/near_sdk/collections/index.html)
:::

In chapter 1, we set the crossword puzzle solution hash when we first deployed the contract and called the initialization method `new`, passing it. This would only allow us to have only one puzzle, but let's allow for many.

At a high level, let's discuss what we'll want to add if our contract is to store multiple crossword puzzles. First, we'll have the concept of many puzzles where some of them will have different states (unfinished and finished) and we'll want to know which ones are unsolved in quick way. Another thing, which is a general rule of thumb when writing smart contracts, is to anticipate what might happen if it gets a lot of usage. What if we end up with 10,000 crossword puzzles? How might that affect how many data structures we use and which ones?

## LookupMap and UnorderedSet

Let's try having two specialized NEAR collections:

1. A [LookupMap](https://docs.rs/near-sdk/latest/near_sdk/collections/struct.LookupMap.html) which will store key-value pairs. (Solution hash » Puzzle object)
2. An [UnorderedSet](https://docs.rs/near-sdk/latest/near_sdk/collections/struct.UnorderedSet.html) containing a set (list with no duplicates) of the solution hashes for puzzles which have not been solved yet.

As you look at the list of specialized collections in the Rust SDK, you might notice some begin with `Lookup` while others have `Unordered`. As is written in the reference documentation, the `Lookup` is non-iterable while the `Unordered` collections are iterable. This means if you will need to loop through the list of contents of this data structure, you'll likely use an iterable data structure. If you'll only ever be adding and retrieving data by the key, and the key will always be known, it's more efficient to use a non-iterable collection.

So why would we have two data structures here? Again, if we end up with a large number of puzzles, we might not be able to loop through all the puzzles, looking for ones that are unsolved. Because of the limit of gas execution per transaction, we must be conscious that there can be operations which will eventually exceed this limit. I suppose we could assume  that our `UnorderedSet` of unsolved puzzles wouldn't contain tens of thousands of puzzles. That's one way to avoid running into limits, but we could also learn how to utilize **pagination** through an iterable collection like an `UnorderedSet` which we'll get to later.

Think of our collection as having multiple pages of puzzle hashes.
Art by pierced_staggg.near

As we remember from the previous chapter, every smart contract has a primary struct containing the `#[near_bindgen]` macro.

:::note Naming the primary struct
Note in the [previous chapter](../01-basics/01-set-up-skeleton.md#start-writing-rust) we named our primary struct `Contract`, but in this chapter we'll call it `Crossword.`

The name of the struct doesn't matter and there's nothing special about naming it `Contract`, though you might see that convention used in several smart contracts on NEAR. We've named it something different simply to illustrate that there's no magic behind the scenes. This *does* mean, however, that our `impl` block will also be `Crossword`.
:::

Here's how our struct will look with the iterable and non-iterable NEAR collections:

```rust reference
https://github.com/near-examples/crossword-tutorial-chapter-2/blob/276217ad82c64c610148e998ec926942ba910a12/contract/src/lib.rs#L73-L79
```

Above, we have the `puzzles` and `unsolved_puzzles` fields which are collections.

We also have an `owner_id` so we can exercise a common pattern in smart contract development: implementing a rudimentary permission system which can restrict access to certain functions. We'll expand on this thought in a moment.

The snippet below shows the first method in the implementation of the `Crossword` struct, where the `new` function sets up these two specialized collections.

```rust reference
https://github.com/near-examples/crossword-tutorial-chapter-2/blob/276217ad82c64c610148e998ec926942ba910a12/contract/src/lib.rs#L81-L90
```

So during the initialization function (`new`) we're setting the `owner_id`. For our purposes the owner will likely be the contract itself, but there can be several reasons to have it be a DAO or another user. Next, let's look at the `b"c"` and `b"u"` bits for the collection fields.

## Collections have prefixes

Above, the `new` function is initializing the struct's fields by giving them a unique prefix. You can learn more about [the prefixes here](/sdk/rust/contract-structure/nesting#traditional-approach-for-unique-prefixes), but know that these prefixes (`c` and `u`) should be short and different.

Let's take a peek at how we'll add a new crossword puzzle. Note that there will be a new struct here, `Answer`, which we haven't defined yet. We'll also be introducing the concept of enums, like `PuzzleStatus::Solved` and `PuzzleStatus::Unsolved`. We'll be covering these in the next section.

Unlike the previous chapter where there was only one crossword puzzle, we'll be inserting into our new collections, so let's create a `new_puzzle` method.

```rust reference
https://github.com/near-examples/crossword-tutorial-chapter-2/blob/8ec941c82539e6eafa4971444e1da9e4819330d3/contract/src/lib.rs#L147-L163
```

Now we're set up to store multiple puzzles!

## Permissions or permissionless?

Guarding which accounts can enter the smart contract logic.
Art by connoisseur_dane.near

**Is NEAR permissionless?**

Yes.

**What did you mean by a permission system earlier, and what are the ways you can control permissions?**

There are two ways that permissions can be controlled:

1. In the smart contract code itself
2. When using function-call access keys

We'll get to the second topic in later in this chapter, but will focus on the first item.

As you can see in the previous snippet, the first thing that happens in the `new_puzzle` method is a check. It looks to see if the predecessor (the person who most recently called this method, sometimes the same as the signer) is the same as the `owner_id` that we set during the contract's initialization.

If someone else is trying to call `new_puzzle`, this check will fail and the smart contract will panic, going no further. This example is the simplest form of a permission. Much more complex system can exist for users. The SputnikDAO smart contracts, for instance, implement custom policies. It's up the smart contract developer to write their roles/policies and apply them to users. Sometimes an allow-list (or whitelist) is used.

In short, **any account with a full-access key can call any method on a smart contract**, but that doesn't mean the smart contract will let them continue execution. It's up to the developer to protect their functions with guards like the one in `new_puzzle`.

---

Let's dive into structs and enums next.

repository: think-in-universe/docs

gha_language: TypeScript

repo_name: think-in-universe/docs


text:
---
layout: post
title: "Freudian Psychology"
date: 2018-07-25
tags: [psychology, 85102, freud]
comments: true
---

# Defensive Mechanisms
- Repression - Banish anxiety-provoking thoughts from consciousness
- Reaction formation - Make unacceptable impulses look like their opposite
- Projection - Attribute threatening impulses to others
- Rationalization - Self-justifying explanations for behavior
- Displacement - Divert impulses to a more acceptable target
- Sublimation - Transformation of unacceptable impulses into socially valued motivations

# Freud
- Freud drew evidence from several sources
- Including errors people make in everyday life
- Also felt that dreams hold important clues about the unconscious mind
    - Latent content versus manifest content

# Critique of Freud
## Weekness
- ideas are implausible, unvalidated and contradict research
-  Offer after-the-fact-explanations

## Strengths - draw attention to
- Unconscious
- Struggle with anxiety and sexuality
- Conflict between biological impulses and social constraint

# Trait Perspective
- Sheldon's body types
    - Endomorph - relaxed, jolly
    - Mesomorph - bold, physically active
    - Ectomorph - high strung, solitary

# The "Big Five"
- Big Five distinct personality traits
    - Emotional stability
    - Extroversion
    - Openness
    - Agreeableness
    - Conscientiousness
- Partially derived by work from Cattell's use of factor analysis

# Assessing Traits
- Personality inventories
- Minnesota Multiphasic Personality Inventory (MMPI) Assesses psychological disorders
- Criticisms of Trait assessment
    - Behavior is influenced by the interaction of dispositions and the environment
    - Personality tests only mildly predict behavior

# Temperament
- Character emotional or behavioral pattern
- Twin studies of the Big Five dimensions confirm a high heritability
    - Extraversion - genetic influences depend on level of central nervous system reactivity, with introverts more reactive than extraverts
    - Sensation seeking and inhibited temperament

# Family and Personality
## Adpted children
- Zero correlation between adopted children and their adoptive parents
## TODO
- Copy the slid

# Humanistic Approach
- Emphasizes positive human motives
    - Self-actualizatoin rather than deficiency needs
- According to Carl Roger's self theory
    - Children only achieve solid sense of sef-worth if they've experienced a sense of unconditional positive regard

# Social Cognitive Approach
## Albert Bandura
- Role of experience
- Outcome expectations and self-efficiency
## Walter Mischel
- They way people interpret world around them
-  Competencies and self-regulatory plans

gha_language: HTML

gha_license_id: MIT


text:
## Summary

Side projects solving applications of the Rural Postman Problem using the [postman_problems] library.  Current examples leverage OSM (Open Street Maps) for building, optimizing and visualizing graphs.  Examples include:

1. **50 States Ride**:  Required edges are the state named avenues in DC.  Optional edges are all others roads and trails.  Many more details in the
accompanying blog post [here][rpp_blog_post].

2. **Sleeping Giant**: Required edges are the named trails in Sleeping Giant State Park (see [Giant master program]).  Optional edges are the non-required trails and roads.  More examples in the accompanying blog post [here][rpp_sg_osm_blogpost].

## 1. 50 States Ride

#### Graph

Derived from Open Street Maps data.  Edges are contracted to ease computation.  There are ~400 required edges in the final edgelist.

- required state avenues: **112 miles**
- connectors between required components: **12 miles**

#### Solution

The optimal route covers 160 miles: 124 miles of required road and 36 miles of optional roads and doublebacking.

See the [blog post][rpp_blog_post] for more visualizations and details on the approach.

[Here][rpp_50states_solution.geojson] is the route (geojson map).

[Here][rpp_50states_solution_csv] is the solution edgelist CSV with lat and lon and street names.

![pic](https://github.com/brooksandrew/postman_problems_examples/raw/master/50states/fig/50states_rpp_solution_edge_cnt.png)

#### Contents

- `50states/50states-blogpost.ipynb`: notebook solving and visualizing the problem
- `50states/rpp_solution.csv`: eulerian circuit solution solution to RPP

## 2. Sleeping Giant

#### Graph

For more details on the Sleeping Giant problem and graph, check out the blog post [here][rpp_sg_osm_blogpost].

#### Solution

The optimal route covers 30.7 miles: 25.6 of required trails and 5.1 miles of optional trails and doublebacking.

 ![pic](https://github.com/brooksandrew/postman_problems_examples/raw/master/sleepinggiant/fig/sleepinggiant_rpp_solution_edge_cnt.png)

## Project

#### Contents

- `environment.yml`: environment used to produce `50states-blogpost.ipynb`.
- `graph.py`: module consolidating heavy lifting for blog post

#### Resources

- [postman_problems]: Python package with RPP and CPP solvers
- [Blog post: 50 states RPP][rpp_blog_post]: solving and visualizing RPP with Leaflet using DC OSM data
- [Blog post: Sleeping Giant RPP][rpp_sg_osm_blogpost]: solving and visualizing RPP with Leaflet using OSM data.
- [Blog post: DataCamp]: Original blog post implementing CPP from scratch using Networkx 1.11
- [Blog post: Intro to Graph Optimization]: Same post as above, but modified for Networkx 2.0

[rpp_50states_solution.geojson]: https://github.com/brooksandrew/50states/blob/master/50states/maps/rpp_solution.geojson
[postman_problems]: https://github.com/brooksandrew/postman_problems

[rpp_50states_solution_csv]: https://github.com/brooksandrew/50states/blob/master/50states/rpp_solution.csv
[Blog post: DataCamp]: https://www.datacamp.com/community/tutorials/networkx-python-graph-tutorial
[Blog post: Intro to Graph Optimization]: http://brooksandrew.github.io/simpleblog/articles/intro-to-graph-optimization-solving-cpp/

[rpp_blog_post]: http://brooksandrew.github.io/simpleblog/articles/fifty-states-rural-postman-problem/
[Giant master program]: http://www.sgpa.org/hikes/masters.html
[rpp_sg_osm_blogpost]: http://brooksandrew.github.io/simpleblog/articles/sleeping-giant-rural-postman-problem/


text:
# TESTP
Test PASERIE internals

```
PASERIE/INSTALL GIT_USER(AndreaRibuoli) PACKAGEN(TESTP)
```

## tuning behaviour

PASERIE/INSTALL transfers an **installation mode** value to the **BUILD** program (compiled in QTEMP).
This value can be tested to differentiate behaviour.
It is called `DEVOPT` and is defined as a `CHAR(1)`.

When **Y** che convention is that the source files are to be copied from QTEMP to the target library.
The save BUILD program (CLLE) will be compiled and will behave differently assuming the CHAR(1) argument
is omitted. Missing argument default to **L** value for *Local build*.

When **N** (the default value PASERIE/INSTALL passes to BUILD) the build is supposed to execute in QTEMP
without saving source files.

repository: AndreaRibuoli/TESTP

repo_name: AndreaRibuoli/TESTP


text:
+++
title = "TCP Proxying and Protocol Detection"
description = "Linkerd is capable of proxying all TCP traffic, including TLS'd connections, WebSockets, and HTTP tunneling."
weight = 2
aliases = [
  "/2.10/supported-protocols/"
]
+++

Linkerd is capable of proxying all TCP traffic, including TLS connections,
WebSockets, and HTTP tunneling.

In most cases, Linkerd can do this without configuration. To accomplish this,
Linkerd performs *protocol detection* to determine whether traffic is HTTP or
HTTP/2 (including gRPC). If Linkerd detects that a connection is HTTP or
HTTP/2, Linkerd automatically provides HTTP-level metrics and routing.

If Linkerd *cannot* determine that a connection is using HTTP or HTTP/2,
Linkerd will proxy the connection as a plain TCP connection, applying
[mTLS](../automatic-mtls/) and providing byte-level metrics as usual.

(Note that HTTPS calls to or from meshed pods are treated as TCP, not as HTTP.
Because the client initiates the TLS connection, Linkerd is not be able to
decrypt the connection to observe the HTTP transactions.)

## Configuring protocol detection

{{< note >}}
If you are experiencing 10-second delays when establishing connections, you are
likely running into a protocol detection timeout. This section will help you
understand how to fix this.
{{< /note >}}

In some cases, Linkerd's protocol detection will time out because it doesn't
see any bytes from the client. This situation is commonly encountered when
using "server-speaks-first" protocols where the server sends data before the
client does, such as SMTP, or protocols that proactively establish connections
without sending data, such as Memcache. In this case, the connection will
proceed as a TCP connection after a 10-second protocol detection delay.

To avoid this delay, you will need to provide some configuration for Linkerd.
There are two basic mechanisms for configuring protocol detection: _opaque
ports_ and _skip ports_. Marking a port as _opaque_ instructs Linkerd to skip
protocol detection and immediately proxy the connection as a TCP stream;
marking a port as a _skip port_ bypasses the proxy entirely. Opaque ports are
generally preferred (as Linkerd can provide mTLS, TCP-level metrics, etc), but
can only be used for services inside the cluster.

By default, Linkerd automatically marks the ports for some server-speaks-first
protocol as opaque. Services that speak those protocols over the default ports
to destinations inside the cluster do not need further configuration.
Linkerd's default list of opaque ports in the 2.10 release is 25 (SMTP), 443
(client-initiated TLS), 587 (SMTP), 3306 (MySQL), 5432 (Postgres), and 11211
(Memcache). Note that this may change in future releases.

The following table contains common protocols that may require configuration.

| Protocol        | Default port(s) | Notes |
|-----------------|-----------------|-------|
| SMTP            | 25, 587         |       |
| MySQL           | 3306            |       |
| MySQL with Galera | 3306, 4444, 4567, 4568 | Ports 4444, 4567, and 4568 are not in Linkerd's default set of opaque ports |
| PostgreSQL      | 5432            |       |
| Redis           | 6379            |       |
| ElasticSearch   | 9300            | Not in Linkerd's default set of opaque ports |
| Memcache        | 11211           |       |

If you are using one of those protocols, follow this decision tree to determine
which configuration you need to apply.

* Is the protocol wrapped in TLS?
  * Yes: no configuration required.
  * No: is the destination on the cluster?
    * Yes: is the port in Linkerd's default list of opaque ports?
      * Yes: no configuration required.
      * No: mark port(s) as opaque.
    * No: mark port(s) as skip.

## Marking a port as opaque

You can use the `config.linkerd.io/opaque-ports` annotation to mark a port as
opaque. This instructions Linkerd to skip protocol detection for that port.

This annotation can be set on a workload, service, or namespace. Setting it on
a workload tells meshed clients of that workload to skip protocol detection for
connections established to the workload, and tells Linkerd to skip protocol
detection when reverse-proxying incoming connections. Setting it on a service
tells meshed clients to skip protocol detection when proxying connections to
the service. Set it on a namespace applies this behavior to all services and
workloads in that namespace.

{{< note >}}
Since this annotation informs the behavior of meshed _clients_, it can be
applied to unmeshed services as well as meshed services.
{{< /note >}}

Setting the opaque-ports annotation can be done by using the `--opaque-ports`
flag when running `linkerd inject`. For example, for a MySQL database running
on the cluster using a non-standard port 4406, you can use the commands:

```bash
linkerd inject mysql-deployment.yml --opaque-ports=4406 \
  | kubectl apply -f -
 linkerd inject mysql-service.yml --opaque-ports=4406 \
  | kubectl apply -f -
```

{{< note >}}
Multiple ports can be provided as a comma-delimited string. The values you
provide will replace, not augment, the default list of opaque ports.
{{< /note >}}

## Marking a port as skip

Sometimes it is necessary to bypass the proxy altogether. For example, when
connecting to a server-speaks-first destination that is outside of the cluster,
there is no Service resource on which to set the
`config.linkerd.io/opaque-ports` annotation.

In this case, you can use the `--skip-outbound-ports` flag when running
`linkerd inject` to configure resources to bypass the proxy entirely when
sending to those ports. (Similarly, the `--skip-inbound-ports` flag will
configure the resource to bypass the proxy for incoming connections to those
ports.)

Skipping the proxy can be useful for these situations, as well as for
diagnosing issues, but otherwise should rarely be necessary.

As with opaque ports, multiple skipports can be provided as a comma-delimited
string.

## Using `NetworkPolicy` resources with opaque ports

When a service has a port marked as opaque, any `NetworkPolicy` resources that
apply to the respective port and restrict ingress access will have to be
changed to target the proxy's inbound port instead (by default, `4143`). If the
service has a mix of opaque and non-opaque ports, then the `NetworkPolicy`
should target both the non-opaque ports, and the proxy's inbound port.

A connection that targets an opaque endpoint (i.e a pod with a port marked as
opaque) will have its original target port replaced with the proxy's inbound
port. Once the inbound proxy receives the traffic, it will transparently
forward it to the main application container over a TCP connection.

repository: linkerd/website

branch_name: refs/heads/main

gha_language: JavaScript

repo_name: linkerd/website


text:
# pubnub-react

> A chat application written in React using PubNub API

## Getting Started

Clone this repo.

## npm scripts

Install the npm packages using:

```bash
$ npm install
```

### Dev
```bash
$ npm run dev
```

This runs a development mode server with live reload etc.

Open `http://localhost:8080` in your browser.

### Production

```bash
$ npm run build
$ npm start
```

This runs a production-ready express server that serves up a bundled and
minified version of the client.

Open `http://localhost:8080` in your browser.

### Tests

#### Single Run
```bash
$ npm run test
```

#### Watch Files
```bash
$ npm run test:watch
```

#### Coverage
```bash
$ npm run cover
```

#### Connecting to remote APIs

Both the devmode and production servers provide a way to proxy requests to
remote HTTP APIs.  This can be useful for working around CORS issues when
developing your software.

Edit [this file](server/proxy-config.js) to mount such APIs at a given path.

## License

Copyright (c) 2016 rangle.io

[MIT License][MIT]

[MIT]: ./LICENSE "Mit License"


text:
# graphql-grpc-edge

This repo is an **EXPERIMENTAL** work to automatically generate graphql server
as aggregate server to serve gRPC backed service.

## Background

gRPC and GraphQL are application level communication protocol designed to solve different set of problems. Both gRPC and GraphQL using different serialization and specification but shares same characteristics and functionalities as listed below.

Same specification characteristics between protobuf to grphql schema:

|  Protobuf   | GraphQL                                    |
|-------------|--------------------------------------------|
|  Package    | N/A                                        |
|  Service    | N/A                                        |
|  Import     | N/A                                        |
|  Enum       | Enum                                       |
|  Oneof      | Union                                      |
|  Message    | Type                                       |
|  Field      | Field                                      |
|  RPC        | `Query` or `Mutation`                      |
|  RPC Input  | `InputObject` with `option (graphql.type)` |
|  RPC Output | `Object` with `option (graphql.type)`.     |

Same primitive serialization data types:

| Protobuf | GraphQL. |
|----------|----------|
| uint8    | Int      |
| uint16   | Int      |
| uint32   | Int      |
| uint64   | Int      |
| int8     | Int      |
| int16    | Int      |
| int32    | Int      |
| int64    | Int      |
| float32  | Float    |
| float64  | Float    |
| string   | String   |
| bool     | Boolean  |

## Goals

Create a tool to get the best of both worlds. gRPC is very helpful to develop backend service. With gRPC, API contracts can be described concisely and also code implementation can be autogenerated. Unfortunately, as of this repository is created, there is no easy way to use gRPC directly from web browsers for web application. On the otherhand, GraphQL is very popular on web frontend community thanks to its flexible query fields resulting in efficient network transfer size, and graph-like data representation very helpful for frontend engineer. One of the downsize of using GraphQL is there's no easy way to generate a GraphQL schema.

It is possible to create a GraphQL server and schema to be used by frontend engineer while communicating to backend services using gRPC to return the results. But to do this manually will be very tedious.

## Design

![Design diagram](docs/diagram.png)

## Usage

1. Install `protoc-gen-graphql` executable with `go get github.com/ncrypthic/graphql-grpc-edge/protoc-gen-graphql`.

2. Import `graphql-grpc-edge/graphql/graphql.proto` protobuf file.

3. Add `graphql.type` option to `service.rpc`(s) to generate graphql operation type (Query, Mutation) along with the operation name. For example:

    ```proto
    syntax="proto3";

    // ...
    import "graphql-grpc-edge/graphql/graphql.proto";

    // ...
    service Example {
        rpc GetSomething(GetSomethingRequest) returns(GetSomethingResponse) {
            option (graphql.type) = {
                // this will generate a graphql query named `getSomething` with `GetSomethingRequestInput` as its parameter
                // and `GetSomethingResponse` object as its return type
                query: "getSomething"
            };
        }

        rpc MutateSomething(MutateSomethingRequest) returns(MutateSomethingResponse) {
            option (graphql.type) = {
                // this will generate a graphql mutation named `mutateSomething` with `MutateSomethingRequest` as its parameter
                // and `MutateSomethingResponse` object as its return type
                mutation: "mutateSomething"
            };
        }
    }
    ```

5. Generate golang code using `protoc --graphql_out=:. file.proto`

6. Register generated graphql types, queries and mutations. Using example generated code from proto definition above:

    ```golang
    import (
        "github.com/graphql-go/handler"
        edge "github.com/ncrypthic/graphql-grpc-edge/graphql"
    )

    // ...
    // grpcClient: grpcClient to upstream gRPC server

    somePackage.RegisterExampleServiceTypes()
    somePackage.RegisterExampleServiceQueries(grpcClient)
    somePackage.RegisterExampleServiceMutations(grpcClient)

    gqlSchema := edge.GetSchema()
    ```

7. Serve the graphql schema

    ```golang
    import (
        "github.com/graphql-go/handler"
        edge "github.com/ncrypthic/graphql-grpc-edge/graphql"
    )

    // ...

    somePackage.RegisterExampleServiceTypes()
    somePackage.RegisterExampleServiceQueries(grpcClient)
    somePackage.RegisterExampleServiceMutations(grpcClient)

    gqlSchema := edge.GetSchema()
    h := handler.New(&handler.Config{
        Schema:   schema,
        Pretty:   true,
        GraphiQL: true,
    })

    http.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) {
        // Optional: enable opentracing
        span, ctx := opentracing.StartSpanFromContext(context.Background(), "entrypoint")
        defer span.Finish()
        // Handle graphql API
        h.ContextHandler(ctx, w, req)
    })
    ```

## More example

See [example](example)

## License

MIT License

Copyright (c) 2019 Lim Afriyadi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

repository: ncrypthic/graphql-grpc-edge

repo_name: ncrypthic/graphql-grpc-edge