text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2003</year><year>2017</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Concurrent Programming</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>conc_prog.xml</file>

  <marker id="Distributed Programming"></marker>

    <title>Processes</title>

One of the main reasons for using Erlang instead of other
      functional languages is Erlang's ability to handle concurrency
      and distributed programming. By concurrency is meant programs
      that can handle several threads of execution at the same time.
      For example, modern operating systems allow you to use a
      word processor, a spreadsheet, a mail client, and a print job all
      running at the same time. Each processor (CPU) in
      the system is probably only handling one thread (or job) at a
      time, but it swaps between the jobs at such a rate that it gives
      the illusion of running them all at the same time. It is easy to
      create parallel threads of execution in an Erlang program and
      to allow these threads to communicate with each other. In
      Erlang, each thread of execution is called a process.

(Aside: the term "process" is usually used when the threads of
      execution share no data with each other and the term "thread"
      when they share data in some way. Threads of execution in Erlang
      share no data, that is why they are called processes).

The Erlang BIF <c>spawn</c> is used to create a new process:
      <c>spawn(Module, Exported_Function, List of Arguments)</c>.
      Consider the following module:

-module(tut14).

-export([start/0, say_something/2]).

say_something(What, 0) ->
    done;
say_something(What, Times) ->
    io:format("~p~n", [What]),
    say_something(What, Times - 1).

start() ->
    spawn(tut14, say_something, [hello, 3]),
    spawn(tut14, say_something, [goodbye, 3]).

5> <input>c(tut14).</input>
{ok,tut14}
6> <input>tut14:say_something(hello, 3).</input>
hello
hello
hello
done

As shown, the function <c>say_something</c> writes its first
      argument the number of times specified by second argument.
      The function <c>start</c> starts two Erlang processes,
      one that writes "hello" three times and one that writes
      "goodbye" three times. Both processes use the function
      <c>say_something</c>. Notice that a function used in this way by
      <c>spawn</c>, to start a process, must be exported from the module
      (that is, in the <c>-export</c> at the start of the module).

9> <input>tut14:start().</input>
hello
goodbye
<0.63.0>
hello
goodbye
hello
goodbye

Notice that it did not write "hello" three times and then
      "goodbye" three times. Instead, the first process wrote a "hello",
      the second a "goodbye", the first another "hello" and so forth.
      But where did the <0.63.0> come from? The return value of a
      function is the return value of the last "thing" in
      the function. The last thing in the function <c>start</c> is

spawn(tut14, say_something, [goodbye, 3]).

<c>spawn</c> returns a process identifier, or
      pid, which uniquely identifies the process. So <0.63.0>
      is the pid of the <c>spawn</c> function call above.
      The next example shows how to use pids.

Notice also that ~p is used instead of ~w in
      <c>io:format</c>. To quote the manual: "~p Writes the data with
      standard syntax in the same way as ~w, but breaks terms whose
      printed representation is longer than one line into many lines
      and indents each line sensibly. It also tries to detect lists of
      printable characters and to output these as strings".

    <title>Message Passing</title>

In the following example two processes are created and
    they send messages to each other a number of times.

-module(tut15).

-export([start/0, ping/2, pong/0]).

ping(0, Pong_PID) ->
    Pong_PID ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_PID) ->
    Pong_PID ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_PID).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start() ->
    Pong_PID = spawn(tut15, pong, []),
    spawn(tut15, ping, [3, Pong_PID]).

1> <input>c(tut15).</input>
{ok,tut15}
2> <input>tut15: start().</input>
<0.36.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished

The function <c>start</c> first creates a process,
      let us call it "pong":

Pong_PID = spawn(tut15, pong, [])

This process executes <c>tut15:pong()</c>. <c>Pong_PID</c> is
      the process identity of the "pong" process. The function
      <c>start</c> now creates another process "ping":

spawn(tut15, ping, [3, Pong_PID]),

This process executes:

tut15:ping(3, Pong_PID)

<0.36.0> is the return value from the <c>start</c> function.

The process "pong" now does:

receive
    finished ->
        io:format("Pong finished~n", []);
    {ping, Ping_PID} ->
        io:format("Pong received ping~n", []),
        Ping_PID ! pong,
        pong()
end.

The <c>receive</c> construct is used to allow processes to wait
      for messages from other processes. It has the following format:

receive
   pattern1 ->
       actions1;
   pattern2 ->
       actions2;
   ....
   patternN
       actionsN
end.

Notice there is no ";" before the <c>end</c>.

Messages between Erlang processes are simply valid Erlang terms.
      That is, they can be lists, tuples, integers, atoms, pids,
      and so on.

Each process has its own input queue for messages it receives.
      New messages received are put at the end of the queue. When a
      process executes a <c>receive</c>, the first message in the queue
      is matched against the first pattern in the <c>receive</c>. If
      this matches, the message is removed from the queue and
      the actions corresponding to the pattern are executed.

However, if the first pattern does not match, the second pattern
      is tested. If this matches, the message is removed from the queue
      and the actions corresponding to the second pattern are executed.
      If the second pattern does not match, the third is tried and so on
      until there are no more patterns to test. If there are no more
      patterns to test, the first message is kept in the queue and
      the second message is tried instead. If this matches any pattern,
      the appropriate actions are executed and the second message is
      removed from the queue (keeping the first message and any other
      messages in the queue). If the second message does not match,
      the third message is tried, and so on, until the end of
      the queue is reached. If the end of the queue is reached,
      the process blocks
      (stops execution) and waits until a new message is received and
      this procedure is repeated.

The Erlang implementation is "clever" and minimizes
      the number of times each message is tested against the patterns
      in each <c>receive</c>.

Now back to the ping pong example.

"Pong" is waiting for messages. If the atom <c>finished</c> is
      received, "pong" writes "Pong finished" to the output and, as it
      has nothing more to do, terminates. If it receives a message with
      the format:

{ping, Ping_PID}

it writes "Pong received ping" to the output and sends the atom
      <c>pong</c> to the process "ping":

Ping_PID ! pong

Notice how the operator "!" is used to send messages. The syntax
      of "!" is:

Pid ! Message

That is, <c>Message</c> (any Erlang term) is sent to the process
      with identity <c>Pid</c>.

After sending the message <c>pong</c> to the process "ping",
      "pong" calls the <c>pong</c> function again, which causes it to
      get back to the <c>receive</c> again and wait for another message.

Now let us look at the process "ping". Recall that it was started
      by executing:

tut15:ping(3, Pong_PID)

Looking at the function <c>ping/2</c>, the second
      clause of <c>ping/2</c> is executed since the value of the first
      argument is 3 (not 0) (first clause head is
      <c>ping(0,Pong_PID)</c>, second clause head is
      <c>ping(N,Pong_PID)</c>, so <c>N</c> becomes 3).

The second clause sends a message to "pong":

Pong_PID ! {ping, self()},

<c>self()</c> returns the pid of the process that executes
      <c>self()</c>, in this case the pid of "ping". (Recall the code
      for "pong", this lands up in the variable <c>Ping_PID</c> in
      the <c>receive</c> previously explained.)

"Ping" now waits for a reply from "pong":

receive
    pong ->
        io:format("Ping received pong~n", [])
end,

It writes "Ping received pong" when this reply arrives, after
      which "ping" calls the <c>ping</c> function again.

ping(N - 1, Pong_PID)

<c>N-1</c> causes the first argument to be decremented until it
      becomes 0. When this occurs, the first clause of <c>ping/2</c>
      is executed:

ping(0, Pong_PID) ->
    Pong_PID !  finished,
    io:format("ping finished~n", []);

The atom <c>finished</c> is sent to "pong" (causing it to
      terminate as described above) and "ping finished" is written to
      the output. "Ping" then terminates as it has nothing left
      to do.

    <title>Registered Process Names</title>

In the above example, "pong" was first created to be able
      to give the identity of "pong" when "ping" was started. That is, in
      some way "ping" must be able to know the identity of "pong" to be
      able to send a message to it. Sometimes processes
      which need to know each other's identities are started
      independently of each other. Erlang thus provides a mechanism for
      processes to be given names so that these names can be used as
      identities instead of pids. This is done by using
      the <c>register</c> BIF:

register(some_atom, Pid)

Let us now rewrite the ping pong example using this and give
      the name <c>pong</c> to the "pong" process:

-module(tut16).

-export([start/0, ping/1, pong/0]).

ping(0) ->
    pong ! finished,
    io:format("ping finished~n", []);

ping(N) ->
    pong ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start() ->
    register(pong, spawn(tut16, pong, [])),
    spawn(tut16, ping, [3]).

2> <input>c(tut16).</input>
{ok, tut16}
3> <input>tut16:start().</input>
<0.38.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished

Here the <c>start/0</c> function,

register(pong, spawn(tut16, pong, [])),

both spawns the "pong" process and gives it the name <c>pong</c>.
      In the "ping" process, messages can be sent to <c>pong</c> by:

pong ! {ping, self()},

<c>ping/2</c> now becomes <c>ping/1</c> as
      the argument <c>Pong_PID</c> is not needed.

    <title>Distributed Programming</title>

Let us rewrite the ping pong program with "ping" and "pong"
      on different computers. First a few things
      are needed to set up to get this to work. The distributed Erlang
      implementation provides a very basic authentication mechanism to prevent
      unintentional access to an Erlang system on another computer.
      Erlang systems which talk to each other must have
      the same magic cookie. The easiest way to achieve this
      is by having a file called <c>.erlang.cookie</c> in your home
      directory on all machines on which you are going to run
      Erlang systems communicating with each other:

      <list type="bulleted">
	<item>On Windows systems the home directory is the directory
	pointed out by the environment variable $HOME - you may need
        to set this.</item>
        <item> On Linux or UNIX
        you can safely ignore this and simply create a file called
        <c>.erlang.cookie</c> in the directory you get to after executing
        the command <c>cd</c> without any argument.</item>
      </list>

The <c>.erlang.cookie</c> file is to contain a line with
      the same atom. For example, on Linux or UNIX, in the OS shell:

$ <input>cd</input>
$ <input>cat > .erlang.cookie</input>
this_is_very_secret
$ <input>chmod 400 .erlang.cookie</input>

The <c>chmod</c> above makes the <c>.erlang.cookie</c> file
      accessible only by the owner of the file. This is a requirement.

When you start an Erlang system that is going to talk to other
      Erlang systems, you must give it a name, for example:

$ <input>erl -sname my_name</input>

We will see more details of this later. If you want to
      experiment with distributed Erlang, but you only have one
      computer to work on, you can start two separate Erlang systems on
      the same computer but give them different names. Each Erlang
      system running on a computer is called an Erlang node.

(Note: <c>erl -sname</c> assumes that all nodes are in the same
      IP domain and we can use only the first component of the IP
      address, if we want to use nodes in different domains we use
      <c>-name</c> instead, but then all IP address must be given in
      full.)

Here is the ping pong example modified to run on two separate
      nodes:

-module(tut17).

-export([start_ping/1, start_pong/0,  ping/2, pong/0]).

ping(0, Pong_Node) ->
    {pong, Pong_Node} ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_Node) ->
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start_pong() ->
    register(pong, spawn(tut17, pong, [])).

start_ping(Pong_Node) ->
    spawn(tut17, ping, [3, Pong_Node]).

Let us assume there are two computers called gollum and kosken.
      First a node is started on kosken, called ping, and then a node on gollum,
      called pong.

On kosken (on a Linux/UNIX system):

kosken> <input>erl -sname ping</input>
Erlang (BEAM) emulator version 5.2.3.7 [hipe] [threads:0]

Eshell V5.2.3.7  (abort with ^G)
(ping@kosken)1>

On gollum:

gollum> <input>erl -sname pong</input>
Erlang (BEAM) emulator version 5.2.3.7 [hipe] [threads:0]

Eshell V5.2.3.7  (abort with ^G)
(pong@gollum)1>

Now the "pong" process on gollum is started:

(pong@gollum)1> <input>tut17:start_pong().</input>
true

And the "ping" process on kosken is started (from the code above you
      can see that a parameter of the <c>start_ping</c> function is
      the node name of the Erlang system where "pong" is running):

(ping@kosken)1> <input>tut17:start_ping(pong@gollum).</input>
<0.37.0>
Ping received pong
Ping received pong
Ping received pong
ping finished

As shown, the ping pong program has run. On the "pong" side:

(pong@gollum)2>
Pong received ping
Pong received ping
Pong received ping
Pong finished
(pong@gollum)2>

Looking at the <c>tut17</c> code, you see that the <c>pong</c>
      function itself is unchanged, the following lines work in the same way
      irrespective of on which node the "ping" process is executes:

{ping, Ping_PID} ->
    io:format("Pong received ping~n", []),
    Ping_PID ! pong,

Thus, Erlang pids contain information about
      where the process executes. So if you know the pid of a process,
      the "!" operator can be used to send it a message disregarding
      if the process is on the same node or on a different node.

A difference is how messages are sent to a registered process on
      another node:

{pong, Pong_Node} ! {ping, self()},

A tuple <c>{registered_name,node_name}</c> is used instead of
      just the <c>registered_name</c>.

In the previous example, "ping" and "pong" were started from
      the shells of two separate Erlang nodes. <c>spawn</c> can also be
      used to start processes in other nodes.

The next example is the ping pong program, yet again,
      but this time "ping" is started in another node:

-module(tut18).

-export([start/1,  ping/2, pong/0]).

ping(0, Pong_Node) ->
    {pong, Pong_Node} ! finished,
    io:format("ping finished~n", []);

ping(N, Pong_Node) ->
    {pong, Pong_Node} ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_Node).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start(Ping_Node) ->
    register(pong, spawn(tut18, pong, [])),
    spawn(Ping_Node, tut18, ping, [3, node()]).

Assuming an Erlang system called ping (but not the "ping"
      process) has already been started on kosken, then on gollum this is done:

(pong@gollum)1> <input>tut18:start(ping@kosken).</input>
<3934.39.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong finished
ping finished

Notice that all the output is received on gollum. This is because
      the I/O
      system finds out where the process is spawned from and sends all
      output there.

    <title>A Larger Example</title>

Now for a larger example with a simple
      "messenger". The messenger is a program that allows users to log
      in on different nodes and send simple messages to each other.

Before starting, notice the following:

    <list type="bulleted">
      <item>

This example only shows the message passing logic - no
          attempt has been made to provide a nice graphical user
          interface, although this can also be done in Erlang.

      </item>
      <item>

This sort of problem can be solved easier by use of
          the facilities in OTP, which also provide methods for
          updating code on the fly and so on (see
	  <seealso marker="doc/design_principles:des_princ#otp design principles">
          OTP Design Principles</seealso>).

      </item>
      <item>

The first program contains some inadequacies
          regarding handling of nodes which disappear.
          These are corrected in a later version of the program.

      </item>
    </list>

The messenger is set up by allowing "clients" to connect to
      a central server and say who and where they are. That is, a user
      does not need to know the name of the Erlang node where another user
      is located to send a message.

File <c>messenger.erl</c>:

    <marker id="ex"></marker>

%%% Message passing utility.
%%% User interface:
%%% logon(Name)
%%%     One user at a time can log in from each Erlang node in the
%%%     system messenger: and choose a suitable Name. If the Name
%%%     is already logged in at another node or if someone else is
%%%     already logged in at the same node, login will be rejected
%%%     with a suitable error message.
%%% logoff()
%%%     Logs off anybody at that node
%%% message(ToName, Message)
%%%     sends Message to ToName. Error messages if the user of this
%%%     function is not logged on or if ToName is not logged on at
%%%     any node.
%%%
%%% One node in the network of Erlang nodes runs a server which maintains
%%% data about the logged on users. The server is registered as "messenger"
%%% Each node where there is a user logged on runs a client process registered
%%% as "mess_client"
%%%
%%% Protocol between the client processes and the server
%%% ----------------------------------------------------
%%%
%%% To server: {ClientPid, logon, UserName}
%%% Reply {messenger, stop, user_exists_at_other_node} stops the client
%%% Reply {messenger, logged_on} logon was successful
%%%
%%% To server: {ClientPid, logoff}
%%% Reply: {messenger, logged_off}
%%%
%%% To server: {ClientPid, logoff}
%%% Reply: no reply
%%%
%%% To server: {ClientPid, message_to, ToName, Message} send a message
%%% Reply: {messenger, stop, you_are_not_logged_on} stops the client
%%% Reply: {messenger, receiver_not_found} no user with this name logged on
%%% Reply: {messenger, sent} Message has been sent (but no guarantee)
%%%
%%% To client: {message_from, Name, Message},
%%%
%%% Protocol between the "commands" and the client
%%% ----------------------------------------------
%%%
%%% Started: messenger:client(Server_Node, Name)
%%% To client: logoff
%%% To client: {message_to, ToName, Message}
%%%
%%% Configuration: change the server_node() function to return the
%%% name of the node where the messenger server runs

-module(messenger).
-export([start_server/0, server/1, logon/1, logoff/0, message/2, client/2]).

%%% Change the function below to return the name of the node where the
%%% messenger server runs
server_node() ->
    messenger@bill.

%%% This is the server process for the "messenger"
%%% the user list has the format [{ClientPid1, Name1},{ClientPid22, Name2},...]
server(User_List) ->
    receive
        {From, logon, Name} ->
            New_User_List = server_logon(From, Name, User_List),
            server(New_User_List);
        {From, logoff} ->
            New_User_List = server_logoff(From, User_List),
            server(New_User_List);
        {From, message_to, To, Message} ->
            server_transfer(From, To, Message, User_List),
            io:format("list is now: ~p~n", [User_List]),
            server(User_List)
    end.

%%% Start the server
start_server() ->
    register(messenger, spawn(messenger, server, [[]])).

%%% Server adds a new user to the user list
server_logon(From, Name, User_List) ->
    %% check if logged on anywhere else
    case lists:keymember(Name, 2, User_List) of
        true ->
            From ! {messenger, stop, user_exists_at_other_node},  %reject logon
            User_List;
        false ->
            From ! {messenger, logged_on},
            [{From, Name} | User_List]        %add user to the list
    end.

%%% Server deletes a user from the user list
server_logoff(From, User_List) ->
    lists:keydelete(From, 1, User_List).

%%% Server transfers a message between user
server_transfer(From, To, Message, User_List) ->
    %% check that the user is logged on and who he is
    case lists:keysearch(From, 1, User_List) of
        false ->
            From ! {messenger, stop, you_are_not_logged_on};
        {value, {From, Name}} ->
            server_transfer(From, Name, To, Message, User_List)
    end.
%%% If the user exists, send the message
server_transfer(From, Name, To, Message, User_List) ->
    %% Find the receiver and send the message
    case lists:keysearch(To, 2, User_List) of
        false ->
            From ! {messenger, receiver_not_found};
        {value, {ToPid, To}} ->
            ToPid ! {message_from, Name, Message},
            From ! {messenger, sent}
    end.

%%% User Commands
logon(Name) ->
    case whereis(mess_client) of
        undefined ->
            register(mess_client,
                     spawn(messenger, client, [server_node(), Name]));
        _ -> already_logged_on
    end.

logoff() ->
    mess_client ! logoff.

message(ToName, Message) ->
    case whereis(mess_client) of % Test if the client is running
        undefined ->
            not_logged_on;
        _ -> mess_client ! {message_to, ToName, Message},
             ok
end.

%%% The client process which runs on each server node
client(Server_Node, Name) ->
    {messenger, Server_Node} ! {self(), logon, Name},
    await_result(),
    client(Server_Node).

client(Server_Node) ->
    receive
        logoff ->
            {messenger, Server_Node} ! {self(), logoff},
            exit(normal);
        {message_to, ToName, Message} ->
            {messenger, Server_Node} ! {self(), message_to, ToName, Message},
            await_result();
        {message_from, FromName, Message} ->
            io:format("Message from ~p: ~p~n", [FromName, Message])
    end,
    client(Server_Node).

%%% wait for a response from the server
await_result() ->
    receive
        {messenger, stop, Why} -> % Stop the client
            io:format("~p~n", [Why]),
            exit(normal);
        {messenger, What} ->  % Normal response
            io:format("~p~n", [What])
    end.

To use this program, you need to:

    <list type="bulleted">
      <item>Configure the <c>server_node()</c> function.</item>
      <item>Copy the compiled code (<c>messenger.beam</c>) to
       the directory on each computer where you start Erlang.</item>
    </list>

In the following example using this program,
      nodes are started on four different computers. If you do not have that
      many machines available on your network, you can start
      several nodes on the same machine.

Four Erlang nodes are started up: messenger@super, c1@bilbo,
      c2@kosken, c3@gollum.

First the server at messenger@super is started up:

(messenger@super)1> <input>messenger:start_server().</input>
true

Now Peter logs on at c1@bilbo:

(c1@bilbo)1> <input>messenger:logon(peter).</input>
true
logged_on

James logs on at c2@kosken:

(c2@kosken)1> <input>messenger:logon(james).</input>
true
logged_on

And Fred logs on at c3@gollum:

(c3@gollum)1> <input>messenger:logon(fred).</input>
true
logged_on

Now Peter sends Fred a message:

(c1@bilbo)2> <input>messenger:message(fred, "hello").</input>
ok
sent

Fred receives the message and sends a message to Peter and
      logs off:

Message from peter: "hello"
(c3@gollum)2> <input>messenger:message(peter, "go away, I'm busy").</input>
ok
sent
(c3@gollum)3> <input>messenger:logoff().</input>
logoff

James now tries to send a message to Fred:

(c2@kosken)2> <input>messenger:message(fred, "peter doesn't like you").</input>
ok
receiver_not_found

But this fails as Fred has already logged off.

First let us look at some of the new concepts that have
       been introduced.

There are two versions of the <c>server_transfer</c> function:
      one with four arguments (<c>server_transfer/4</c>) and one with
      five (<c>server_transfer/5</c>). These are regarded by Erlang as
      two separate functions.

Notice how to write the <c>server</c> function so that it calls
      itself, through <c>server(User_List)</c>, and thus creates a loop.
      The Erlang compiler is "clever" and optimizes the code so that
      this really is a sort of loop and not a proper function call. But
      this only works if there is no code after the call. Otherwise,
      the compiler expects the call to return and make a proper
      function call. This would result in the process getting bigger
      and bigger for every loop.

Functions in the <c>lists</c> module are used. This is a very
      useful module and a study of the manual page is recommended
      (<c>erl -man lists</c>).
      <c>lists:keymember(Key,Position,Lists)</c> looks through a list
      of tuples and looks at <c>Position</c> in each tuple to see if it
      is the same as <c>Key</c>. The first element is position 1. If it
      finds a tuple where the element at <c>Position</c> is the same as
      <c>Key</c>, it returns <c>true</c>, otherwise <c>false</c>.

3> <input>lists:keymember(a, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</input>
true
4> <input>lists:keymember(p, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</input>
false

<c>lists:keydelete</c> works in the same way but deletes
      the first tuple found (if any) and returns the remaining list:

5> <input>lists:keydelete(a, 2, [{x,y,z},{b,b,b},{b,a,c},{q,r,s}]).</input>
[{x,y,z},{b,b,b},{q,r,s}]

<c>lists:keysearch</c> is like <c>lists:keymember</c>, but it
      returns <c>{value,Tuple_Found}</c> or the atom <c>false</c>.

There are many very useful functions in the <c>lists</c>
      module.

An Erlang process (conceptually) runs until it does a
      <c>receive</c> and there is no message which it wants to receive
      in the message queue. "conceptually" is used here because the Erlang
      system shares the CPU time between the active processes in
      the system.

A process terminates when there is nothing more for it to do,
      that is, the last function it calls simply returns and does not call
      another function. Another way for a process to terminate is for
      it to call <c>exit/1</c>. The argument to <c>exit/1</c> has a
      special meaning, which is discussed later. In this example,
      <c>exit(normal)</c> is done, which has the same effect as a
      process running out of functions to call.

The BIF <c>whereis(RegisteredName)</c> checks if a registered
      process of name <c>RegisteredName</c> exists. If it exists, the pid of
      that process is returned. If it does not exist, the atom
      <c>undefined</c> is returned.

You should by now be able to understand most of the code in the
      messenger-module. Let us study one case in detail: a message is
      sent from one user to another.

The first user "sends" the message in the example above by:

messenger:message(fred, "hello")

After testing that the client process exists:

whereis(mess_client)

And a message is sent to <c>mess_client</c>:

mess_client ! {message_to, fred, "hello"}

The client sends the message to the server by:

{messenger, messenger@super} ! {self(), message_to, fred, "hello"},

And waits for a reply from the server.

The server receives this message and calls:

server_transfer(From, fred, "hello", User_List),

This checks that the pid <c>From</c> is in the <c>User_List</c>:

lists:keysearch(From, 1, User_List)

If <c>keysearch</c> returns the atom <c>false</c>, some
      error has occurred and the server sends back the message:

From ! {messenger, stop, you_are_not_logged_on}

This is received by the client, which in turn does
      <c>exit(normal)</c> and terminates. If <c>keysearch</c> returns
      <c>{value,{From,Name}}</c> it is certain that the user is logged on and
      that his name (peter) is in variable <c>Name</c>.

Let us now call:

server_transfer(From, peter, fred, "hello", User_List)

Notice that as this is <c>server_transfer/5</c>, it is not the same
      as the previous function <c>server_transfer/4</c>. Another
      <c>keysearch</c> is done on <c>User_List</c> to find the pid of
      the client corresponding to fred:

lists:keysearch(fred, 2, User_List)

This time argument 2 is used, which is the second element in
      the tuple. If this returns the atom <c>false</c>,
      fred is not logged on and the following message is sent:

From ! {messenger, receiver_not_found};

This is received by the client.

 If <c>keysearch</c> returns:

{value, {ToPid, fred}}

The following message is sent to fred's client:

ToPid ! {message_from, peter, "hello"},

The following message is sent to peter's client:

From ! {messenger, sent}

Fred's client receives the message and prints it:

{message_from, peter, "hello"} ->
    io:format("Message from ~p: ~p~n", [peter, "hello"])

Peter's client receives the message in
      the <c>await_result</c> function.

</chapter>


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/tty.h>
#include <linux/devpts_fs.h>
#include <linux/parser.h>

#define DEVPTS_SUPER_MAGIC 0x1cd1

static struct vfsmount *devpts_mnt;
static struct dentry *devpts_root;

static struct {
	int setuid;
	int setgid;
	uid_t   uid;
	gid_t   gid;
	umode_t mode;
} config = {.mode = 0600};

enum {
	Opt_uid, Opt_gid, Opt_mode,
	Opt_err
};

static match_table_t tokens = {
	{Opt_uid, "uid=%u"},
	{Opt_gid, "gid=%u"},
	{Opt_mode, "mode=%o"},
	{Opt_err, NULL}
};

static int devpts_remount(struct super_block *sb, int *flags, char *data)
{
	char *p;

	config.setuid  = 0;
	config.setgid  = 0;
	config.uid     = 0;
	config.gid     = 0;
	config.mode    = 0600;

	while ((p = strsep(&data, ",")) != NULL) {
		substring_t args[MAX_OPT_ARGS];
		int token;
		int option;

		if (!*p)
			continue;

		token = match_token(p, tokens, args);
		switch (token) {
		case Opt_uid:
			if (match_int(&args[0], &option))
				return -EINVAL;
			config.uid = option;
			config.setuid = 1;
			break;
		case Opt_gid:
			if (match_int(&args[0], &option))
				return -EINVAL;
			config.gid = option;
			config.setgid = 1;
			break;
		case Opt_mode:
			if (match_octal(&args[0], &option))
				return -EINVAL;
			config.mode = option & ~S_IFMT;
			break;
		default:
			printk(KERN_ERR "devpts: called with bogus options\n");
			return -EINVAL;
		}
	}

	return 0;
}

static const struct super_operations devpts_sops = {
	.statfs		= simple_statfs,
	.remount_fs	= devpts_remount,
};

static int
devpts_fill_super(struct super_block *s, void *data, int silent)
{
	struct inode * inode;

	s->s_blocksize = 1024;
	s->s_blocksize_bits = 10;
	s->s_magic = DEVPTS_SUPER_MAGIC;
	s->s_op = &devpts_sops;
	s->s_time_gran = 1;

	inode = new_inode(s);
	if (!inode)
		goto fail;
	inode->i_ino = 1;
	inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
	inode->i_blocks = 0;
	inode->i_uid = inode->i_gid = 0;
	inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR;
	inode->i_op = &simple_dir_inode_operations;
	inode->i_fop = &simple_dir_operations;
	inode->i_nlink = 2;

	devpts_root = s->s_root = d_alloc_root(inode);
	if (s->s_root)
		return 0;

	printk("devpts: get root dentry failed\n");
	iput(inode);
fail:
	return -ENOMEM;
}

static int devpts_get_sb(struct file_system_type *fs_type,
	int flags, const char *dev_name, void *data, struct vfsmount *mnt)
{
	return get_sb_single(fs_type, flags, data, devpts_fill_super, mnt);
}

static struct file_system_type devpts_fs_type = {
	.owner		= THIS_MODULE,
	.name		= "devpts",
	.get_sb		= devpts_get_sb,
	.kill_sb	= kill_anon_super,
};

/*
 * The normal naming convention is simply /dev/pts/<number>; this conforms
 * to the System V naming convention
 */

static struct dentry *get_node(int num)
{
	char s[12];
	struct dentry *root = devpts_root;
	mutex_lock(&root->d_inode->i_mutex);
	return lookup_one_len(s, root, sprintf(s, "%d", num));
}

int devpts_pty_new(struct tty_struct *tty)
{
	int number = tty->index;
	struct tty_driver *driver = tty->driver;
	dev_t device = MKDEV(driver->major, driver->minor_start+number);
	struct dentry *dentry;
	struct inode *inode = new_inode(devpts_mnt->mnt_sb);

	/* We're supposed to be given the slave end of a pty */
	BUG_ON(driver->type != TTY_DRIVER_TYPE_PTY);
	BUG_ON(driver->subtype != PTY_TYPE_SLAVE);

	if (!inode)
		return -ENOMEM;

	inode->i_ino = number+2;
	inode->i_uid = config.setuid ? config.uid : current->fsuid;
	inode->i_gid = config.setgid ? config.gid : current->fsgid;
	inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
	init_special_inode(inode, S_IFCHR|config.mode, device);
	inode->i_private = tty;

	dentry = get_node(number);
	if (!IS_ERR(dentry) && !dentry->d_inode)
		d_instantiate(dentry, inode);

	mutex_unlock(&devpts_root->d_inode->i_mutex);

	return 0;
}

struct tty_struct *devpts_get_tty(int number)
{
	struct dentry *dentry = get_node(number);
	struct tty_struct *tty;

	tty = NULL;
	if (!IS_ERR(dentry)) {
		if (dentry->d_inode)
			tty = dentry->d_inode->i_private;
		dput(dentry);
	}

	mutex_unlock(&devpts_root->d_inode->i_mutex);

	return tty;
}

void devpts_pty_kill(int number)
{
	struct dentry *dentry = get_node(number);

	if (!IS_ERR(dentry)) {
		struct inode *inode = dentry->d_inode;
		if (inode) {
			inode->i_nlink--;
			d_delete(dentry);
			dput(dentry);
		}
		dput(dentry);
	}
	mutex_unlock(&devpts_root->d_inode->i_mutex);
}

static int __init init_devpts_fs(void)
{
	int err = register_filesystem(&devpts_fs_type);
	if (!err) {
		devpts_mnt = kern_mount(&devpts_fs_type);
		if (IS_ERR(devpts_mnt))
			err = PTR_ERR(devpts_mnt);
	}
	return err;
}

static void __exit exit_devpts_fs(void)
{
	unregister_filesystem(&devpts_fs_type);
	mntput(devpts_mnt);
}

module_init(init_devpts_fs)
module_exit(exit_devpts_fs)
MODULE_LICENSE("GPL");

redpajama_set_name: RedPajamaGithub


text:
@implementation MockDownloadProgressObserver

- (void)didUpdateProgeress:(float)progerss url:(NSString *)url
{
    if ([url isEqualToString:@"url1"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.progressView) {
                self.progressView.progress = progerss;
            }
        });
    }

}

@end


text:
"""Session authentication backend"""
from functools import wraps
from typing import Any, Callable, Optional, Tuple, TypeVar, Union, cast

from flask import Response, g

CLIENT_AUTH: Optional[Union[Tuple[str, str], Any]] = None

def init_app(_):
    """Initializes authentication backend"""

T = TypeVar("T", bound=Callable)

def requires_authentication(function: T):
    """Decorator for functions that require authentication"""

    @wraps(function)
    def decorated(*args, **kwargs):
        if g.user.is_anonymous:
            return Response("Unauthorized", 401, {})
        return function(*args, **kwargs)

    return cast(T, decorated)


text:
package org.apache.hadoop.hive.ql.parse;

import junit.framework.TestCase;

/**
 * TestEximUtil.
 *
 */
public class TestEximUtil extends TestCase {

  @Override
  protected void setUp() {
  }

  @Override
  protected void tearDown() {
  }

  public void testCheckCompatibility() throws SemanticException {

    // backward/forward compatible
    EximUtil.doCheckCompatibility(
        "10.3", // current code version
        "10.4", // data's version
        null // data's FC version
        ); // No exceptions expected
    EximUtil.doCheckCompatibility(
        "10.4", // current code version
        "10.4", // data's version
        null // data's FC version
        ); // No exceptions expected
    EximUtil.doCheckCompatibility(
        "10.5", // current code version
        "10.4", // data's version
        null // data's FC version
        ); // No exceptions expected

    // not backward compatible
    try {
      EximUtil.doCheckCompatibility(
          "11.0", // current code version
          "10.4", // data's version
          null // data's FC version
          ); // No exceptions expected
      fail();
    } catch (SemanticException e) {
    }

    // not forward compatible
    try {
      EximUtil.doCheckCompatibility(
          "9.9", // current code version
          "10.4", // data's version
          null // data's FC version
          ); // No exceptions expected
      fail();
    } catch (SemanticException e) {
    }

    // forward compatible
    EximUtil.doCheckCompatibility(
          "9.9", // current code version
        "10.4", // data's version
        "9.9" // data's FC version
    ); // No exceptions expected
    EximUtil.doCheckCompatibility(
        "9.9", // current code version
        "10.4", // data's version
        "9.8" // data's FC version
    ); // No exceptions expected
    EximUtil.doCheckCompatibility(
        "9.9", // current code version
        "10.4", // data's version
        "8.8" // data's FC version
    ); // No exceptions expected
    EximUtil.doCheckCompatibility(
        "10.3", // current code version
        "10.4", // data's version
        "10.3" // data's FC version
    ); // No exceptions expected

    // not forward compatible
    try {
      EximUtil.doCheckCompatibility(
          "10.2", // current code version
          "10.4", // data's version
          "10.3" // data's FC version
      ); // No exceptions expected
      fail();
    } catch (SemanticException e) {
    }

  }
}


text:
using UnityEngine;
using System.Collections;

public class FadeSample : MonoBehaviour
{

	public void FadeScene ()
	{
		FadeManager.Instance.LoadScene ("Scene1", 2.0f);
	}
}


text:
package com.github.salvatorenovelli.seo.websiteversioning.controller;

import com.github.salvatorenovelli.seo.websiteversioning.crawler.Crawler;
import com.github.salvatorenovelli.seo.websiteversioning.crawler.Worker;
import com.github.salvatorenovelli.seo.websiteversioning.crawler.WorkerManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.security.Principal;
import java.util.UUID;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(MockitoJUnitRunner.class)
public class WorkerControllerTest {

    public static final String TEST_URL = "http://example.com";
    private MockMvc mvc;
    @Mock private Crawler crawler;
    private WorkerManager workerManager = new WorkerManager(() -> Mockito.spy(new Worker(UUID.randomUUID().toString(), crawler)));
    @Mock private Principal currentPrincipal;
    private Worker worker1;
    private Worker worker2;

    @Before
    public void setup() {
        when(currentPrincipal.getName()).thenReturn("testUser");
        worker1 = workerManager.createWorkerForUser("testUser");
        worker2 = workerManager.createWorkerForUser("testUser");

        mvc = MockMvcBuilders
                .standaloneSetup(new WorkerController(workerManager))
                .build();
    }

    @Test
    public void shouldListAllUserWorkers() throws Exception {
        mvc.perform(get("/api/worker/list").principal(currentPrincipal))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0]", is(worker1.getId())))
                .andExpect(jsonPath("$[1]", is(worker2.getId())));
    }

    @Test
    public void shouldAllowStartingOfValidWorker() throws Exception {
        mvc.perform(
                put("/api/worker/" + worker1.getId() + "/start")
                        .principal(currentPrincipal)
                        .param("url", TEST_URL))
                .andExpect(status().isOk());
        verify(worker1).startCrawling(TEST_URL);
    }

    @Test
    public void shouldReturn404InCaseWorkerIsNotFoundForCurrentUser() throws Exception {
        mvc.perform(
                put("/api/worker/" + "WRONG_ID" + "/start")
                        .principal(currentPrincipal)
                        .param("url", TEST_URL))
                .andExpect(status().isNotFound());
    }

    @Test
    public void shouldGetWorkerStatus() throws Exception {
        mvc.perform(get("/api/worker/" + worker1.getId()).principal(currentPrincipal))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", is(worker1.getId())));
    }

    @Test
    public void shouldReturn404IfWorkerIsNotPresent() throws Exception {
        mvc.perform(get("/api/worker/" + "WRONG_ID").principal(currentPrincipal))
                .andExpect(status().isNotFound());
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;

namespace OrchardCore.Users.Workflows.Activities
{
    public class ValidateUserTask : TaskActivity
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string _roleClaimType;
        private readonly IStringLocalizer S;

        public ValidateUserTask(IHttpContextAccessor httpContextAccessor, IOptions<IdentityOptions> optionsAccessor, IStringLocalizer<ValidateUserTask> localizer)
        {
            _httpContextAccessor = httpContextAccessor;
            _roleClaimType = optionsAccessor.Value.ClaimsIdentity.RoleClaimType;
            S = localizer;
        }

        public override string Name => nameof(ValidateUserTask);

        public override LocalizedString Category => S["User"];

        public bool SetUserName
        {
            get => GetProperty(() => true);
            set => SetProperty(value);
        }

        public IEnumerable<string> Roles
        {
            get => GetProperty(() => new List<string>());
            set => SetProperty(value);
        }

        public override LocalizedString DisplayText => S["Validate User Task"];

        public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        {
            return Outcomes(S["Anonymous"], S["Authenticated"], S["InRole"]);
        }

        public override ActivityExecutionResult Execute(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        {
            var user = _httpContextAccessor.HttpContext.User;
            var isAuthenticated = user?.Identity?.IsAuthenticated;

            if (isAuthenticated == true)
            {
                if (SetUserName)
                {
                    workflowContext.Properties["UserName"] = user.Identity.Name;
                }

                if (Roles.Any())
                {
                    var userRoleNames = user
                        .FindAll(c => c.Type == _roleClaimType)
                        .Select(c => c.Value)
                        .ToList();

                    foreach (var role in Roles)
                    {
                        if (userRoleNames.Contains(role))
                        {
                            workflowContext.LastResult = userRoleNames;
                            return Outcomes("InRole");
                        }
                    }
                }

                return Outcomes("Authenticated");
            }

            return Outcomes("Anonymous");
        }
    }
}


text:
<?php

namespace Arthem\GoogleApi\Domain\Place\Query\Place;

use Arthem\GoogleApi\Domain\Place\VO\PlaceId;

class PlaceDetailsQuery
{
    /**
     * @var PlaceId
     */
    private $id;

    /**
     * @param string $id
     */
    public function __construct($id)
    {
        $this->id = new PlaceId($id);
    }

    /**
     * @return PlaceId
     */
    public function getId()
    {
        return $this->id;
    }
}


text:
**Welcome to the Flutter API reference documentation!**

Flutter is Google's SDK for crafting beautiful, fast user experiences for
mobile, web, and desktop from a single codebase. Flutter works with existing
code, is used by developers and organizations around the world, and is free
and open source.

This API reference covers all libraries that are exported by the Flutter
SDK.

### More Documentation

This site hosts Flutter's API documentation. Other documentation can be found at
the following locations:

* [flutter.dev](https://flutter.dev) (main site)
* [Installation](https://flutter.dev/docs/get-started/install)
* [Codelabs](https://flutter.dev/docs/codelabs)
* [Contributing to Flutter](https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md)

### Importing a Library

#### Framework Libraries

Libraries in the "Libraries" section below (or in the left navigation) are part
of the core Flutter framework and are imported using
`'package:flutter/<library>.dart'`, like so:

```dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
```

#### Dart Libraries

Libraries in the "Dart" section exist in the `dart:` namespace and are imported
using `'dart:<library>'`, like so:

```dart
import 'dart:async';
import 'dart:ui';
```

Except for `'dart:core'`, you must import a Dart library before you can use it.

#### Supporting Libraries

Libraries in other sections are supporting libraries that ship with Flutter.
They are organized by package and are imported using
`'package:<package>/<library>.dart'`, like so:

```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:file/local.dart';
```

### Packages on pub.dev

Flutter has a rich ecosystem of packages that have been contributed by the
Flutter team and the broader open source community to a central repository.
Among the thousands of packages, you'll find support for Firebase, Google
Fonts, hardware services like Bluetooth and camera, new widgets and
animations, and integration with other popular web services. You can browse
those packages at [pub.dev](https://pub.dev).


text:
//
//  DMPlayerCommonHeader.h
//  DMPlayerTest
//
//  Created by MinLison on 2017/4/28.
//  Copyright © 2017年 . All rights reserved.
//

#ifndef DMPlayerCommonHeader_h
#define DMPlayerCommonHeader_h
#import <UIKit/UIKit.h>

#define  DMUIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define DMNULLString(string) ((string == nil) || ([string isKindOfClass:[NSNull class]]) || (![string isKindOfClass:[NSString class]])||[string isEqualToString:@""] || [string isEqualToString:@"<null>"] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]== 0 )

#define DMNULLStringDefault(string,default) (DMNULLString(string) ? default : string)

#define DMNULLObject(obj) (obj == nil || obj == [NSNull null] || ([obj isKindOfClass:[NSString class]] && DMNULLString((NSString *)obj)))
#define DMNULLObjectDefault(obj,defalut) (DMNULLObject((id)obj) ? defalut : obj)

#define iPhone4s ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
// 监听TableView的contentOffset
#define kZFPlayerViewContentOffset          @"contentOffset"
#define kZFPlayerViewFrame		    @"frame"
// player的单例
#define ZFPlayerShared                      [ZFBrightnessView sharedBrightnessView]
// 屏幕的宽
#define ScreenWidth                         [[UIScreen mainScreen] bounds].size.width
// 屏幕的高
#define ScreenHeight                        [[UIScreen mainScreen] bounds].size.height
// 颜色值RGB
#define RGBA(r,g,b,a)                       [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
// 图片路径
#define ZFPlayerSrcName(file)               [@"ZFPlayer.bundle" stringByAppendingPathComponent:file]

#define ZFPlayerFrameworkSrcName(file)      [@"Frameworks/ZFPlayer.framework/ZFPlayer.bundle" stringByAppendingPathComponent:file]

#define ZFPlayerImage(img) 		    [UIImage imageNamed:img inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil]

//#define ZFPlayerImage(file)                 [UIImage imageNamed:ZFPlayerSrcName(file)] ? :[UIImage imageNamed:ZFPlayerFrameworkSrcName(file)]

#define ZFPlayerOrientationIsLandscape      UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)

#define ZFPlayerOrientationIsPortrait       UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)

#endif /* DMPlayerCommonHeader_h */


text:
namespace Common
{
    public enum User_Level
    {
        Cash = 0x1,
        Super,
        /// <summary>
        /// aka "God" level, used to indicate that no one may perform the action
        /// </summary>
        None
    }
}


text:
package com.thoughtworks.go.plugin.access.scm;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class SCMMetadataStoreTest {
    @BeforeEach
    public void setUp() throws Exception {
        SCMMetadataStore.getInstance().clear();
    }

    @AfterEach
    public void tearDown() throws Exception {
        SCMMetadataStore.getInstance().clear();
    }

    @Test
    public void shouldPopulateDataCorrectly() throws Exception {
        SCMConfigurations scmConfigurations = new SCMConfigurations();
        SCMView scmView = createSCMView("display-value", "template");
        SCMMetadataStore.getInstance().addMetadataFor("plugin-id", scmConfigurations, scmView);

        assertThat(SCMMetadataStore.getInstance().getConfigurationMetadata("plugin-id"), is(scmConfigurations));
        assertThat(SCMMetadataStore.getInstance().getViewMetadata("plugin-id"), is(scmView));
        assertThat(SCMMetadataStore.getInstance().displayValue("plugin-id"), is("display-value"));
        assertThat(SCMMetadataStore.getInstance().template("plugin-id"), is("template"));

        assertThat(SCMMetadataStore.getInstance().getConfigurationMetadata("some-plugin-which-does-not-exist"), is(nullValue()));
        assertThat(SCMMetadataStore.getInstance().getViewMetadata("some-plugin-which-does-not-exist"), is(nullValue()));
        assertThat(SCMMetadataStore.getInstance().displayValue("some-plugin-which-does-not-exist"), is(nullValue()));
        assertThat(SCMMetadataStore.getInstance().template("some-plugin-which-does-not-exist"), is(nullValue()));
    }

    @Test
    public void shouldBeAbleToCheckIfPluginExists() throws Exception {
        SCMConfigurations scmConfigurations = new SCMConfigurations();
        SCMView scmView = createSCMView(null, null);
        SCMMetadataStore.getInstance().addMetadataFor("plugin-id", scmConfigurations, scmView);

        assertThat(SCMMetadataStore.getInstance().hasPlugin("plugin-id"), is(true));
        assertThat(SCMMetadataStore.getInstance().hasPlugin("some-plugin-which-does-not-exist"), is(false));
    }

    private SCMView createSCMView(final String displayValue, final String template) {
        return new SCMView() {
            @Override
            public String displayValue() {
                return displayValue;
            }

            @Override
            public String template() {
                return template;
            }
        };
    }
}


text:
using Org.Apache.Reef.Driver.Bridge;
using Org.Apache.Reef.Driver.Evaluator;
using Org.Apache.Reef.Tang.Annotations;
using System;

namespace Org.Apache.Reef.Examples.HelloCLRBridge
{
    public class HelloFailedEvaluatorHandler : IObserver<IFailedEvaluator>
    {
        private static int _failureCount = 0;

        private static int _maxTrial = 2;

        [Inject]
        public HelloFailedEvaluatorHandler()
        {
        }

        public void OnNext(IFailedEvaluator failedEvaluator)
        {
            Console.WriteLine("Receive a failed evaluator: " + failedEvaluator.Id);
            if (++_failureCount < _maxTrial)
            {
                Console.WriteLine("Requesting another evaluator");
                EvaluatorRequest newRequest = new EvaluatorRequest(1, 512, "somerack");
                IEvaluatorRequestor requestor = failedEvaluator.GetEvaluatorRequetor();
                if (failedEvaluator.GetEvaluatorRequetor() != null)
                {
                    requestor.Submit(newRequest);
                }
            }
            else
            {
                Console.WriteLine("Exceed max retries number");
                throw new Exception("Unrecoverable evaluator failure.");
            }
        }

        public void OnError(Exception error)
        {
            throw new NotImplementedException();
        }

        public void OnCompleted()
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Imperial, Imperial County Airport, CA</location>
	<station_id>KIPL</station_id>
	<latitude>32.83417</latitude>
	<longitude>-115.57861</longitude>
	<observation_time>Last Updated on Jan 4 2016, 6:53 pm PST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 18:53:00 -0800</observation_time_rfc822>
	<weather>Overcast</weather>
	<temperature_string>57.0 F (13.9 C)</temperature_string>
	<temp_f>57.0</temp_f>
	<temp_c>13.9</temp_c>
	<relative_humidity>69</relative_humidity>
	<wind_string>Southeast at 3.5 MPH (3 KT)</wind_string>
	<wind_dir>Southeast</wind_dir>
	<wind_degrees>120</wind_degrees>
	<wind_mph>3.5</wind_mph>
	<wind_kt>3</wind_kt>
	<pressure_string>1011.9 mb</pressure_string>
	<pressure_mb>1011.9</pressure_mb>
	<pressure_in>29.88</pressure_in>
	<dewpoint_string>46.9 F (8.3 C)</dewpoint_string>
	<dewpoint_f>46.9</dewpoint_f>
	<dewpoint_c>8.3</dewpoint_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KIPL.html</two_day_history_url>
	<icon_url_name>ovc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KIPL.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
[![Build Status](http://img.shields.io/travis/mhelvens/delta.js.svg)](https://travis-ci.org/mhelvens/delta.js)
[![Coverage Status](http://img.shields.io/coveralls/mhelvens/delta.js.svg)](https://coveralls.io/r/mhelvens/delta.js?branch=master)

achieve modularity and separation of concerns through feature-oriented programming

## Description

Programming is an activity very prone to human error, especially if you have
multiple developers changing the same code-base at the same time.
As more and more features are implemented by different programmers, progress will
often slow to a crawl. Programmers can easily lose overview and step on each others
toes when their code is spread across the code base surrounded by
the code of others.

*delta.js* helps you organize your JavaScript code in terms of *features*.
As it turns out, files, modules, objects, functions (and so on), are not
the right abstractions for describing a feature. But they are very good at
other stuff! This library introduces the notion of a *delta*, which complements
those other constructs.

A delta is the place to gather all the code belonging to a specific feature.
Basically, for each piece of code, you instruct the delta to put that code in
the file, module, object or function where it belongs. That way, the code
can *physically* be gathered in one place, and therefore be easy to maintain.

This has other benefits as well. By having some deltas be explicitly applied
*after* others, you give them permission to overwrite things.
If two deltas that are *unordered* try to overwrite each others code,
you will get a friendly error message. Moreover, by separating your features
so explicitly, you will be able to turn them on or off with a switch, for
either debugging or production.

This might all seem overly complicated at first. But once you get started,
you'll soon fall in love with this approach.

At this time, delta.js is a runtime library. But in concept, deltas could be
applied by a preprocessor. This will be supported by a future version.

## Installation

This library depends only on the [Babel ES6 polyfill](https://babeljs.io/docs/usage/polyfill/). For your convenience, a delta.js version is provided with this polyfill already baked in, but you also have the option of providing it yourself.

### Install using Bower

`delta.js` is available as a [Bower](http://bower.io/) package:

```shell
bower install delta.js
```

Unfortunately, the Babel polyfill is [not distributed through Bower](https://github.com/babel/babel/issues/315). So you'll have to either use the version of delta.js with the polyfill baked in, or you'll have to get the polyfill from someplace else, like NPM.

### Install using NPM

`delta.js` is available as an [NPM](https://www.npmjs.org) package:

```shell
npm install delta.js
```

## Importing `DeltaJs`

The delta.js package offers a [UMD](https://github.com/umdjs/umd) API, so it supports
AMD ([RequireJS](http://requirejs.org/)), CommonJS and script-tags:

```javascript
requirejs(['lib/delta.js/dist/delta.js'], function (DeltaJs) {
    // use DeltaJs
});
```

```javascript
var DeltaJs = require('lib/delta.js/dist/delta.js')
// use DeltaJs
```

```html
<script src="lib/delta.js/dist/delta.js"></script>
<!-- use DeltaJs -->
```

###Files

The `dist` directory offers different files for use in different circumstances.
Use the following table to determine which file to use in your situation.

| File                          | Description                                                                      |
| ----------------------------- | -------------------------------------------------------------------------------- |
| `delta.js`,
`delta.min.js` | requires you to load the [Babel polyfill](https://babeljs.io/docs/usage/polyfill/) yourself |
| `delta.full.js`,
`delta.full.min.js` | already includes the Babel polyfill |

If you don't know which you need, you probably want `delta.full.min.js`, because it will work out-of-the-box. But it is generally more elegant to load the polyfill yourself, especially if you use other libraries that depend on it.

## Using `DeltaJs`

`DeltaJs` is a class that can be instantiated:

```javascript
var deltaJs = new DeltaJs();
```

`deltaJs` is a context within which all new types of delta operation and all project-specific
features are localized. It is also home to a core *delta model*, which is the structure that
organizes and orders a set of deltas.
Using multiple `DeltaJs` instances allows you to use different sets of deltas and rules in
the same project that work independently from each other. But you'll usually need only one.

## The `DeltaJs` API

Given a `DeltaJs` instance, the following methods are available:

### `.vp(name, initialValue)`

This method creates a *variation point*. It should be used in your code-base wherever
deltas may need to make changes. Each variation point needs a unique name for
deltas to refer to. The method modifies a value 'in place', and does not make
a copy. For example:

```javascript
function MyClass() {
    this.someMethod = function () {};
    this.someField  = 'some value';
};
deltaJs.vp('MyClass', MyClass);
```

This allows the selected deltas to modify the `MyClass` class, as well as all of its
properties. The `.vp` method also returns the new value. So the following is equivalent
to the example above:

```javascript
var MyClass = deltaJs.vp('MyClass', function MyClass() {
    this.someMethod = function () {};
    this.someField  = 'some value';
});
```

### `.do(name, [options])`

This function returns a `Proxy` interface that may be used to easily create
new deltas / operations in a core delta model that can then target specific
variation points:

```javascript
var proxy = deltaJs.do('cool-feature', {
    // options
});
```

This `proxy` variable can then be used to specify the modifications its
corresponding delta should perform, and where to perform them. For example:

```javascript
proxy.add('MyClass.prototype.coolMethod', function () {
	// do something cool
}).insert('MyClass.prototype.construct', function () {
	this.coolMethod();
});
```

So when the `'cool-feature'` is selected, this delta adds the new `coolMethod` method
to `MyClass`, and ensures that it is called by the existing `construct` method.
A comprehensive list of these operations and how to use them follows later in this document.

Like variation points, deltas in a delta model need a unique name. But deltas and variation
points have separate namespaces. In other words: you may give a delta and a variation
point the same name. (Thought if you find yourself doing this often, you may not have
fully understood the point of delta.js.)

Note: For the sake of simplicity, you may assume that deltas and features are the same thing. More advanced users may have reasons to see them as separate entities by providing the option feature: false, but because this option defaults to true, the code above defines both a feature and a delta with the name 'cool-feature', and links them one-to-one. Usually, you don't need to be aware of this, and may treat features and deltas as interchangeable concepts.

#### Predicates

Before listing the supported options, let's briefly describe the notion of 'predicate',
a type of data accepted by several of those options.
A predicate is a condition on the set of selected features, and can be
given as one of the following:

* the value `true`
* the value `false`
* an array of feature-names, interpreted as a conjunction. The condition is true exactly if *all* features in the list are selected.

#### Supported Options

The following options may be passed:

| options              | default   | meaning
| -------------------- | --------- | -------
| `feature`            | `true`    | a Boolean, specifying whether a feature with the same name should be linked to this delta
| `if`                 | `false`   | a predicate, specifying when (if ever) this delta should be automatically selected
| `onlyIf`             | `true`    | a predicate that is required to hold if this delta is ever selected. If this delta is ever selected without this predicate being met, an error will be thrown whenever this delta is applied.
| `after`              | `[]`      | a list of delta names. This delta is guaranteed to be applied after the deltas in the list. If the registration of this delta creates an application order *cycle*, an error will be thrown.
| `selects`            | `[]`      | a list of delta names. If this delta is selected, all deltas in this list will also be selected.

For convenience, there are some options that combine multiple of the above:

| options     | combines
| ----------- | --------
| `iff`       | `if` and `onlyIf`
| `requires`  | `after` and `selects`
| `resolves`  | `if`, `onlyIf` and `after`; and sets `feature` to `false`

Deltas representing specific changes to the variation points can be created through
various operations through the `Proxy` API described below.

### `.select(...deltaNames)`

This method can be used to manually select specific features by name.

```javascript
deltaJs.select('cool-feature', 'silly-feature', 'debugging-patch-359');
```

Other features and deltas, if they are linked with the features given,
can be automatically pulled in through any `if` or `selects` options.

Note that a feature needs to be registered before it can be selected. And a delta needs to be
selected before the appearance of any variation point to which it applies. It is probably
something you want to do very early in your application.

## The `Proxy` API

Deltas can modify values in any number of ways, from completely
replacing them with other values, to making fine-grained modifications in a deeply nested
object. It does so through well-defined *operations*, which you can specify through the
various methods of a `Proxy` instance.

Every delta *targets* a specific JavaScript object, which we'll denote as `target` in the
descriptions below. All operations of that delta act on one of the properties of `target`.
The deltas constructed directly from the delta model target an imaginary root object that
contains all variation points as properties. We'll denote this object as `root`.

### `.modify(key)`

This method returns another `Proxy` object that targets `target[key]`,
allowing us to *step into* a sub-object to make fine-grained modifications
inside:

```javascript
var d1 = deltaJs.do('my-delta');         // d1 targets 'root'
var d2 = d1.modify('vp1');               // d2 targets 'root.vp1'
var d3 = d2.modify('foo').modify('bar'); // d3 targets 'root.vp1.foo.bar'
```

For convenience, the `key` can also be given as a dot-separated list:

```javascript
var d4 = d1.modify('vp1.foo.bar');       // d4 also targets 'root.vp1.foo.bar'
```

The `key` is then usually referred to as a *path*.
This also works for the all the other operations below. It implicitly
constructs a `.modify` chain to reach the right-most key.

Note: Because of this shorthand notation, property names that actually
contain the . character are not supported (at least for now). If there is any need for this to change, please open a GitHub issue.

When you've targeted the proper object, you can use the operations described
below to make specific changes to its properties.

### `.add(key, newValue)`

This makes the delta *add* a new property `key` to `target`, such that `target[key] === newValue`.
Before the operation, it is expected that `typeof target[key] === 'undefined'`. In other words,
it cannot already have a property named `key`.

```javascript
delta.modify('my-vp.foo').add('bar', 'bas');
var value = vp('my-vp', { foo: {}, bar: [] });
expect(value).toEqual({ foo: { bar: 'bas' }, bar: [] });
```

### `.remove(key)`

This makes the delta *remove* the property named `key` from `target`, such that `typeof target[key] === 'undefined'`.
Before the operation, it is expected that `typeof target[key] !== 'undefined'`. In other words, it
must first *have* a property named `key`.

```javascript
delta.modify('my-vp').remove('foo');
var value = vp('my-vp', { foo: { bar: 'bas' }, bar: [] });
expect(value).toEqual({ bar: [] });
```

### `.replace(key, newValue)`

This makes the delta *replace* the property named `key` in `target`, such that `target[key] === value`.
Before the operation, it is expected that `typeof target[key] !== 'undefined'`. In other words, it
must already *have* a property named `key`.

```javascript
delta.modify('my-vp').replace('foo', 'bar');
var value = vp('my-vp', { foo: { bar: 'bas' }, bar: [] });
expect(value).toEqual({ foo: 'bar', bar: [] });
```

### `.prepend(key, newValue)`
### `.append(key, newValue)`
### `.insert(key, newValue)`

These methods work if `target[key]` is an *array* or a *function*,
and respectively prepend, append or insert `newValue` into it.

If `target[key]` is a function, `newValue` also needs to be a function,
which will then be set up to run in the position where it is placed,
and provided with the same arguments and `this` context of the original
function-call.

The `.prepend` operation places the value in the beginning,
and `.append` places it at the end of the existing array / function.

The `.insert` operation is special, because it gives the delta the
freedom to put the value in an arbitrary position; you don't have
any control over the placement.
The advantage of `.insert` is that the order between multiple
insertions does not matter. As far as delta.js is concerned,
`d.insert('f', fn1).insert('f', fn2)` and `d.insert('f', fn2).insert('f', fn1)`
are equivalent. Moreover, two unordered deltas can insert things into the same
array or function without this being regarded as a conflict.

For example, for an array:

```javascript
delta.modify('my-vp').append('a', 999).prepend('a', -999);
var value = vp('my-vp', {
    a: [1, 2, 3]
});
expect(value).toEqual({
	a: [-999, 1, 2, 3, 999]
});
```

And for a function:

```javascript
delta.modify('my-vp').append('f', function (a, b) {
    doOtherThings(a, b);
});
var value = vp('my-vp', {
    f: function (a, b, c) {
        doThings(b, c);
    }
});
```
The variable `value` will be equivalent to:
```javascript
{
    f: function () {
        (function (a, b, c) {
            doThings(a, b);
        }).apply(this, arguments);
        (function (a, b) {
            doOtherThings(a, b);
        }).apply(this, arguments);
    }
}
```

delta.js cannot actually add statements to existing functions. Instead,
it defines a new function, which calls the original and the added function
in the proper order, properly passing the function arguments and `this`
context to both. This has some consequences:

* Local variables are not shared across function 'parts'. 'Function-part local' is also 'delta local'.
* All non-standard properties of a function are lost after a `.prepend`, `.append` or `.insert`.
  If this is undesirable, it is recommended that the original function is written to call
  an auxiliary function, so the delta operations can apply to the auxiliary. For class
  constructors, it is recommended that you use a function `Class.prototype.construct` for
  this purpose:

```javascript
function MyClass() { this.construct.apply(this, arguments) }
MyClass.prototype.construct = function () {};
deltaJs.vp('MyClass', MyClass)
```
```javascript
deltaJs.do('my-delta').append('MyClass.prototype.construct', function (a, b, c) {
    this.doExtraThings(a, b, c);
});
```

## Future Plans

Here is an incomplete list of future plans for this library:

* support for changing HTML and CSS with deltas
* transpiler to resolve deltas at build-time

## License

`delta.js` is released under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
It permits reuse within both open and proprietary software, provided
all copies of the licensed software include a copy of the MIT License
terms and the copyright notice.


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ThreadSafeSplitMesh {

    Dictionary<string, short> mappings = new Dictionary<string, short>();

    public Dictionary<short, MeshInfo> Split(MeshInfo mesh, KDTree tree, List<Vector3> voxels, short[,,] colourings, ThreadSafeVoxelisation.GridSize size) {

        Dictionary<short, Dictionary<string, int>> meshFoundIndices = new Dictionary<short, Dictionary<string, int>>();
        Dictionary<short, List<Vector3>> meshVertices = new Dictionary<short, List<Vector3>>();
        Dictionary<short, List<int>> meshIndices = new Dictionary<short, List<int>>();
        Dictionary<short, List<Vector3>> meshEdges = new Dictionary<short, List<Vector3>>();

        int[] tris = mesh.index;
        Vector3[] verts = mesh.verts;

        for (int i = 0; i < tris.Length; i += 3) {

            Vector3 v1 = verts[tris[i]];
            Vector3 v2 = verts[tris[i + 1]];
            Vector3 v3 = verts[tris[i + 2]];

            short c1 = nearestColour(toVoxelSpace(v1, size, 0.5f), tree, voxels, colourings);
            short c2 = nearestColour(toVoxelSpace(v2, size, 0.5f), tree, voxels, colourings);
            short c3 = nearestColour(toVoxelSpace(v3, size, 0.5f), tree, voxels, colourings);

            if (c1 == c2 && c1 == c3) {
                Dictionary<string, int> foundIndices;
                if (!(meshFoundIndices.TryGetValue(c1, out foundIndices))) {
                    foundIndices = new Dictionary<string, int>();
                    meshFoundIndices.Add(c1, foundIndices);
                }

                List<Vector3> vertices;
                if (!(meshVertices.TryGetValue(c1, out vertices))) {
                    vertices = new List<Vector3>();
                    meshVertices.Add(c1, vertices);
                }

                List<int> indices;
                if (!(meshIndices.TryGetValue(c1, out indices))) {
                    indices = new List<int>();
                    meshIndices.Add(c1, indices);
                }

                StoreVertex(v1, foundIndices, indices, vertices);
                StoreVertex(v2, foundIndices, indices, vertices);
                StoreVertex(v3, foundIndices, indices, vertices);

            } else {
                if (c1 == c2) {
                    List<Vector3> edges;
                    if (!(meshEdges.TryGetValue(c1, out edges))) {
                        edges = new List<Vector3>();
                        meshEdges.Add(c1, edges);
                    }
                    edges.Add(v1);
                    edges.Add(v2);
                    edges.Add(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity));
                }
                if (c1 == c3) {
                    List<Vector3> edges;
                    if (!(meshEdges.TryGetValue(c1, out edges))) {
                        edges = new List<Vector3>();
                        meshEdges.Add(c1, edges);
                    }
                    edges.Add(v1);
                    edges.Add(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity));
                    edges.Add(v3);
                }
                if (c2 == c3) {
                    List<Vector3> edges;
                    if (!(meshEdges.TryGetValue(c2, out edges))) {
                        edges = new List<Vector3>();
                        meshEdges.Add(c2, edges);
                    }
                    edges.Add(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity));
                    edges.Add(v2);
                    edges.Add(v3);
                }
            }

        }

        Dictionary<short, MeshInfo> output = new Dictionary<short, MeshInfo>();

        foreach (short s in meshFoundIndices.Keys) {
            List<Vector3> vertices;
            meshVertices.TryGetValue(s, out vertices);

            List<int> indices;
            meshIndices.TryGetValue(s, out indices);

            List<Vector3> edges;
            meshEdges.TryGetValue(s, out edges);

            Fragment c = new Fragment(s);

            c.vertices.AddRange(edges);

            output.Add(s, new MeshInfo(vertices.ToArray(), indices.ToArray(), c));

        }

        return output;
    }

    private Vector3 toVoxelSpace(Vector3 worldSpace, ThreadSafeVoxelisation.GridSize size, float scale) {
        float side = size.side;

        Vector3 mid = new Vector3(size.x * 0.5f, size.y * 0.5f, size.z * 0.5f);

        return new Vector3(worldSpace.x * size.x * scale, worldSpace.y * size.y * scale, worldSpace.z * size.z * scale) + mid;

    }

    private short nearestColour(Vector3 vert, KDTree tree, List<Vector3> voxels, short[,,] colourings) {
        short colour;
        if (mappings.TryGetValue(vert.x+","+vert.y+","+vert.z, out colour)) {
            return colour;
        } else {
            int index = tree.FindNearest(vert);
            Vector3 voxel = voxels[index];
            mappings.Add(vert.x+","+vert.y+","+vert.z, colourings[(int)voxel.x, (int)voxel.y, (int)voxel.z]);
            return colourings[(int)voxel.x, (int)voxel.y, (int)voxel.z];
        }

    }

    void StoreVertex(Vector3 vertex, Dictionary<string, int> foundIndices, List<int> indices, List<Vector3> vertices) {
        int idx = vertices.Count;

        string points = vertex.x + "," + vertex.y + "," + vertex.z;
        int index = -1;

        bool found = foundIndices.TryGetValue(points, out index);

        if (found) {
            indices.Add(index);
        } else {
            indices.Add(idx);
            vertices.Add(vertex);
            foundIndices.Add(points, idx);
        }
    }
}


text:
@interface Notification : JSONModel

@property(nonatomic, strong) NSNumber<Ignore>* identifier;
@property(nonatomic, strong) Contact* contact;
@property(nonatomic, strong) NSNumber* type;
@property(nonatomic, strong) NSString<Optional>* content;
@property(nonatomic, strong) NSDate<Optional>* date;
@property(nonatomic) BOOL read;

-(NSString *) typeToString;

@end


text:
package com.impetus.client.entities;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * The Class Person.
 */
@Entity
@Table(name = "PERSON", schema = "RedisK@redis_pu")
public class PersonOTORedis
{

    /** The person id. */
    @Id
    @Column(name = "PERSON_ID")
    private String personId;

    /** The person name. */
    @Column(name = "PERSON_NAME")
    private String personName;

    /** The age. */
    @Column(name = "AGE")
    private Integer age;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "ADDRESS_ID")
    private AddressOTORedis address;

    public PersonOTORedis(String personId)
    {
        this.personId = personId;
    }

    public PersonOTORedis()
    {

    }

    /**
     * Gets the person id.
     *
     * @return the person id
     */
    public String getPersonId()
    {
        return personId;
    }

    /**
     * Gets the person name.
     *
     * @return the person name
     */
    public String getPersonName()
    {
        return personName;
    }

    /**
     * Sets the person name.
     *
     * @param personName
     *            the new person name
     */
    public void setPersonName(String personName)
    {
        this.personName = personName;
    }

    /**
     * Sets the person id.
     *
     * @param personId
     *            the new person id
     */
    public void setPersonId(String personId)
    {
        this.personId = personId;
    }

    /**
     * @return the age
     */
    public Integer getAge()
    {
        return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(int age)
    {
        this.age = age;
    }

    public AddressOTORedis getAddress()
    {
        return address;
    }

    public void setAddress(AddressOTORedis address)
    {
        this.address = address;
    }

    public void setAge(Integer age)
    {
        this.age = age;
    }

}


text:
<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\TemplateMethod;

abstract class Journey
{
    /**
     * @var string[]
     */
    private array $thingsToDo = [];

    /**
     * This is the public service provided by this class and its subclasses.
     * Notice it is final to "freeze" the global behavior of algorithm.
     * If you want to override this contract, make an interface with only takeATrip()
     * and subclass it.
     */
    final public function takeATrip()
    {
        $this->thingsToDo[] = $this->buyAFlight();
        $this->thingsToDo[] = $this->takePlane();
        $this->thingsToDo[] = $this->enjoyVacation();
        $buyGift = $this->buyGift();

        if ($buyGift !== null) {
            $this->thingsToDo[] = $buyGift;
        }

        $this->thingsToDo[] = $this->takePlane();
    }

    /**
     * This method must be implemented, this is the key-feature of this pattern.
     */
    abstract protected function enjoyVacation(): string;

    /**
     * This method is also part of the algorithm but it is optional.
     * You can override it only if you need to
     */
    protected function buyGift(): ?string
    {
        return null;
    }

    private function buyAFlight(): string
    {
        return 'Buy a flight ticket';
    }

    private function takePlane(): string
    {
        return 'Taking the plane';
    }

    /**
     * @return string[]
     */
    public function getThingsToDo(): array
    {
        return $this->thingsToDo;
    }
}


text:
import { settings } from 'carbon-components';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

const { prefix } = settings;

function Popover({
  as: BaseComponent = 'div',
  caret = true,
  className: customClassName,
  children,
  align = 'bottom',
  highContrast = false,
  light = false,
  open,
  relative,
  ...rest
}) {
  const className = cx({
    [`${prefix}--popover`]: true,
    [`${prefix}--popover--caret`]: caret,
    [`${prefix}--popover--light`]: light,
    [`${prefix}--popover--high-contrast`]: highContrast,
    [`${prefix}--popover--${align}`]: true,
    [`${prefix}--popover--open`]: open,
    [`${prefix}--popover--relative`]: relative,
    [customClassName]: !!customClassName,
  });

  return (
    <BaseComponent {...rest} className={className}>
      {children}
    </BaseComponent>
  );
}

Popover.displayName = 'Popover';
Popover.propTypes = {
  /**
   * Specify how the popover should align with the trigger element
   */
  align: PropTypes.oneOf([
    'top',
    'top-left',
    'top-right',

    'bottom',
    'bottom-left',
    'bottom-right',

    'left',
    'left-bottom',
    'left-top',

    'right',
    'right-bottom',
    'right-top',
  ]),

  /**
   * Provide a custom element or component to render the top-level node for the
   * component.
   */
  as: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),

  /**
   * Specify whether a caret should be rendered
   */
  caret: PropTypes.bool,

  /**
   * Provide elements to be rendered inside of the component
   */
  children: PropTypes.node,

  /**
   * Provide a custom class name to be added to the outermost node in the
   * component
   */
  className: PropTypes.string,

  /**
   * Render the component using the high-contrast variant
   */
  highContrast: PropTypes.bool,

  /**
   * Render the component using the light variant
   */
  light: PropTypes.bool,

  /**
   * Specify whether the component is currently open or closed
   */
  open: PropTypes.bool.isRequired,

  /**
   * Specify whether the component should be positioned using position:
   * relative. By default, it will use position: absolute
   */
  relative: PropTypes.bool,
};

const PopoverContent = React.forwardRef(function PopoverContent(
  { as: BaseComponent = 'div', className, children, ...rest },
  ref
) {
  return (
    <BaseComponent
      {...rest}
      className={cx(`${prefix}--popover-contents`, className)}
      ref={ref}>
      {children}
    </BaseComponent>
  );
});

PopoverContent.displayName = 'PopoverContent';

PopoverContent.propTypes = {
  /**
   * Provide a custom element or component to render the top-level node for the
   * component.
   */
  as: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),

  /**
   * Provide elements to be rendered inside of the component
   */
  children: PropTypes.node,

  /**
   * Provide a custom class name to be added to the outermost node in the
   * component
   */
  className: PropTypes.string,
};

export { Popover, PopoverContent };


text:
package uk.co.listpoint.context;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ContextStartNewDraftResponse6Type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ContextStartNewDraftResponse6Type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="NewContextName" type="{http://www.listpoint.co.uk/messages/Context}FullName6Structure" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ContextStartNewDraftResponse6Type", namespace = "http://www.listpoint.co.uk/messages/Context", propOrder = {
    "newContextName"
})
public class ContextStartNewDraftResponse6Type {

    @XmlElement(name = "NewContextName")
    protected FullName6Structure2 newContextName;

    /**
     * Gets the value of the newContextName property.
     *
     * @return
     *     possible object is
     *     {@link FullName6Structure2 }
     *
     */
    public FullName6Structure2 getNewContextName() {
        return newContextName;
    }

    /**
     * Sets the value of the newContextName property.
     *
     * @param value
     *     allowed object is
     *     {@link FullName6Structure2 }
     *
     */
    public void setNewContextName(FullName6Structure2 value) {
        this.newContextName = value;
    }

}


text:
cask 'keep-it' do
  version '1.8.9'
  sha256 '17202677e7c3aea79f366b088784f615bd5fe2cff17e611fcf2bacdd27025713'

  url "https://reinventedsoftware.com/keepit/downloads/KeepIt_#{version}.dmg"
  appcast 'https://reinventedsoftware.com/keepit/downloads/keepit.xml'
  name 'Keep It'
  homepage 'https://reinventedsoftware.com/keepit/'

  auto_updates true
  depends_on macos: '>= :high_sierra'

  app 'Keep It.app'

  zap trash: [
               '~/Library/Containers/com.reinvented.Keep-It-Indexing',
               '~/Library/Containers/com.reinvented.Keep-It-Metadata',
               '~/Library/Containers/com.reinvented.Keep It',
             ]
end


text:
Connection::Connection()  {
    int PORT;
    std::cout << "What port number? ";
    std::cin >> PORT;

    int tempSockfd, portno;
    socklen_t clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    tempSockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (tempSockfd < 0)
       std::cout << "ERROR opening socket";
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(PORT);
    if (bind(tempSockfd, (struct sockaddr *) &serv_addr,
             sizeof(serv_addr)) < 0)
    		std::cout << "ERROR on binding";
    listen(tempSockfd,5);
    clilen = sizeof(cli_addr);
    std::cout << "Waiting for connection\n";
    socketFd = accept(tempSockfd,
                (struct sockaddr *) &cli_addr,
                &clilen);

    std::cout << "Recieved connection\n";
    if (socketFd < 0)
    	std::cout << "ERROR on accept";
}

Connection::~Connection() {
	disconnect();
}

double Connection::getReward() {
	std::string currentLine = getString();
	std::cout << "lineL " << currentLine << "\n";
	while(currentLine.compare("4") != 0) {
		std::cout << "line: " << currentLine << "\n";
	}
	return atof(getString().c_str());
}

void Connection::disconnect() {
	close(socketFd);
}

std::string Connection::getString() {
	std::string newString = "";
	char buffer;

	// Keep reading char by char until a newline
	while(true) {
		read(socketFd, &buffer, 1);

		std::cout << buffer;

		if (buffer == '\n') break;
		else newString += buffer;
	}

	return newString;
}