%% Rubis
-define(GROUPING_SEP, <<"+">>).
-define(ID_SEP, <<"@">>).
-define(FIELD_SEP, <<"/">>).

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 25).

%% Amount of Transaction metadata kept
-define(VERSION_THRESHOLD, 500).
-define(MAX_VERSIONS, 100).

%% Size of active listener pool for the protocol buffer server
-define(COORD_PB_POOL, (1 * erlang:system_info(schedulers_online))).
%% Port number for protocol buffer sever
-define(COORD_PB_PORT, 7878).

Add documentation to PVC log limits

%% Rubis
-define(GROUPING_SEP, <<"+">>).
-define(ID_SEP, <<"@">>).
-define(FIELD_SEP, <<"/">>).

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 25).

%% Amount of Transaction metadata kept for the Version and Commit log
%%
%% VERSION_THRESHOLD specifies the point where the logs will perform a GC
%% The lower this number is set, the more common GC will become.
%%
%% MAX_VERSIONS specifies the number of versions kept in the logs after a GC
%%
%% So, every time VERSION_THRESHOLD versions are reached, we will remove all
%% versions, except for last MAX_VERSIONS.
-define(VERSION_THRESHOLD, 500).
-define(MAX_VERSIONS, 100).

%% Size of active listener pool for the protocol buffer server
-define(COORD_PB_POOL, (1 * erlang:system_info(schedulers_online))).
%% Port number for protocol buffer sever
-define(COORD_PB_PORT, 7878).


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (action_disable_selection).
-include_lib ("wf.hrl").
-compile(export_all).

render_action(_Record) ->
    "Nitrogen.$disable_selection(obj(me));".

Fix js typoe in disable_selection

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (action_disable_selection).
-include_lib ("wf.hrl").
-compile(export_all).

render_action(_Record) ->
    "Nitrogen.$disable_selection(obj('me'));".


-module( largest_series_product_tests ).
-include_lib("eunit/include/eunit.hrl").

three_test() -> ?assert( 504 =:= largest_series_product:from_string("0123456789", 3) ).

five_test() -> ?assert( 15120 =:= largest_series_product:from_string("0123456789", 5) ).

six_test() -> ?assert( 23520 =:= largest_series_product:from_string("73167176531330624919225119674426574742355349194934", 6) ).

Add tests where result is zero

-module( largest_series_product_tests ).
-include_lib("eunit/include/eunit.hrl").

three_test() -> ?assert( 504 =:= largest_series_product:from_string("0123456789", 3) ).

five_test() -> ?assert( 15120 =:= largest_series_product:from_string("0123456789", 5) ).

six_test() -> ?assert( 23520 =:= largest_series_product:from_string("73167176531330624919225119674426574742355349194934", 6) ).

all_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("0000", 2) ).

all_contain_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("99099", 3) ).


%% @doc Top-level module doc.
%% @end
-module(edoc_example).
-export([f/0]).

-include_lib("docsh/include/docsh.hrl").

-type l(A) :: list(A).
-type l() :: list().

-type r() :: ok.

%% @doc Doc for f/0.
%% @end
-spec f() -> r().
f() ->
    ok.

Add example of a type description extractable by EDoc

%% @doc Top-level module doc.
%% @end
-module(edoc_example).
-export([f/0]).

-include_lib("docsh/include/docsh.hrl").

-type l(A) :: list(A).
-type l() :: list().

%% @type r(). Doc for type r().
-type r() :: ok.

%% @doc Doc for f/0.
%% @end
-spec f() -> r().
f() ->
    ok.


-module(tag_analysis_sup).

-behaviour(supervisor).

-export([start_link/0]).

-export([init/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

rest() ->
    RestDispatch = [{'_', [
        {[<<"tag">>, tag], tag_analysis, []}
    ]}],
    RestConfig = [rest_listener, 100,
        [{port, 10001}],
        [{dispatch, RestDispatch}]],
    {rest, {cowboy, start_http, RestConfig}, permanent, 5000, supervisor, dynamic}.

init([]) ->
    Pool = poolboy:child_spec(tag_analysis_pool,
        [
            {name, {local, tag_analysis_pool}},
            {worker_module, tag_analysis_pg},
            {size, 3},
            {max_overflow, 10}
        ],
        [
            {hostname, "127.0.0.1"},
            {database, "airship_dict"},
            {username, "airship_dict"},
            {password, "TEMP_PASS_1234"}
        ]),
    {ok, { {one_for_one, 5, 10}, [Pool, rest()]} }.

Change from /tag => /tags

-module(tag_analysis_sup).

-behaviour(supervisor).

-export([start_link/0]).

-export([init/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

rest() ->
    RestDispatch = [{'_', [
        {[<<"tags">>, tag], tag_analysis, []}
    ]}],
    RestConfig = [rest_listener, 100,
        [{port, 10001}],
        [{dispatch, RestDispatch}]],
    {rest, {cowboy, start_http, RestConfig}, permanent, 5000, supervisor, dynamic}.

init([]) ->
    Pool = poolboy:child_spec(tag_analysis_pool,
        [
            {name, {local, tag_analysis_pool}},
            {worker_module, tag_analysis_pg},
            {size, 3},
            {max_overflow, 10}
        ],
        [
            {hostname, "127.0.0.1"},
            {database, "airship_dict"},
            {username, "airship_dict"},
            {password, "TEMP_PASS_1234"}
        ]),
    {ok, { {one_for_one, 5, 10}, [Pool, rest()]} }.


-module(rebar_packages).

-export([get_packages/1]).

-export_type([package/0]).

-include("rebar.hrl").

-type pkg_name() :: binary() | atom().
-type vsn() :: binary().
-type package() :: pkg_name() | {pkg_name(), vsn()}.

-spec get_packages(rebar_state:t()) -> {rebar_dict(), rebar_digraph()}.
get_packages(State) ->
    RebarDir = rebar_dir:global_config_dir(State),
    PackagesFile = filename:join(RebarDir, "packages"),
    case ec_file:exists(PackagesFile) of
        true ->
            try
                {ok, Binary} = file:read_file(PackagesFile),
                {Dict, Graph} = binary_to_term(Binary),
                {Dict, rebar_digraph:restore_graph(Graph)}
            catch
                _:_ ->
                    ?ERROR("Bad packages index, try to fix with `rebar update`", []),
                    {dict:new(), digraph:new()}
            end;
        false ->
            {dict:new(), digraph:new()}
    end.

Fix error message to point to rebar3

-module(rebar_packages).

-export([get_packages/1]).

-export_type([package/0]).

-include("rebar.hrl").

-type pkg_name() :: binary() | atom().
-type vsn() :: binary().
-type package() :: pkg_name() | {pkg_name(), vsn()}.

-spec get_packages(rebar_state:t()) -> {rebar_dict(), rebar_digraph()}.
get_packages(State) ->
    RebarDir = rebar_dir:global_config_dir(State),
    PackagesFile = filename:join(RebarDir, "packages"),
    case ec_file:exists(PackagesFile) of
        true ->
            try
                {ok, Binary} = file:read_file(PackagesFile),
                {Dict, Graph} = binary_to_term(Binary),
                {Dict, rebar_digraph:restore_graph(Graph)}
            catch
                _:_ ->
                    ?ERROR("Bad packages index, try to fix with `rebar3 update`", []),
                    {dict:new(), digraph:new()}
            end;
        false ->
            {dict:new(), digraph:new()}
    end.


-module(eavro_rpc_proto_tests).

-include("eavro.hrl").

-include_lib("eunit/include/eunit.hrl").

parse_flume_proto_test() ->
    Proto = eavro_rpc_proto:parse_protocol_file("../test/data/flume.avpr"),
    ?assertMatch(
       #avro_proto{ ns       = <<"org.apache.flume.source.avro">>,
		    name     = <<"AvroSourceProtocol">>,
		    types    = [_ | _],
		    messages = [#avro_message{} | _],
		    json     = <<_,_/binary>>}, Proto).

Add RPC test against Java e-mail server.

-module(eavro_rpc_proto_tests).

-include("eavro.hrl").

-include_lib("eunit/include/eunit.hrl").

parse_flume_proto_test() ->
    Proto = eavro_rpc_proto:parse_protocol_file("../test/data/flume.avpr"),
    ?assertMatch(
       #avro_proto{ ns       = <<"org.apache.flume.source.avro">>,
		    name     = <<"AvroSourceProtocol">>,
		    types    = [_ | _],
		    messages = [#avro_message{} | _],
		    json     = <<_,_/binary>>}, Proto).

call_email_server_test_() ->
    {timeout, 30,
     fun()->
	     Port = erlang:open_port(
		      {spawn, "mvn exec:java -Dexec.mainClass=\"email.Main\""},
		      [{cd, "../jtest"},
		       {env, []},
		       binary,
		       stream,
		       {parallelism, true},
		       exit_status]),
	     try
		 ok = await_start_finished(Port),
		 {ok, P} = eavro_rpc_fsm:start_link(
			     "localhost", 65111, "../jtest/src/main/avro/mail.avpr"),
		 Ret = eavro_rpc_fsm:call(
			 P, send,
			 _Args = [ _Rec = [ <<"TOOOO">>, <<"FROOOOOM">>, <<"HELLO">> ] ]),
		 ?assertMatch({ok, <<"Sending ",_/binary>>}, Ret)
	     after
		 erlang:port_close(Port)
	     end
     end}.

await_start_finished(Port) ->
    receive
	{Port, {data, <<"Server started",_/binary>>}} -> ok;
	{Port, {data, _}} ->
	    await_start_finished(Port)
    end.


-module(lmq_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-define(CHILD(I, Type, Args), {I, {I, start_link, Args}, permanent, 5000, Type, [I]}).

%% ===================================================================
%% API functions
%% ===================================================================

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%% ===================================================================
%% Supervisor callbacks
%% ===================================================================

init([]) ->
    {ok, InfluxDB} = application:get_env(influxdb),
    Host = proplists:get_value(host, InfluxDB),
    Port = proplists:get_value(port, InfluxDB),

    {ok, {{one_for_all, 5, 10},
          [?CHILD(lmq_queue_supersup, supervisor),
           ?CHILD(lmq_mpull_sup, supervisor),
           ?CHILD(lmq_event, worker),
           ?CHILD(lmq_hook, worker),
           ?CHILD(influxdb_client, worker, [Host, Port])]}}.

Fix start-up order to avoid the crash

-module(lmq_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-define(CHILD(I, Type, Args), {I, {I, start_link, Args}, permanent, 5000, Type, [I]}).

%% ===================================================================
%% API functions
%% ===================================================================

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%% ===================================================================
%% Supervisor callbacks
%% ===================================================================

init([]) ->
    {ok, InfluxDB} = application:get_env(influxdb),
    Host = proplists:get_value(host, InfluxDB),
    Port = proplists:get_value(port, InfluxDB),

    {ok, {{one_for_all, 5, 10},
          [?CHILD(lmq_event, worker),
           ?CHILD(lmq_hook, worker),
           ?CHILD(lmq_queue_supersup, supervisor),
           ?CHILD(lmq_mpull_sup, supervisor),
           ?CHILD(influxdb_client, worker, [Host, Port])]}}.


-record(rs3_user, {
          name :: binary(),
          key_id :: binary(),
          key_secret :: binary(),
          buckets = []}).

-record(rs3_bucket, {
          name :: binary(),
          creation_date :: term()}).

-record(context, {auth_bypass :: atom(),
                  auth_mod=riak_kv_passthru_auth :: atom(),
                  user :: #rs3_user{}}).

-define(USER_BUCKET, <<"moss.users">>).

Remove default value for auth_mod from context record.

-record(rs3_user, {
          name :: binary(),
          key_id :: binary(),
          key_secret :: binary(),
          buckets = []}).

-record(rs3_bucket, {
          name :: binary(),
          creation_date :: term()}).

-record(context, {auth_bypass :: atom(),
                  auth_mod :: atom(),

-define(USER_BUCKET, <<"moss.users">>).


% 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.

-module(twig_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init([]) ->
    {ok, { {one_for_one, 5, 10}, [?CHILD(twig_monitor, gen_server)]} }.

Fix type of child specification

% 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.

-module(twig_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init([]) ->
    {ok, { {one_for_one, 5, 10}, [?CHILD(twig_monitor, worker)]} }.


%% @copyright 2012 Opscode, Inc. All Rights Reserved
%% @author Tim Dysinger <timd@opscode.com>
%%
%% Licensed to the Apache Software Foundation (ASF) under one or more
%% contributor license agreements.  See the NOTICE file distributed
%% with this work for additional information regarding copyright
%% ownership.  The ASF licenses this file to you 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.

-include("amazon_s3.hrl").
-include("shorthand.hrl").
-include("test.hrl").
-include("types.hrl").

Add some useful 'constant' macros

%% @copyright 2012 Opscode, Inc. All Rights Reserved
%% @author Tim Dysinger <timd@opscode.com>
%%
%% Licensed to the Apache Software Foundation (ASF) under one or more
%% contributor license agreements.  See the NOTICE file distributed
%% with this work for additional information regarding copyright
%% ownership.  The ASF licenses this file to you 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.

-include("amazon_s3.hrl").
-include("shorthand.hrl").
-include("test.hrl").
-include("types.hrl").

-define(TIMEOUT_MS, 4096).
-define(BLOCK_SIZE, 16384).

-define(BACKEND, bookshelf_fs).


-module(holiday_ping_app).

-behaviour(application).

-export([start/2,
         stop/1]).

start(_StartType, _StartArgs) ->
    pgapp:connect(hp_config:get(pg_options)),

    Dispatch = cowboy_router:compile([
                                      {'_', [{"/", cowboy_static, {priv_file, holiday_ping, "/ui/index.html"}},
                                             {"/[...]", cowboy_static, {priv_dir, holiday_ping, "/ui"}},
                                             {"/api/users", user_handler, []},
                                             {"/api/auth/token", token_handler, []},
                                             {"/api/channels", channel_list_handler, []},
                                             {"/api/channels/:name", channel_detail_handler, []}]}
                                     ]),
    cowboy:start_http(my_http_listener, 100, [{port, hp_config:get(port)}],
                      [{env, [{dispatch, Dispatch}]}]
                     ),
    hp_sup:start_link().

stop(_State) ->
    ok.

Fix broken paths for static files

-module(holiday_ping_app).

-behaviour(application).

-export([start/2,
         stop/1]).

start(_StartType, _StartArgs) ->
    pgapp:connect(hp_config:get(pg_options)),

    Dispatch = cowboy_router:compile([
                                      {'_', [{"/", cowboy_static, {priv_file, holiday_ping, "/ui/index.html"}},
                                             {"/js/[...]", cowboy_static, {priv_dir, holiday_ping, "/ui/js"}},
                                             {"/css/[...]", cowboy_static, {priv_dir, holiday_ping, "/ui/css"}},
                                             {"/api/users", user_handler, []},
                                             {"/api/auth/token", token_handler, []},
                                             {"/api/channels", channel_list_handler, []},
                                             {"/api/channels/:name", channel_detail_handler, []}]}
                                     ]),
    cowboy:start_http(my_http_listener, 100, [{port, hp_config:get(port)}],
                      [{env, [{dispatch, Dispatch}]}]
                     ),
    hp_sup:start_link().

stop(_State) ->
    ok.


-module(stats).

-export([minimum/1]).

minimum([H | T]) ->
    minimum(T, H).

minimum([H | T], Min) when H < Min ->
    minimum(T, H);
minimum([_H | T], Min) ->
    minimum(T, Min);
minimum([], Min) ->
    Min.

Add documetation and spec signature for minimum.

%% @author Purity Control
%% @vsn 0.1
%% @doc an implementation of getting the minimum value from a list
-module(stats).

-export([minimum/1]).

%% doc return the minimum in a list. Throws an error on the empty list
-spec(minimum(nonempty_list(any())) -> any()).
minimum([H | T]) ->
    minimum(T, H).

minimum([H | T], Min) when H < Min ->
    minimum(T, H);
minimum([_H | T], Min) ->
    minimum(T, Min);
minimum([], Min) ->
    Min.


-module(basho_bench_driver_file).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

-record(state, { target_dir_path    % target dir to issue read/write syscalls
               }).

%% ====================================================================
%% API
%% ====================================================================

new(_Id) ->
    %% The IPs, port and path we'll be testing
    TargetDir = basho_bench_config:get(target_dir_path, ["./"]),
    filelib:ensure_dir(TargetDir),
    {ok, #state{ target_dir_path = TargetDir}}.

run(read, KeyGen, _ValueGen, State) ->
    NextFile = next_file(KeyGen, State),
    case file:read_file(NextFile) of
        {ok, _Binary} ->
            {ok, State};
        {error, Reason} ->
            {error, Reason, State}
    end;
run(write, KeyGen, ValueGen, State) ->
    NextFile = next_file(KeyGen, State),
    case file:write_file(NextFile, ValueGen()) of
        ok ->
            {ok, State};
        {error, Reason} ->
            {error, Reason, State}
    end.

next_file(KeyGen, #state{target_dir_path = TargetDir}) ->
    filename:join(TargetDir, KeyGen()).

Fix generating a file name

-module(basho_bench_driver_file).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

-record(state, { target_dir_path    % target dir to issue read/write syscalls
               }).

%% ====================================================================
%% API
%% ====================================================================

new(_Id) ->
    %% The IPs, port and path we'll be testing
    TargetDir = basho_bench_config:get(target_dir_path, ["./"]),
    filelib:ensure_dir(TargetDir),
    {ok, #state{ target_dir_path = TargetDir}}.

run(read, KeyGen, _ValueGen, State) ->
    NextFile = next_file(KeyGen, State),
    case file:read_file(NextFile) of
        {ok, _Binary} ->
            {ok, State};
        {error, Reason} ->
            {error, Reason, State}
    end;
run(write, KeyGen, ValueGen, State) ->
    NextFile = next_file(KeyGen, State),
    case file:write_file(NextFile, ValueGen()) of
        ok ->
            {ok, State};
        {error, Reason} ->
            {error, Reason, State}
    end.

next_file(KeyGen, #state{target_dir_path = TargetDir}) ->
    case KeyGen() of
        Key when is_list(Key) ->
            filename:join(TargetDir, Key);
        Key when is_integer(Key) ->
            filename:join(TargetDir, integer_to_list(Key));
        _ ->
            filename:join(TargetDir, [])
    end.


-module(mzb_string).

-export([
    format/2,
    char_substitute/3,
    str_to_bstr/1
]).

-spec format(Format :: string(), Args :: [term()]) -> FlatString :: string().
format(Format, Args) ->
    lists:flatten(io_lib:format(Format, Args)).

-spec char_substitute(string(), char(), char()) -> string().
char_substitute(String, OldChar, NewChar) ->
    lists:map(fun(Char) when Char =:= OldChar -> NewChar;
        (Char) -> Char end, String).

str_to_bstr(T) when is_list(T) ->
    case io_lib:printable_list(T) of
        true -> list_to_binary(T);
        false -> [str_to_bstr(X) || X <- T]
    end;
str_to_bstr(T) when is_map(T) ->
    maps:from_list([{str_to_bstr(K), str_to_bstr(V)} || {K, V} <- maps:to_list(T)]);
str_to_bstr(T) -> T.

Add empty array condition to str_to_bstr

-module(mzb_string).

-export([
    format/2,
    char_substitute/3,
    str_to_bstr/1
]).

-spec format(Format :: string(), Args :: [term()]) -> FlatString :: string().
format(Format, Args) ->
    lists:flatten(io_lib:format(Format, Args)).

-spec char_substitute(string(), char(), char()) -> string().
char_substitute(String, OldChar, NewChar) ->
    lists:map(fun(Char) when Char =:= OldChar -> NewChar;
        (Char) -> Char end, String).

str_to_bstr([]) -> [];
str_to_bstr(T) when is_list(T) ->
    case io_lib:printable_list(T) of
        true -> list_to_binary(T);
        false -> [str_to_bstr(X) || X <- T]
    end;
str_to_bstr(T) when is_map(T) ->
    maps:from_list([{str_to_bstr(K), str_to_bstr(V)} || {K, V} <- maps:to_list(T)]);
str_to_bstr(T) -> T.


-module(fingwb_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    fingwb_whiteboard:init([]),
    {ok, _Pid} = fingwb_sup:start_link(),
    Dispatch = cowboy_router:compile([
	    {'_', [
			{"/", cowboy_static, {priv_file, fingwb, "index.html"}},
			{"/new", fingwb_create, []},
			{"/ws/:whiteboard_id", fingwb_msg_handler, []},
			{"/:whiteboard_id", fingwb_canvas, []},
			{"/static/[...]", cowboy_static, {priv_dir, fingwb, "static"}}
		]}
	]),
	{ok, _} = cowboy:start_http(http, 25, [{ip, {127,0,0,1}}, {port, 8080}],
        [{env, [{dispatch, Dispatch}]}]).

stop(_State) ->
    ok.

Change routing for css / js files

-module(fingwb_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    fingwb_whiteboard:init([]),
    {ok, _Pid} = fingwb_sup:start_link(),
    Dispatch = cowboy_router:compile([
	    {'_', [
			{"/", cowboy_static, {priv_file, fingwb, "index.html"}},
			{"/new", fingwb_create, []},
			{"/ws/:whiteboard_id", fingwb_msg_handler, []},
			{"/:whiteboard_id", fingwb_canvas, []},
			{"/js/[...]", cowboy_static, {priv_dir, fingwb, "static/js/"}},
			{"/css/[...]", cowboy_static, {priv_dir, fingwb, "static/css/"}}
		]}
	]),
	{ok, _} = cowboy:start_http(http, 25, [{ip, {127,0,0,1}}, {port, 8080}],
        [{env, [{dispatch, Dispatch}]}]).

stop(_State) ->
    ok.


-module(oauth1_resource).

-export_type(
    [ t/0
    , realm/0
    , uri/0
    ]).

-export(
    [ cons/2
    , get_realm/1
    , get_uri/1
    ]).

-type realm() ::
    binary().

-type uri() ::
    oauth1_uri:t().

-record(t,
    { realm :: realm()
    , uri   :: uri()
    }).

-opaque t() ::
    #t{}.

-spec cons(realm(), uri()) ->
    t().
cons(Realm, URI) ->
    #t
    { realm = Realm
    , uri   = URI
    }.

-spec get_realm(t()) ->
    realm().
get_realm(#t{realm=Realm}) ->
    Realm.

-spec get_uri(t()) ->
    uri().
get_uri(#t{uri=URI}) ->
    URI.

Add serialization API to resource abstraction.

-module(oauth1_resource).

-export_type(
    [ t/0
    , realm/0
    , uri/0
    ]).

-export(
    % Construct
    [ cons/2

    % Access
    , get_realm/1
    , get_uri/1

    % Serialize (for internal storage purposes only!)
    , to_props/1
    , of_props/1
    ]).

-type realm() ::
    binary().

-type uri() ::
    oauth1_uri:t().

-record(t,
    { realm :: realm()
    , uri   :: uri()
    }).

-opaque t() ::
    #t{}.

-define(SERIALIZATION_KEY_REALM, <<"realm">>).
-define(SERIALIZATION_KEY_URI  , <<"uri">>).

-spec cons(realm(), uri()) ->
    t().
cons(Realm, URI) ->
    #t
    { realm = Realm
    , uri   = URI
    }.

-spec get_realm(t()) ->
    realm().
get_realm(#t{realm=Realm}) ->
    Realm.

-spec get_uri(t()) ->
    uri().
get_uri(#t{uri=URI}) ->
    URI.

-spec to_props(t()) ->
    [{binary(), binary()}].
to_props(#t{realm = <<Realm/binary>>, uri=URI}) ->
    [ {?SERIALIZATION_KEY_REALM , Realm}
    , {?SERIALIZATION_KEY_URI   , oauth1_uri:to_bin(URI)}
    ].

-spec of_props([{binary(), binary()}]) ->
    t().
of_props(Props1) ->
    KeyRealm = ?SERIALIZATION_KEY_REALM,
    KeyURI   = ?SERIALIZATION_KEY_URI,
    {value, {KeyRealm, Realm },  Props2} = lists:keytake(KeyRealm, 1, Props1),
    {value, {KeyURI  , URIBin}, _Props3} = lists:keytake(KeyURI  , 1, Props2),
    {ok, URI} = oauth1_uri:of_bin(URIBin),
    #t
    { realm = Realm
    , uri   = URI
    }.


%%%-------------------------------------------------------------------
%%% File : similar_process.erl
%%% Author : Nicolas Dufour <nrdufour@gmail.com>
%%% Created : 2009/07/29
%%% Description :
%%%	Utility functions related to the simulation engine.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------

-module(similar_utils).

-export([trace_on/1, trace_off/1, kill_current/1, reset/1]).

-include("similar_data.hrl").

trace_on(State) ->
	State#sm_data{trace = true}.

trace_off(State) ->
	State#sm_data{trace = false}.

kill_current(State) ->
	State.

reset(State) ->
	lists:foreach(fun similar_process:kill_sim_proc/1, State#sm_data.processes),
	lists:foreach(fun utils:kill_erlang_process/1, State#sm_data.resources),
	State#sm_data{events = [], resources = [], processes = [], actives = []}.

%% END

Reset has to empty the event list.

%%%-------------------------------------------------------------------
%%% File : similar_process.erl
%%% Author : Nicolas Dufour <nrdufour@gmail.com>
%%% Created : 2009/07/29
%%% Description :
%%%	Utility functions related to the simulation engine.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------

-module(similar_utils).

-export([trace_on/1, trace_off/1, kill_current/1, reset/1]).

-include("similar_data.hrl").

trace_on(State) ->
	State#sm_data{trace = true}.

trace_off(State) ->
	State#sm_data{trace = false}.

kill_current(State) ->
	State.

reset(State) ->
	lists:foreach(fun similar_process:kill_sim_proc/1, State#sm_data.processes),
	lists:foreach(fun utils:kill_erlang_process/1, State#sm_data.resources),
	State#sm_data{events = events:create_event_store(), resources = [], processes = [], actives = []}.

%% END


%% @doc Top-level module doc.
%% @end
-module(edoc_example).
-export([f/0]).

-include_lib("docsh/include/pt_docsh.hrl").

-type r() :: ok.

%% @doc Doc for f/0.
%% @end
-spec f() -> r().
f() ->
    ok.

Add example of a parameterized type

%% @doc Top-level module doc.
%% @end
-module(edoc_example).
-export([f/0]).

-include_lib("docsh/include/pt_docsh.hrl").

-type l(A) :: list(A).
-type l() :: list().

-type r() :: ok.

%% @doc Doc for f/0.
%% @end
-spec f() -> r().
f() ->
    ok.


-record(block, {
        name,
        child,
        next=nil}).

-record(set, {
        key,
        value,
        next=nil}).

-record(get, {
        address}).

-record(cons, {
        head,
        tail=nil}).

Create a State record for the new interpreter

-record(block, {
        name,
        child,
        next=nil}).

-record(set, {
        key,
        value,
        next=nil}).

-record(get, {
        address}).

-record(cons, {
        head,
        tail=nil}).

-record(interp, {
        node,
        scope=''}).


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2010. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(eunit_SUITE).

-export([all/1,eunit_test/1]).

-include("test_server.hrl").

all(suite) ->
    [eunit_test].

eunit_test(Config) when is_list(Config) ->
    ok = file:set_cwd(code:lib_dir(eunit)),
    ok = eunit:test(eunit).

Update eunit tests to conform with common_test standard

%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2010. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(eunit_SUITE).

-export([all/0,groups/0,init_per_group/2,end_per_group/2,eunit_test/1]).

-include_lib("common_test/include/ct.hrl").

all() ->
[eunit_test].

groups() ->
    [].

init_per_group(_GroupName, Config) ->
	Config.

end_per_group(_GroupName, Config) ->
	Config.

eunit_test(Config) when is_list(Config) ->
    ok = file:set_cwd(code:lib_dir(eunit)),
    ok = eunit:test(eunit).


-module(saturn_leaf).
-include("saturn_leaf.hrl").
-include_lib("riak_core/include/riak_core_vnode.hrl").

-export([
         ping/0,
         update/3,
         read/1
        ]).

%% Public API

%% @doc Pings a random vnode to make sure communication is functional
ping() ->
    DocIdx = riak_core_util:chash_key({<<"ping">>, term_to_binary(now())}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    riak_core_vnode_master:sync_spawn_command(IndexNode, ping, ?PROXY_MASTER).

update(Key, Value, Clock) ->
    DocIdx = riak_core_util:chash_key({?BUCKET, Key}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    saturn_proxy_vnode:update(IndexNode, Key, Value, Clock).

read(Key) ->
    DocIdx = riak_core_util:chash_key({?BUCKET, Key}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    saturn_proxy_vnode:read(IndexNode, Key).

Add Clock to read for remote reads

-module(saturn_leaf).
-include("saturn_leaf.hrl").
-include_lib("riak_core/include/riak_core_vnode.hrl").

-export([
         ping/0,
         update/3,
         read/2
        ]).

%% Public API

%% @doc Pings a random vnode to make sure communication is functional
ping() ->
    DocIdx = riak_core_util:chash_key({<<"ping">>, term_to_binary(now())}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    riak_core_vnode_master:sync_spawn_command(IndexNode, ping, ?PROXY_MASTER).

update(Key, Value, Clock) ->
    DocIdx = riak_core_util:chash_key({?BUCKET, Key}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    saturn_proxy_vnode:update(IndexNode, Key, Value, Clock).

read(Key, Clock) ->
    DocIdx = riak_core_util:chash_key({?BUCKET, Key}),
    PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, ?PROXY_SERVICE),
    [{IndexNode, _Type}] = PrefList,
    saturn_proxy_vnode:read(IndexNode, Key, Clock).


-module(basic_SUITE).

-compile(export_all).

init_per_suite(Config) ->
    Config.

end_per_suite(_Config) ->
    ok.

init_per_testcase(_Tc, Config) ->
    Config.

end_per_testcase(_Tc, _Config) ->
    ok.

all() ->
    [basic].

basic(_Config) ->
    Ctx = llevm:'LLVMGetGlobalContext'(),
    ModRef = llevm:'LLVMModuleCreateWithName'("test"),
    FunTypeRef = llevm:'LLVMFunctionType'(llevm:'LLVMDoubleType'(),
				       {llevm:'LLVMDoubleType'(),
				        llevm:'LLVMDoubleType'()}, 2, false),
    FunRef = llevm:'LLVMAddFunction'(ModRef, "foo", FunTypeRef),
    llevm:'LLVMDumpModule'(ModRef),
    BuildRef = llevm:'LLVMCreateBuilderInContext'(Ctx),
    _BB = llevm:'LLVMAppendBasicBlockInContext'(Ctx,FunRef,"entry"),
    Value = llevm:'LLVMConstReal'(llevm:'LLVMDoubleType'(),
				  1.2),
    llevm:'LLVMBuildRet'(BuildRef, Value),

    llevm:'LLVMDumpModule'(ModRef).

Extend basic tests to create a small function

-module(basic_SUITE).

-compile(export_all).

init_per_suite(Config) ->
    Config.

end_per_suite(_Config) ->
    ok.

init_per_testcase(_Tc, Config) ->
    Config.

end_per_testcase(_Tc, _Config) ->
    ok.

all() ->
    [basic].

basic(_Config) ->
    Ctx = llevm:'LLVMGetGlobalContext'(),
    ModRef = llevm:'LLVMModuleCreateWithName'("test"),
    FunTypeRef = llevm:'LLVMFunctionType'(llevm:'LLVMDoubleType'(),
					  {llevm:'LLVMDoubleType'(),
					   llevm:'LLVMDoubleType'() }, 2, false),
    FunRef = llevm:'LLVMAddFunction'(ModRef, "foo", FunTypeRef),
    llevm:'LLVMDumpModule'(ModRef),
    BuildRef = llevm:'LLVMCreateBuilderInContext'(Ctx),
    BB = llevm:'LLVMAppendBasicBlock'(FunRef,"entry"),
    llevm:'LLVMPositionBuilderAtEnd'(BuildRef, BB),
    Value10 = llevm:'LLVMConstReal'(llevm:'LLVMDoubleType'(),
				    1.0),
    ValueArg1 = llevm:'LLVMGetParam'(FunRef, 0),
    ValueArg2 = llevm:'LLVMGetParam'(FunRef, 1),

    ValueAdd = llevm:'LLVMBuildFAdd'(BuildRef, Value10, ValueArg1, "addtmp"),
    ValueMul = llevm:'LLVMBuildFMul'(BuildRef, ValueAdd, ValueArg2, "multmp"),
    llevm:'LLVMBuildRet'(BuildRef, ValueMul),

    llevm:'LLVMDumpModule'(ModRef).


-module(dlq_test).
-include_lib("eunit/include/eunit.hrl").

% Should create an empty DLQ
initDLQ_test() -> {[], 3, "Test"} = dlq:initDLQ(3, "Test").

Add delete dlq function which does not make sense yet

-module(dlq_test).
-include_lib("eunit/include/eunit.hrl").

% Should create an empty DLQ
initDLQ_test() -> {[], 3, "Test"} = dlq:initDLQ(3, "Test").

% Should create an empty DLQ
delDLQ_empty_dlq_test() -> ok = dlq:delDLQ(dlq:initDLQ(3, "Test")).


-record(context, {auth_bypass :: boolean(),
                  bucket :: binary(),
                  owner_id :: all | string()}).

-record(moss_user_v1, {
          name :: string(),
          display_name :: string(),
          email :: string(),
          key_id :: string(),
          key_secret :: string(),
          canonical_id :: string()}).
-type moss_user() :: #moss_user_v1{}.

-define(USER_BUCKET, <<"moss.users">>).
-define(BUCKETS_BUCKET, <<"moss.buckets">>).
-define(FREE_BUCKET_MARKER, <<"0">>).
-define(MOSS_USER, #moss_user_v1).

Add bucket field back to user record.

-record(context, {auth_bypass :: boolean(),
                  bucket :: binary(),
                  owner_id :: all | string()}).

-record(moss_user_v1, {
          name :: string(),
          display_name :: string(),
          email :: string(),
          key_id :: string(),
          key_secret :: string(),
          canonical_id :: string(),
          buckets=[] :: [term()]}).
-type moss_user() :: #moss_user_v1{}.

-define(USER_BUCKET, <<"moss.users">>).
-define(BUCKETS_BUCKET, <<"moss.buckets">>).
-define(FREE_BUCKET_MARKER, <<"0">>).
-define(MOSS_USER, #moss_user_v1).


-module(oauth1_client).

-export(
    [ ready/2
    ]).

-spec ready(TempToken :: oauth1_credentials:id(tmp), Verifier :: binary()) ->
    hope_result:t(ok, oauth1_storage:error()).
ready(_TempToken, _Verifier) ->
%   {ok, ConsumerKey} = application:get_env(oauth1, client_consumer_key),
%   SignatureMethod = 'HMAC_SHA1',
%   SignatureConsArgs = #oauth1_signature_cons
%       {
%       },
%   Signature = oauth1_signature:cons(SignatureConsArgs),
%   ServerTokenArgs = #oauth1_server_token
%       { consumer_key     = ConsumerKey
%       , token            = TempToken
%       , signature_method = SignatureMethod
%       , timestamp        = oauth1_timestamp:get()
%       , nonce            = oauth1_nonce:generate()
%       , verifier         = Verifier
%       , signature        = Signature
%       },
%   % This should probably just construct and return a URI.
%   oauth1_server:token(ServerTokenArgs)
    error(not_implemented).

Use oauth1_verifier:t() instead of binary()

-module(oauth1_client).

-export(
    [ ready/2
    ]).

-spec ready(TempToken :: oauth1_credentials:id(tmp), oauth1_verifier:t()) ->
    hope_result:t(ok, oauth1_storage:error()).
ready(_TempToken, _Verifier) ->
%   {ok, ConsumerKey} = application:get_env(oauth1, client_consumer_key),
%   SignatureMethod = 'HMAC_SHA1',
%   SignatureConsArgs = #oauth1_signature_cons
%       {
%       },
%   Signature = oauth1_signature:cons(SignatureConsArgs),
%   ServerTokenArgs = #oauth1_server_token
%       { consumer_key     = ConsumerKey
%       , token            = TempToken
%       , signature_method = SignatureMethod
%       , timestamp        = oauth1_timestamp:get()
%       , nonce            = oauth1_nonce:generate()
%       , verifier         = Verifier
%       , signature        = Signature
%       },
%   % This should probably just construct and return a URI.
%   oauth1_server:token(ServerTokenArgs)
    error(not_implemented).


%
% reia_ivars: Transform Reia instance variables into dict representation
% Copyright (C)2008 Tony Arcieri
%
% Redistribution is permitted under the MIT license.  See LICENSE for details.
%

-module(reia_ivars).
-export([ast/1, ast/2, transform/2]).

%-define(msg(Str, Xs), io:format(Str, Xs)).
-define(msg(Str, Xs), ok).

ast(Ast) ->
  ast(Ast, []).

ast(Ast, Variables) ->
  Dict = dict:from_list([{Variable, 0} || Variable <- Variables]),
  ?msg("Input: ~p~n", [Ast]),
  {ok, _, Ast2} = reia_visitor:transform(Ast, {normal, Dict}, fun transform/2),
  ?msg("Output: ~p~n", [Ast2]),
  Ast2.

% Walk unrecognized nodes without transforming them
transform(State, Node) ->
  {walk, State, Node}.

Add errors for incorrect ivar usage

%
% reia_ivars: Transform Reia instance variables into dict representation
% Copyright (C)2008 Tony Arcieri
%
% Redistribution is permitted under the MIT license.  See LICENSE for details.
%

-module(reia_ivars).
-export([ast/1, ast/2, transform/2]).

%-define(msg(Str, Xs), io:format(Str, Xs)).
-define(msg(Str, Xs), ok).

ast(Ast) ->
  ast(Ast, []).

ast(Ast, Variables) ->
  Dict = dict:from_list([{Variable, 0} || Variable <- Variables]),
  ?msg("Input: ~p~n", [Ast]),
  {ok, _, Ast2} = reia_visitor:transform(Ast, {toplevel, Dict}, fun transform/2),
  ?msg("Output: ~p~n", [Ast2]),
  Ast2.

transform(_State, {ivar, Line, _Name}) ->
  throw({error, {Line, "instance variables may only be used inside methods"}});

% Walk unrecognized nodes without transforming them
transform(State, Node) ->
  {walk, State, Node}.


-type ensemble_id() :: term().
-type peer_id() :: {term(), node()}.
-type leader_id() :: undefined | peer_id().
-type fixme() :: any().
-type views() :: [[peer_id()]].
-type peer_change() :: term(). %% FIXME
-type change_error() :: already_member | not_member.
-type std_reply() :: timeout | failed | unavailable | nack | {ok, term()}.
-type maybe_pid() :: pid() | undefined.
-type peer_pids() :: [{peer_id(), maybe_pid()}].
-type peer_reply() :: {peer_id(), term()}.
-type epoch() :: integer().
-type seq() :: integer().
-type vsn() :: {epoch(), seq()}.
-type orddict(Key,Val) :: [{Key, Val}].
-type ordsets(Val) :: [Val].

-record(ensemble_info, {vsn,
                        mod     = riak_ensemble_basic_backend :: module(),
                        args    = []                          :: [any()],
                        leader                                :: leader_id(),
                        views                                 :: [[peer_id()]],
                        seq                                   :: {integer(), integer()}
                       }).
-type ensemble_info() :: #ensemble_info{}.

%% -type ensemble_info() :: {leader_id(), [peer_id()], {integer(), integer()}, module(), [any()]}.

-define(ENSEMBLE_TICK, 200).

Add type specification for ensemble_info.vsn

-type ensemble_id() :: term().
-type peer_id() :: {term(), node()}.
-type leader_id() :: undefined | peer_id().
-type fixme() :: any().
-type views() :: [[peer_id()]].
-type peer_change() :: term(). %% FIXME
-type change_error() :: already_member | not_member.
-type std_reply() :: timeout | failed | unavailable | nack | {ok, term()}.
-type maybe_pid() :: pid() | undefined.
-type peer_pids() :: [{peer_id(), maybe_pid()}].
-type peer_reply() :: {peer_id(), term()}.
-type epoch() :: integer().
-type seq() :: integer().
-type vsn() :: {epoch(), seq()}.
-type orddict(Key,Val) :: [{Key, Val}].
-type ordsets(Val) :: [Val].

-record(ensemble_info, {vsn                                   :: vsn(),
                        mod     = riak_ensemble_basic_backend :: module(),
                        args    = []                          :: [any()],
                        leader                                :: leader_id(),
                        views                                 :: [[peer_id()]],
                        seq                                   :: {integer(), integer()}
                       }).
-type ensemble_info() :: #ensemble_info{}.

%% -type ensemble_info() :: {leader_id(), [peer_id()], {integer(), integer()}, module(), [any()]}.

-define(ENSEMBLE_TICK, 200).


-module(oauth1_storage).

-export_type(
    [ error/0
    ]).

-export(
    [ put/3
    , get/2
    ]).

-type error() ::
      not_found
    | io_error
    .

-callback put(binary(), binary(), binary()) ->
    hope_result:t(ok, error()).

-callback get(binary(), binary()) ->
    hope_result:t(binary(), error()).

-spec put(binary(), binary(), binary()) ->
    hope_result:t(ok, error()).
put(Bucket, Key, Value) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key, Value).

-spec get(binary(), binary()) ->
    hope_result:t(binary(), error()).
get(Bucket, Key) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key).

-spec lookup_storage_module() ->
    atom().
lookup_storage_module() ->
    {ok, StorageModule} = application:get_env(oauth1, storage_module),
    StorageModule.

Define a more useful IO error type.

-module(oauth1_storage).

-export_type(
    [ error/0
    ]).

-export(
    [ put/3
    , get/2
    ]).

-type error() ::
      not_found
    | {io_error, any()}
    .

-callback put(binary(), binary(), binary()) ->
    hope_result:t(ok, error()).

-callback get(binary(), binary()) ->
    hope_result:t(binary(), error()).

-spec put(binary(), binary(), binary()) ->
    hope_result:t(ok, error()).
put(Bucket, Key, Value) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key, Value).

-spec get(binary(), binary()) ->
    hope_result:t(binary(), error()).
get(Bucket, Key) ->
    StorageModule = lookup_storage_module(),
    StorageModule:put(Bucket, Key).

-spec lookup_storage_module() ->
    atom().
lookup_storage_module() ->
    {ok, StorageModule} = application:get_env(oauth1, storage_module),
    StorageModule.


%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc Nitrogen element: {{description}}
%%% @end
-module({{app_name}}_{{name}}_element).
-author('{{author_name}} <{{author_email}}>').

-include_lib("nitrogen_core/include/wf.hrl").
-export(reflect/0, render_element/1).

%% TODO: Make sure to add record definition to your app's header file.

%%%.
%%%'   NITROGEN CALLBACKS

%% @hidden
reflect() -> record_info(fields, {{app_name}}_{{name}}_element).

%% @hidden
render_element(Record) ->
  wf_tags:emit_tag('div', "", [{class, [{{name}}]}]).

%%%.
%%%'   PRIVATE FUNCTIONS

%% TODO: Add private functions for element module here.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:

Fix syntax error in Nitrogen element template

%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc Nitrogen element: {{description}}
%%% @end
-module({{app_name}}_{{name}}_element).
-author('{{author_name}} <{{author_email}}>').

-include_lib("nitrogen_core/include/wf.hrl").
-export([reflect/0, render_element/1]).

%% TODO: Make sure to add record definition to your app's header file.

%%%.
%%%'   NITROGEN CALLBACKS

%% @hidden
reflect() -> record_info(fields, {{app_name}}_{{name}}_element).

%% @hidden
render_element(Record) ->
  wf_tags:emit_tag('div', "", [{class, [{{name}}]}]).

%%%.
%%%'   PRIVATE FUNCTIONS

%% TODO: Add private functions for element module here.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:


-module(rabbit_auth_backend_kerberos).

-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(rabbit_auth_backend).

-export([description/0, check_user_login/2, check_vhost_access/2, check_resource_access/3]).

description() ->
  [{name, <<"Kerberos">>},
    {description, <<"Kerberos authentication">>}].

check_user_login(Username, AuthProps) ->
  {'ok', Username}.

check_vhost_access(#user{username = Username}, VHost) ->
  true.

check_resource_access(#user{username = Username},
  #resource{virtual_host = VHost, kind = Type, name = Name},
  Permission) ->
  true.

Use the correct user structure.

-module(rabbit_auth_backend_kerberos).

-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(rabbit_auth_backend).

-export([description/0, check_user_login/2, check_vhost_access/2, check_resource_access/3]).

description() ->
  [{name, <<"Kerberos">>},
    {description, <<"Kerberos authentication">>}].

check_user_login(Username, AuthProps) ->
  {ok, #user{username     = Username,
      tags         = none,
      auth_backend = ?MODULE,
      impl         = none}}.

check_vhost_access(#user{username = Username}, VHost) ->
  true.

check_resource_access(#user{username = Username},
  #resource{virtual_host = VHost, kind = Type, name = Name},
  Permission) ->
  true.


-module(erldocs).
-export([main/1]).

%% @doc Called automatically by escript
-spec main(list()) -> ok.
main([]) ->
    Conf = [{apps, ["."]}, {dest, "doc/erldocs"}],
    run(Conf);

main([Dest]) ->
    Conf = [{apps, ["."]}, {dest, Dest}],
    run(Conf);

main(Args) ->
    main(Args, []).

main([Dest], Apps) ->
    Conf = [{apps, Apps}, {dest, Dest}],
    run(Conf);

main([App|Rest], Apps) ->
    main(Rest, [App|Apps]).

run(Conf) ->
    try erldocs_core:dispatch(Conf)
    catch Type:Error ->
            log("Error running script:~n~p~n~p~n",
                [erlang:get_stacktrace(), {Type, Error}])
    end.

-spec log(string(), [_]) -> ok.
log(Str, Args) ->
    io:format(Str, Args).

Fix escript when used with no arguments

-module(erldocs).
-export([main/1]).

%% @doc Called automatically by escript
-spec main(list()) -> ok.
main([]) ->
    {ok, CWD} = file:get_cwd(),
    Conf = [{apps, [CWD]}, {dest, "doc/erldocs"}],
    run(Conf);

main([Dest]) ->
    Conf = [{apps, ["."]}, {dest, Dest}],
    run(Conf);

main(Args) ->
    main(Args, []).

main([Dest], Apps) ->
    Conf = [{apps, Apps}, {dest, Dest}],
    run(Conf);

main([App|Rest], Apps) ->
    main(Rest, [App|Apps]).

run(Conf) ->
    try erldocs_core:dispatch(Conf)
    catch Type:Error ->
            log("Error running script:~n~p~n~p~n",
                [erlang:get_stacktrace(), {Type, Error}])
    end.

-spec log(string(), [_]) -> ok.
log(Str, Args) ->
    io:format(Str, Args).


-module(erldocs).
-export([main/1]).

%% @doc Called automatically by escript
-spec main(list()) -> ok.
main(Args) ->
    parse(Args, []).

parse([], []) ->
    Dest = filename:absname("docs/erldocs"),
    parse([Dest], []);

parse([Dest], []) ->
    Apps = [cwd()],
    parse([Dest], Apps);

parse([Dest], Apps) ->
    Conf = [{apps, Apps}, {dest, filename:absname(Dest)}],
    run(Conf);

parse([App|Rest], Apps) ->
    parse(Rest, [filename:absname(App)|Apps]).

run(Conf) ->
    try erldocs_core:dispatch(Conf)
    catch Type:Error ->
            log("Error running script:~n~p~n~p~n",
                [erlang:get_stacktrace(), {Type, Error}])
    end.

-spec log(string(), [_]) -> ok.
log(Str, Args) ->
    io:format(Str, Args).

cwd() ->
    element(2, file:get_cwd()).

Make command parsing slightly less dumb

-module(erldocs).
-export([main/1]).

-record(conf, {dirs = [], destination = cwd() ++ "/docs/erldocs"}).

%% @doc Called automatically by escript
-spec main(list()) -> ok.
main(Args) ->
    parse(Args, #conf{}).

parse([], #conf{destination = Destination} = Conf) ->
    Dirs = case Conf#conf.dirs of
      [] -> [cwd()];
      Else -> Else
    end,
    run([{apps, Dirs}, {dest, filename:absname(Destination)}]);

parse(["-o", Dest | Rest], Conf) ->
    parse(Rest, Conf#conf{destination=Dest});

parse([Dir | Rest], #conf{dirs = Dirs} = Conf) ->
    parse(Rest, Conf#conf{dirs = [Dir | Dirs]}).

run(Conf) ->
    try erldocs_core:dispatch(Conf)
    catch Type:Error ->
            log("Error running script:~n~p~n~p~n",
                [erlang:get_stacktrace(), {Type, Error}])
    end.

-spec log(string(), [_]) -> ok.
log(Str, Args) ->
    io:format(Str, Args).

cwd() ->
    element(2, file:get_cwd()).


-module(mzb_string).

-export([
    format/2,
    char_substitute/3,
    str_to_bstr/1
]).

-spec format(Format :: string(), Args :: [term()]) -> FlatString :: string().
format(Format, Args) ->
    lists:flatten(io_lib:format(Format, Args)).

-spec char_substitute(string(), char(), char()) -> string().
char_substitute(String, OldChar, NewChar) ->
    lists:map(fun(Char) when Char =:= OldChar -> NewChar;
        (Char) -> Char end, String).

str_to_bstr(T) when is_list(T) ->
    case io_lib:printable_list(T) of
        true -> list_to_binary(T);
        false -> [str_to_bstr(X) || X <- T]
    end;
str_to_bstr(T) when is_map(T) ->
    maps:from_list([{str_to_bstr(K), str_to_bstr(V)} || {K, V} <- maps:to_list(T)]);
str_to_bstr(T) -> T.

Add empty array condition to str_to_bstr

-module(mzb_string).

-export([
    format/2,
    char_substitute/3,
    str_to_bstr/1
]).

-spec format(Format :: string(), Args :: [term()]) -> FlatString :: string().
format(Format, Args) ->
    lists:flatten(io_lib:format(Format, Args)).

-spec char_substitute(string(), char(), char()) -> string().
char_substitute(String, OldChar, NewChar) ->
    lists:map(fun(Char) when Char =:= OldChar -> NewChar;
        (Char) -> Char end, String).

str_to_bstr([]) -> [];
str_to_bstr(T) when is_list(T) ->
    case io_lib:printable_list(T) of
        true -> list_to_binary(T);
        false -> [str_to_bstr(X) || X <- T]
    end;
str_to_bstr(T) when is_map(T) ->
    maps:from_list([{str_to_bstr(K), str_to_bstr(V)} || {K, V} <- maps:to_list(T)]);
str_to_bstr(T) -> T.


%%==============================================================================
%% @author Gavin M. Roy <gavinr@aweber.com>
%% @copyright 2015 AWeber Communications
%% @end
%%==============================================================================

-record(config, {key, os, default, type}).

-define(CONFIG_MAP,
        [{config, backend,              "AUTOCLUSTER_TYPE",      consul,      atom},
         {config, longname,             "RABBITMQ_LONGNAME",     false,       atom},
         {config, cluster_name,         "CLUSTER_NAME",          undefined,   string},
         {config, consul_acl,           "CONSUL_ACL",            undefined,   string},
         {config, consul_scheme,        "CONSUL_SCHEME",         "http",      string},
         {config, consul_host,          "CONSUL_HOST",           "localhost", string},
         {config, consul_port,          "CONSUL_PORT",           8500,        integer},
         {config, consul_service,       "CONSUL_SERVICE",        "rabbitmq",  string},
         {config, consul_service_port,  "CONSUL_SERVICE_PORT",   5672,        integer},
         {config, consul_service_prefix,"CONSUL_SERVICE_PREFIX", undefined,   string},
         {config, consul_service_ttl,   "CONSUL_SERVICE_TTL",    30,          integer}]).

-define(CONSUL_CHECK_NOTES, list_to_atom("RabbitMQ Auto-Cluster Plugin TTL Check")).

Update the default values for cluster and acl

%%==============================================================================
%% @author Gavin M. Roy <gavinr@aweber.com>
%% @copyright 2015 AWeber Communications
%% @end
%%==============================================================================

-record(config, {key, os, default, type}).

-define(CONFIG_MAP,
        [{config, backend,              "AUTOCLUSTER_TYPE",      consul,      atom},
         {config, longname,             "RABBITMQ_LONGNAME",     false,       atom},
         {config, cluster_name,         "CLUSTER_NAME",          "undefined", string},
         {config, consul_acl,           "CONSUL_ACL",            "undefined", string},
         {config, consul_scheme,        "CONSUL_SCHEME",         "http",      string},
         {config, consul_host,          "CONSUL_HOST",           "localhost", string},
         {config, consul_port,          "CONSUL_PORT",           8500,        integer},
         {config, consul_service,       "CONSUL_SERVICE",        "rabbitmq",  string},
         {config, consul_service_port,  "CONSUL_SERVICE_PORT",   5672,        integer},
         {config, consul_service_prefix,"CONSUL_SERVICE_PREFIX", undefined,   string},
         {config, consul_service_ttl,   "CONSUL_SERVICE_TTL",    30,          integer}]).

-define(CONSUL_CHECK_NOTES, list_to_atom("RabbitMQ Auto-Cluster Plugin TTL Check")).


-module(a_long).
-compile([export_all]).
-include("a_include.hrl").

http_show(Response, Content)->
        Response:write_chunk(io_lib:format("~s~n", [lists:flatten(Content, "")])).

pull(Req)->
        Response = Req:ok({"text/plain", chunked}),
        message(Response),
        ok.

message(Response)->
        http_show(Response, ["k"]),
        receive
                cancel->
                        void;
                _ ->
                        good
        after 5000->
                      http_show(Response, ["55555"])
        end,
        message(Response).

Add keepalive output to json string

-module(a_long).
-compile([export_all]).
-include("a_include.hrl").

http_show(Response, Content)->
        Response:write_chunk(io_lib:format("~s~n", [lists:flatten(Content, "")])).

pull(Req)->
        Response = Req:ok({"text/plain", chunked}),
        message(Response),
        ok.

message(Response)->
        http_show(Response, mochijson2:encode([{<<"type">>, <<"keepalive">>}])),
        receive
                cancel->
                        void;
                _ ->
                        good
        after 5000->
                      message(Response)
        end.


%% @author Marc Worrell <marc@worrell.nl>
%% @copyright 2012 Marc Worrell
%% @doc Check if the questions end with a question type that is a submit button.

%% Copyright 2012 Marc Worrell
%%
%% 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.

-module(filter_survey_is_submit).

-export([
    survey_is_submit/2
]).

-include("zotonic_notifications.hrl").

survey_is_submit(Qs, Context) ->
	find_first_question(lists:reverse(Qs), Context).

find_first_question([], _Context) ->
	true;
find_first_question([Q|Qs], Context) ->
	case z_notifier:first(#survey_is_submit{block=Q}, Context) of
		undefined -> find_first_question(Qs, Context);
		true -> true;
		false -> false
	end.

Fix edge case where 'continue' button was not shown for empty pages.

%% @author Marc Worrell <marc@worrell.nl>
%% @copyright 2012 Marc Worrell
%% @doc Check if the questions end with a question type that is a submit button.

%% Copyright 2012 Marc Worrell
%%
%% 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.

-module(filter_survey_is_submit).

-export([
    survey_is_submit/2
]).

-include("zotonic_notifications.hrl").

survey_is_submit(Qs, Context) ->
	find_first_question(lists:reverse(Qs), Context).

find_first_question([], _Context) ->
	false;
find_first_question([Q|Qs], Context) ->
	case z_notifier:first(#survey_is_submit{block=Q}, Context) of
		undefined -> find_first_question(Qs, Context);
		true -> true;
		false -> false
	end.


%% @doc A basic SPARQL client.
-module(sparql_client).

-export([
    describe/2,
    query/2
]).

-include_lib("zotonic.hrl").

describe(Endpoint, <<"https://", _/binary>> = Uri) ->
    describe(Endpoint, <<"<", Uri/binary, ">">>);
describe(Endpoint, <<"http://", _/binary>> = Uri) ->
    describe(Endpoint, <<"<", Uri/binary, ">">>);
describe(Endpoint, Clause) ->
    query(Endpoint, z_convert:to_binary(z_url:url_encode(<<"DESCRIBE ", Clause/binary>>))).

query(Endpoint, Query) ->
    Qs = z_convert:to_binary(z_url:url_encode(Query)),
    Url = <<Endpoint/binary, "?query=", Qs/binary>>,
    case ginger_http_client:get(Url, headers()) of
        undefined ->
            undefined;
        Map ->
            decode(Map)
    end.

decode(Data) ->
    ginger_json_ld:deserialize(Data).

headers() ->
    [
        {"Accept", "application/ld+json"}
    ].

Add plain JSON support to SPARQL client

%% @doc A basic SPARQL client.
-module(sparql_client).

-export([
    describe/2,
    query/2,
    query/3
]).

-include_lib("zotonic.hrl").

describe(Endpoint, <<"https://", _/binary>> = Uri) ->
    describe(Endpoint, <<"<", Uri/binary, ">">>);
describe(Endpoint, <<"http://", _/binary>> = Uri) ->
    describe(Endpoint, <<"<", Uri/binary, ">">>);
describe(Endpoint, Clause) ->
    query(Endpoint, (<<"DESCRIBE ", Clause/binary>>)).

query(Endpoint, Query) ->
    query(Endpoint, Query, headers()).

-spec query(binary(), binary(), map()) -> list().
query(Endpoint, Query, Headers) ->
    Qs = z_convert:to_binary(z_url:url_encode(Query)),
    Url = <<Endpoint/binary, "?query=", Qs/binary>>,
    case ginger_http_client:get(Url, Headers) of
        undefined ->
            undefined;
        Map ->
            decode(Map)
    end.

decode(#{<<"@graph">> := _} = Data) ->
    ginger_json_ld:deserialize(Data);
decode(Data) ->
    Data.

headers() ->
    #{<<"Accept">> => <<"application/ld+json">>}.


% BKK secure cipher module %

% Usage, from erl:
%% c(bkk_crypt).
%% bkk_crypt:encrypt("Haxxor protec, but he also attac").
-module(bkk_crypt).
-export([encrypt/1]).

encrypt(Message) ->
    Message.

Add Erlang tests (EUNIT), improve comments and usage

%%% BKK secure cipher module %

%% Usage, from erl...
%%
%% - compile:
%%
%%     > c(bkk_crypt).
%%
%% - run:
%%
%%     > bkk_crypt:encrypt("Haxxor protec, but he also attac").
%%
%% - to run tests:
%%
%%     > eunit:test(bkk_crypt).
%%
-module(bkk_crypt).

%% API
-export([encrypt/1]).

%% Tests
-include_lib("eunit/include/eunit.hrl").

encrypt(Message) ->
    Message.

-ifdef(EUNIT).
encrypt_test() ->
    ?assertEqual("password", bkk_crypt:encrypt("password")),
    ?assertNotEqual("7KVcbLRkKU15XiCRlTGuj0raudw+pl+SaGVnm456LoE=", bkk_crypt:encrypt("password")).
-endif.


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_button).
-include_lib ("wf.hrl").
-compile(export_all).

reflect() -> record_info(fields, button).

render_element(Record) ->
    ID = Record#button.id,
    Anchor = Record#button.anchor,
    case Record#button.postback of
        undefined -> ignore;
        Postback -> wf:wire(Anchor, #event { type=click, validation_group=ID, postback=Postback, delegate=Record#button.delegate })
    end,

	case Record#button.click of
		undefined -> ignore;
		ClickActions -> wf:wire(Anchor, #event { type=click, actions=ClickActions })
	end,

    Value = ["  ", wf:html_encode(Record#button.text, Record#button.html_encode), "  "],
    wf_tags:emit_tag(input, [
        {id, Record#button.html_id},
        {type, button},
        {class, [button, Record#button.class]},
        {style, Record#button.style},
        {value, Value}
    ]).

Fix commas being removed from button values

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_button).
-include_lib ("wf.hrl").
-compile(export_all).

reflect() -> record_info(fields, button).

render_element(Record) ->
    ID = Record#button.id,
    Anchor = Record#button.anchor,
    case Record#button.postback of
        undefined -> ignore;
        Postback -> wf:wire(Anchor, #event { type=click, validation_group=ID, postback=Postback, delegate=Record#button.delegate })
    end,

	case Record#button.click of
		undefined -> ignore;
		ClickActions -> wf:wire(Anchor, #event { type=click, actions=ClickActions })
	end,

    Value = wf:html_encode(Record#button.text, Record#button.html_encode),
    wf_tags:emit_tag(input, [
        {id, Record#button.html_id},
        {type, button},
        {class, [button, Record#button.class]},
        {style, Record#button.style},
        {value, Value}
    ]).


-module(socket_util).

-export([
    acceptor_start/1,
    acceptor_loop/1
]).

-export([
    receiver_start/1,
    receiver_loop/1
]).

-include("socket_rec.hrl").

acceptor_start(Socket) when is_port(Socket) ->
    acceptor_start(#s_handler{socket = Socket, owner = self()});

acceptor_start(#s_handler{} = Handler) ->
    proc_lib:spawn_link(?MODULE, acceptor_loop, [Handler]).

acceptor_loop(#s_handler{} = Handler) ->
    case gen_tcp:accept(Handler#s_handler.socket) of
        {ok, Socket} ->
            Handler#s_handler.owner ! {acceptor, {socket, Socket}},
            acceptor_loop(Handler);

        {error, Reason} ->
            Handler#s_handler.owner ! {acceptor, {error, Reason}}
    end.

receiver_start(Socket) when is_port(Socket) ->
    receiver_start(#s_handler{socket = Socket, owner = self()});

receiver_start(#s_handler{} = Handler) ->
    proc_lib:spawn_link(?MODULE, receiver_loop, [Handler]).

receiver_loop(#s_handler{} = Handler) ->
    case gen_tcp:recv(Handler#s_handler.socket, 0) of
        {ok, Payload} ->
            Handler#s_handler.owner ! {receiver, {payload, Payload}},
            receiver_loop(Handler);

        {error, Reason} ->
            Handler#s_handler.owner ! {receiver, {error, Reason}}
    end.

Make socket utility processes tail recursive

-module(socket_util).

-export([
    acceptor_start/1,
    acceptor_loop/1
]).

-export([
    receiver_start/1,
    receiver_loop/1
]).

-include("socket_rec.hrl").

acceptor_start(Socket) when is_port(Socket) ->
    acceptor_start(#s_handler{socket = Socket, owner = self()});

acceptor_start(#s_handler{} = Handler) ->
    proc_lib:spawn_link(?MODULE, acceptor_loop, [Handler]).

acceptor_loop(#s_handler{} = Handler) ->
    case gen_tcp:accept(Handler#s_handler.socket) of
        {ok, Socket} ->
            Handler#s_handler.owner ! {acceptor, {socket, Socket}};

        {error, Reason} ->
            Handler#s_handler.owner ! {acceptor, {error, Reason}}
    end,
    acceptor_loop(Handler).

receiver_start(Socket) when is_port(Socket) ->
    receiver_start(#s_handler{socket = Socket, owner = self()});

receiver_start(#s_handler{} = Handler) ->
    proc_lib:spawn_link(?MODULE, receiver_loop, [Handler]).

receiver_loop(#s_handler{} = Handler) ->
    case gen_tcp:recv(Handler#s_handler.socket, 0) of
        {ok, Payload} ->
            Handler#s_handler.owner ! {receiver, {payload, Payload}};

        {error, Reason} ->
            Handler#s_handler.owner ! {receiver, {error, Reason}}
    end,
    receiver_loop(Handler).


%%=======================================================================
%% Rete data structures
%%=======================================================================

% An alpha node definition
-record(anode,
        {id :: integer(),
         wme_constraint :: fun( (term()) -> boolean() ),
         bnode_ids :: [integer()]}).
% A beta node definition
-record(bnode,
        {id :: integer(),
         token_constraint :: fun( (term()) -> boolean() ),
         left_key_fun :: fun( (term()) -> term() ),
         right_key_fun :: fun( (term()) -> term() ),
         pnodes=[]:: [integer()],
         bnode_ids :: [integer()] }).
% An output node definition
-record(pnode,
        {id :: integer(),
         token_format :: fun( ([ [T] ]) -> [T] ),
         bnode_ids :: [integer()]}).
% A rete spec
-record(rete,
        {anodes=[]:: [#anode{}],
         bnodes=[]:: [#bnode{}],
         pnodes=[]:: [#pnode{}]}).

Add bnodes map containing substitutions.

%%=======================================================================
%% Rete data structures
%%=======================================================================

% An alpha node definition
-record(anode,
        {id             :: integer(),
         wme_constraint :: fun( (term()) -> boolean() ),
         bnode_ids      :: [integer()]}).
% A beta node definition
-record(bnode,
        {id             :: integer(),
         token_constraint :: fun( (term()) -> boolean() ),
         left_key_fun   :: fun( (term()) -> term() ),
         right_key_fun  :: fun( (term()) -> term() ),
         pnodes=[]      :: [integer()],
         bnode_ids      :: [integer()] }).
% An output node definition
-record(pnode,
        {id             :: integer(),
         token_format   :: fun( ([ [T] ]) -> [T] ),
         bnode_ids      :: [integer()]}).
% A rete spec
-record(rete,
        {anodes=[]      :: [#anode{}],
         bnodes=[]      :: [#bnode{}],
         pnodes=[]      :: [#pnode{}],
         bnodes_map=[]  :: [#bnode{}]}).


-module(alog_examples).

-include("alog.hrl").

-export([
         run_examples/0
        ]).

run_examples() ->
    io:format("*** all priorities~n", []),
    alog_parse_trans:load_config([{{mod,[?MODULE]}, {'=<', ?debug},[alog_tty]}]),

    TestVar = test_var_value,
    ?DBG("test debug ~p", [TestVar]),
    ?INFO("test info ~p", [TestVar]),
    ?NOTICE("test notice ~p", [TestVar]),
    ?WARNING("test warning ~p", [TestVar]),
    ?ERROR("test error ~p", [TestVar]),
    ?CRITICAL("test critical ~p", [TestVar]),
    ?EMERGENCY("test emergency ~p", [TestVar]),

    io:format("*** =< errors~n", []),

    alog_parse_trans:load_config(
      [{{mod,[?MODULE]}, {'=<', ?error},[alog_tty]}]),

    ?DBG("test debug ~p", [TestVar]),
    ?INFO("test info ~p", [TestVar]),
    ?NOTICE("test notice ~p", [TestVar]),
    ?WARNING("test warning ~p", [TestVar]),
    ?ERROR("test error ~p", [TestVar]),
    ?CRITICAL("test critical ~p", [TestVar]),
    ?EMERGENCY("test emergency ~p", [TestVar]),

    ok.

Add ~n to examples log messages

-module(alog_examples).

-include("alog.hrl").

-export([
         run_examples/0
        ]).

run_examples() ->
    io:format("*** all priorities~n", []),
    alog_parse_trans:load_config([{{mod,[?MODULE]}, {'=<', ?debug},[alog_tty]}]),

    TestVar = test_var_value,
    ?DBG("test debug ~p~n", [TestVar]),
    ?INFO("test info ~p~n", [TestVar]),
    ?NOTICE("test notice ~p~n", [TestVar]),
    ?WARNING("test warning ~p~n", [TestVar]),
    ?ERROR("test error ~p~n", [TestVar]),
    ?CRITICAL("test critical ~p~n", [TestVar]),
    ?EMERGENCY("test emergency ~p~n", [TestVar]),

    io:format("*** =< errors~n", []),

    alog_parse_trans:load_config(
      [{{mod,[?MODULE]}, {'=<', ?error},[alog_tty]}]),

    ?DBG("test debug ~p~n", [TestVar]),
    ?INFO("test info ~p~n", [TestVar]),
    ?NOTICE("test notice ~p~n", [TestVar]),
    ?WARNING("test warning ~p~n", [TestVar]),
    ?ERROR("test error ~p~n", [TestVar]),
    ?CRITICAL("test critical ~p~n", [TestVar]),
    ?EMERGENCY("test emergency ~p~n", [TestVar]),

    ok.


%
% reia_classes: Convert OOP features to Reia code
% Copyright (C)2010 Tony Arcieri
%
% Redistribution is permitted under the MIT license.  See LICENSE for details.
%

-module(reia_classes).
-export([transform/2]).
-include("reia_nodes.hrl").

transform(Exprs, _Options) ->
  reia_syntax:map_subtrees(fun transform/1, Exprs).

transform(#class{} = Node) ->
  reia_syntax:map_subtrees(fun transform/1, transform_class(Node));

transform(Node) ->
  reia_syntax:map_subtrees(fun transform/1, Node).

transform_class(#class{line=Line, name=Name, methods=Funcs}) ->
  #class{line=Line, name=Name, methods=Funcs}.

Build method table for classes

%
% reia_classes: Convert OOP features to Reia code
% Copyright (C)2010 Tony Arcieri
%
% Redistribution is permitted under the MIT license.  See LICENSE for details.
%

-module(reia_classes).
-export([transform/2]).
-include("reia_nodes.hrl").

transform(Exprs, _Options) ->
  reia_syntax:map_subtrees(fun transform/1, Exprs).

transform(#class{} = Node) ->
  reia_syntax:map_subtrees(fun transform/1, transform_class(Node));

transform(Node) ->
  reia_syntax:map_subtrees(fun transform/1, Node).

transform_class(#class{line=Line, name=Name, methods=Methods}) ->
	_MethodTable = build_method_table(Methods),
  #class{line=Line, name=Name, methods=Methods}.

% Create a dict of methods by name
build_method_table(Methods) ->
	build_method_table(dict:new(), Methods).

build_method_table(Dict, []) ->
	Dict;
build_method_table(Dict, [Func|Rest]) ->
	Dict2 = dict:store(Func#function.name, Func, Dict),
	build_method_table(Dict2, Rest).


% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% Contributions from Torbjorn Tornkvist (tobbe@tornkvist.org)
% See MIT-LICENSE for licensing information.

-module (validator_max_length).
-include_lib ("wf.hrl").
-compile(export_all).

render_validator(TriggerPath, TargetPath, Record)  ->
    Text = wf:js_escape(Record#max_length.text),
    Length = Record#max_length.length,
    validator_custom:render_validator(TriggerPath, TargetPath, #custom { function=fun validate/2, text = Text, tag=Record }),
    wf:f("v.add(Validate.Length, { maximum: ~p, tooLongMessage: \"~s\" });", [Length, Text]).

validate(Record, Value) ->
    Record#max_length.length >= length(Value).

Fix max length validator, probably used older API

% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% Contributions from Torbjorn Tornkvist (tobbe@tornkvist.org)
% See MIT-LICENSE for licensing information.

-module (validator_max_length).
-include_lib ("wf.hrl").
-compile(export_all).

render_action(Record)  ->
    TriggerPath= Record#max_length.trigger,
    TargetPath = Record#max_length.target,
    Text = wf:js_escape(Record#max_length.text),
    Length = Record#max_length.length,
    CustomValidatorAction = #custom { trigger=TriggerPath, target=TargetPath, function=fun validate/2, text=Text, tag=Record },
    validator_custom:render_action(CustomValidatorAction),
    wf:f("v.add(Validate.Length, { maximum: ~p, tooLongMessage: \"~s\" });", [Length, Text]).

validate(Record, Value) ->
    Record#max_length.length >= length(Value).


-module(inets_simple_bridge_anchor).
-export ([do/1]).

do(Req) ->
	Bridge = simple_bridge:make(inets, Req),
	ReqPath = Bridge:path(),
	case simple_bridge_util:is_static_path(inets, ReqPath) of
		true ->
			Bridge2 = Bridge:set_response_file(ReqPath),
			Bridge2:build_response();
		false ->
			Handler = simple_bridge_util:get_env(handler),
			case simple_bridge_websocket:attempt_hijacking(Bridge, Handler) of
				{hijacked, closed} ->
					done;
				{hijacked, Bridge2} ->
					Bridge2:build_response();
				spared ->
					Handler:run(Bridge)
			end
	end.

Remove pmod syntax in inets anchor

-module(inets_simple_bridge_anchor).
-export ([do/1]).

do(Req) ->
	Bridge = simple_bridge:make(inets, Req),
	ReqPath = Bridge:path(),
	case simple_bridge_util:is_static_path(inets, ReqPath) of
		true ->
			Bridge2 = sbw:set_response_file(ReqPath, Bridge),
			sbw:build_response(Bridge2);
		false ->
			Handler = simple_bridge_util:get_env(handler),
			case simple_bridge_websocket:attempt_hijacking(Bridge, Handler) of
				{hijacked, closed} ->
					done;
				{hijacked, Bridge2} ->
					sbw:build_response(Bridge2);
				spared ->
					Handler:run(Bridge)
			end
	end.


-module(driver_tests).

-include_lib("eunit/include/eunit.hrl").

load_test_() ->
  [{setup, fun test_util:port_setup/0,
    fun test_util:port_teardown/1,
    [fun() ->
         P = test_util:get_thing(),
         ?assert(is_port(P)),
         erlang:unlink(P) end]}].

big_heap_test_() ->
    [{setup, fun() -> test_util:port_setup(64) end,
      fun test_util:port_teardown/1,
      [fun() ->
               P = test_util:get_thing(),
               ?assert(is_port(P)),
               erlang:unlink(P) end]}].

destroy_test_() ->
  [{setup, fun test_util:port_setup/0,
    fun test_util:null_teardown/1,
    [fun() ->
         P = test_util:get_thing(),
         ?assertMatch(true, js_driver:destroy(P)),
         ?assertError(badarg, js:define(P, <<"var x = 100;">>)),
         erlang:unlink(P) end]}].

spinup_test_() ->
  [fun() ->
       F = fun({ok, P}) -> js_driver:destroy(P) end,
       Ports = [js_driver:new() || X <- lists:seq(1, 16)],
       [F(P) || P <- Ports] end].

Fix warning (treated as error) about unused variable

-module(driver_tests).

-include_lib("eunit/include/eunit.hrl").

load_test_() ->
  [{setup, fun test_util:port_setup/0,
    fun test_util:port_teardown/1,
    [fun() ->
         P = test_util:get_thing(),
         ?assert(is_port(P)),
         erlang:unlink(P) end]}].

big_heap_test_() ->
    [{setup, fun() -> test_util:port_setup(64) end,
      fun test_util:port_teardown/1,
      [fun() ->
               P = test_util:get_thing(),
               ?assert(is_port(P)),
               erlang:unlink(P) end]}].

destroy_test_() ->
  [{setup, fun test_util:port_setup/0,
    fun test_util:null_teardown/1,
    [fun() ->
         P = test_util:get_thing(),
         ?assertMatch(true, js_driver:destroy(P)),
         ?assertError(badarg, js:define(P, <<"var x = 100;">>)),
         erlang:unlink(P) end]}].

spinup_test_() ->
  [fun() ->
       F = fun({ok, P}) -> js_driver:destroy(P) end,
       Ports = [js_driver:new() || _X <- lists:seq(1, 16)],
       [F(P) || P <- Ports] end].


%% @author Marc Worrell <marc@worrell.nl>
%% @copyright 2012 Marc Worrell

%% Copyright 2012 Marc Worrell
%%
%% 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.

-module(survey_q_upload).

-export([
    answer/3,
    prep_answer_header/2,
    prep_answer/3,
    prep_block/2
]).

-include_lib("zotonic.hrl").

answer(_Block, _Answers, _Context) ->
    {ok, none}.

prep_answer_header(_Q, _Context) ->
    [].

prep_answer(_Q, _Answer, _Context) ->
    [].

prep_block(B, _Context) ->
    B.

Fix crash when viewing results with an upload question.

%% @author Marc Worrell <marc@worrell.nl>
%% @copyright 2012 Marc Worrell

%% Copyright 2012 Marc Worrell
%%
%% 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.

-module(survey_q_upload).

-export([
    answer/3,
    prep_answer_header/2,
    prep_answer/3,
    prep_block/2,
    prep_chart/3
]).

-include_lib("zotonic.hrl").

answer(_Block, _Answers, _Context) ->
    {ok, none}.

prep_answer_header(_Q, _Context) ->
    [].

prep_answer(_Q, _Answer, _Context) ->
    [].

prep_block(B, _Context) ->
    B.

prep_chart(_Q, _As, _Context) ->
    undefined.


-module(factors).

-export([lpf/1]).

lpf(Product) ->
    factorise(Product, [], sqrt_primes(Product)).

factorise(1, [HF | _Factors], _Primes) ->
    HF;
factorise(Product, _Factors, []) ->
    Product;
factorise(Product, Factors, [HP | Primes]) when (Product rem HP) =:= 0 ->
    %io:puts("%s %s %s %s", Product, Factors, HP, Primes),
    factorise(Product div HP, [HP | Factors], [HP | Primes]);
factorise(Product, Factors, [_HP | Primes]) ->
    factorise(Product, Factors, Primes).

sqrt_primes(Product) ->
    eratosthenes:primes_to(trunc(math:sqrt(Product))).

Add edoc markup and specs for functions.

%% @author PurityControl
%% @copyright 2015 PurityControl
%% @doc Library to find the largest prime factor of a number.
-module(factors).

-export([lpf/1]).

%% @doc Returns the largest prime factor of a number. If the number is
%% prime then it returns itself
-spec(lpf(integer()) -> integer()).
lpf(Product) ->
    factorise(Product, [], sqrt_primes(Product)).

%% @doc Will return the head of the list of factors if the number is a compound
%% number.
%%
%% Factors are pushed onto the list starting with the lowest. Therefore
%% the head of the list at the end of factorisation when the Product has been
%% reduced to 1 is the largest prime factor.
%%
%% Alternatively, if the list of
%% factors is exhausted (ie. the number is prime) then the Product itself is
%% returned.
-spec(factorise(integer(), list(integer()), list(integer())) -> integer()).
factorise(1, [HF | _Factors], _Primes) ->
    HF;
factorise(Product, _Factors, []) ->
    Product;
factorise(Product, Factors, [HP | Primes]) when (Product rem HP) =:= 0 ->
    %io:puts("%s %s %s %s", Product, Factors, HP, Primes),
    factorise(Product div HP, [HP | Factors], [HP | Primes]);
factorise(Product, Factors, [_HP | Primes]) ->
    factorise(Product, Factors, Primes).

%% @doc Return all the primes up to the sqaure root of the Product
-spec(sqrt_primes(integer()) -> list(integer())).
sqrt_primes(Product) ->
    eratosthenes:primes_to(trunc(math:sqrt(Product))).


-module(jukeboxsession).
-export([initial_state/1, handler/3]).

-record(session, {username, ip}).

default_name() ->
    "Anonymous Coward".

initial_state(IP) ->
    #session{username = default_name(),
	     ip = IP}.

user_id(Session) ->
    {Session#session.username, Session#session.ip}.

r_user_id(Session) ->
    {U,IP} = user_id(Session),
    {array,[U,{array, tuple_to_list(IP)}]}.

handler(State, Request, undefined) ->
    handler(State, Request, State);
handler(_, {call, login, [NewName]}, Session) ->
    NewSession = Session#session{username = NewName},
    {true, 0, NewSession, {response, r_user_id(NewSession)}};
handler(_, {call, whoami, _}, Session) ->
    {false, {response, r_user_id(Session)}};
handler(_, {call, logout, _}, Session) ->
    NewSession = Session#session{username = default_name()},
    {true, 0, NewSession, {response, r_user_id(NewSession)}};
handler(_, {call, search, [{array, Keys}]}, Session) ->
    io:format("Search by keys ~p ~n -> ~p~n", [Keys, trackdb:search_tracks(Keys)]),
    {false, {response, "ok"}}.

Allow anonymous name to be based on session data.

-module(jukeboxsession).
-export([initial_state/1, handler/3]).

-record(session, {username, ip}).

default_name(Session) ->
    lists:flatten(io_lib:format("Anonymous Coward", [])).

initial_state(IP) ->
    #session{username = default_name(#session{ip = IP}),
	     ip = IP}.

user_id(Session) ->
    {Session#session.username, Session#session.ip}.

r_user_id(Session) ->
    {U,IP} = user_id(Session),
    {array,[U,{array, tuple_to_list(IP)}]}.

handler(State, Request, undefined) ->
    handler(State, Request, State);
handler(_, {call, login, [NewName]}, Session) ->
    NewSession = Session#session{username = NewName},
    {true, 0, NewSession, {response, r_user_id(NewSession)}};
handler(_, {call, whoami, _}, Session) ->
    {false, {response, r_user_id(Session)}};
handler(_, {call, logout, _}, Session) ->
    NewSession = Session#session{username = default_name(Session)},
    {true, 0, NewSession, {response, r_user_id(NewSession)}};
handler(_, {call, search, [{array, Keys}]}, Session) ->
    io:format("Search by keys ~p ~n -> ~p~n", [Keys, trackdb:search_tracks(Keys)]),
    {false, {response, "ok"}}.


%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    %% TODO: Port and other parameters should not be hard-coded and should moved to
    %%       the release configuration file
    cowboy:start_clear(cvmfs_fe, 100,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch}}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.

Fix compilation for Cowboy 2.0.0-rc.1

%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    cowboy:start_clear(cvmfs_fe,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch}}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.


-module(test_util).

-export([port_setup/0, port_setup/1, port_teardown/1, null_teardown/1, get_thing/0]).

port_setup() ->
    port_setup(8).

port_setup(Size) ->
  {ok, P} = js_driver:new(8, Size),
  start_thing_holder(P),
  P.

port_teardown(P) ->
  thing_holder ! stop,
  erlang:port_connect(P, self()),
  js_driver:destroy(P).

null_teardown(_) ->
  thing_holder ! stop,
  ok.

get_thing() ->
  thing_holder ! {get_thing, self()},
  receive
    Thing ->
      if
        is_port(Thing) ->
          erlang:port_connect(Thing, self());
        true ->
          ok
      end,
      Thing
  end.

%% Internal functions
start_thing_holder(Thing) ->
  if
    is_port(Thing) ->
      erlang:unlink(Thing);
    true ->
      ok
  end,
  Pid = spawn(fun() -> thing_holder(Thing) end),
  register(thing_holder, Pid),
  Pid.

thing_holder(Thing) ->
  receive
    {get_thing, Caller} ->
      Caller ! Thing,
      thing_holder(Thing);
    stop ->
      ok
  end.

Fix race condition in tests

-module(test_util).

-export([port_setup/0, port_setup/1, port_teardown/1, null_teardown/1, get_thing/0]).

port_setup() ->
    port_setup(8).

port_setup(Size) ->
  {ok, P} = js_driver:new(8, Size),
  start_thing_holder(P),
  P.

port_teardown(P) ->
  thing_holder ! stop,
  % it might take a while until the stop message reaches the holder process
  % and it actually terminates, so wait a little here to make sure it went away
  timer:sleep(20),
  erlang:port_connect(P, self()),
  js_driver:destroy(P).

null_teardown(_) ->
  thing_holder ! stop,
  ok.

get_thing() ->
  thing_holder ! {get_thing, self()},
  receive
    Thing ->
      if
        is_port(Thing) ->
          erlang:port_connect(Thing, self());
        true ->
          ok
      end,
      Thing
  end.

%% Internal functions
start_thing_holder(Thing) ->
  if
    is_port(Thing) ->
      erlang:unlink(Thing);
    true ->
      ok
  end,
  Pid = spawn(fun() -> thing_holder(Thing) end),
  register(thing_holder, Pid),
  Pid.

thing_holder(Thing) ->
  receive
    {get_thing, Caller} ->
      Caller ! Thing,
      thing_holder(Thing);
    stop ->
      ok
  end.


-module(rinamo_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
  case rinamo_config:is_enabled() of
      true -> add_routes();
      _ -> ok
  end,

  rinamo_sup:start_link().

stop(_State) ->
  [webmachine_router:remove_route(R) || R <- routes()].

%% ===================================================================
%% Internal functions
%% ===================================================================

add_routes() ->
  [webmachine_router:add_route(R) || R <- routes()].

props() ->
  [].

routes() ->
  [
    {[rinamo_config:endpoint_prefix()], rinamo_wm_endpoint, props()},
    {[rinamo_config:endpoint_prefix(), "ping"], rinamo_wm_ping, props()}
  ].

Set rinamo supervisor link to only be created if we can startup the application. Started the work or removing Webmachine dependency and migrating to cowboy as a standalone HTTP server to act as the rinamo API interface.


%% @hidden
-module(shotgun_sup).
-author(pyotrgalois).

-behaviour(supervisor).

-export([
         start_link/0,
         init/1
        ]).

-spec start_link() -> {ok, pid()}.
start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

-spec init(term()) ->
    {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
init([]) ->
    Procs = [{shotgun, {shotgun, start_link, []},
              temporary, 5000, worker, [shotgun]}],
    {ok, {{simple_one_for_one, 10, 10}, Procs}}.

Fix dialyzer warning message for R17 version

%% @hidden
-module(shotgun_sup).
-author(pyotrgalois).

-behaviour(supervisor).

-export([
         start_link/0,
         init/1
        ]).

-spec start_link() -> {ok, pid()}.
start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

-spec init(term()) ->
          {ok, {{supervisor:strategy(), non_neg_integer(), pos_integer()},
                [supervisor:child_spec()]}}.
init([]) ->
    Procs = [{shotgun, {shotgun, start_link, []},
              temporary, 5000, worker, [shotgun]}],
    {ok, {{simple_one_for_one, 10, 10}, Procs}}.


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2014 Basho Technologies, Inc.  All Rights Reserved.
%%
%% This file is provided to you 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.
%%
%% -------------------------------------------------------------------
%% @doc This module tracks registrations for riak_cli integrations.

-module(riak_core_cli_registry).

-define(CLI_MODULES, []).

-export([
         register_cli/0
]).

-spec register_cli() -> ok.
register_cli() ->
   riak_cli:register(?CLI_MODULES).

Add cluster_cli to cli registry

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2014 Basho Technologies, Inc.  All Rights Reserved.
%%
%% This file is provided to you 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.
%%
%% -------------------------------------------------------------------
%% @doc This module tracks registrations for riak_cli integrations.

-module(riak_core_cli_registry).

-define(CLI_MODULES, [riak_core_cluster_cli]).

-export([
         register_cli/0
]).

-spec register_cli() -> ok.
register_cli() ->
   riak_cli:register(?CLI_MODULES).


-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2]).

start_link(NumAgents) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [NumAgents]).

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                temporary, 5000, worker, dynamic},

    % Start the child
    Res = case supervisor:start_child(?MODULE, AgentSpec) of
        {ok, Pid} -> Pid;
        {error, {already_started, Pid}} -> Pid;
        {error, _} -> error
    end,
    start_agents(Num - 1, Space, [Res | Results]).

Return if the process is new or exists

-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2]).

start_link(NumAgents) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [NumAgents]).

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                temporary, 5000, worker, dynamic},

    % Start the child
    Res = case supervisor:start_child(?MODULE, AgentSpec) of
        {ok, Pid} -> {new, Pid};
        {error, {already_started, Pid}} -> {exists, Pid};
        {error, _} -> error
    end,
    start_agents(Num - 1, Space, [Res | Results]).


-module(action_event).
-author('Maxim Sokhatsky').
-include_lib("n2o/include/wf.hrl").
-compile(export_all).

render_action(#event{source=undefined}) -> [];
render_action(#event{postback=Postback,actions=Actions,source=Source,target=Control,type=Type,delegate=Delegate}) ->
    Data = "[" ++ string:join([begin
        {Key, Id} = if  is_atom(Src)-> S = atom_to_list(Src),
                        {"atom('"++S++"')", S};
                    true -> {"utf8.toByteArray('" ++ Src ++ "')", Src} end,
        "tuple(" ++ Key ++ ", utf8.toByteArray(document.querySelector('#"
                      ++ Id ++ "').value))" end || Src <- Source]
    ++ ["tuple(tuple(utf8.toByteArray('"++ Control ++"'), bin('detail')), event.detail)"],",") ++ "]",
    PostbackBin = wf_event:new(Postback, Control, Delegate, event, Data),
    [wf:f("document.querySelector('#~s').addEventListener('~s',function (event){", [Control,Type]),PostbackBin,"});"].

Read checked property of checkboxes

-module(action_event).
-author('Maxim Sokhatsky').
-include_lib("n2o/include/wf.hrl").
-compile(export_all).

render_action(#event{source=undefined}) -> [];
render_action(#event{postback=Postback,actions=Actions,source=Source,target=Control,type=Type,delegate=Delegate}) ->
    Data = "[" ++ string:join([begin
        {Key, Id} = if  is_atom(Src)-> S = atom_to_list(Src),
                        {"atom('"++S++"')", S};
                    true -> {"utf8.toByteArray('" ++ Src ++ "')", Src} end,
        "tuple(" ++ Key ++ ", document.querySelector('#" ++ Id ++ "').type == 'checkbox' ? utf8.toByteArray(document.querySelector('#" ++ Id ++ "').checked.toString()) : utf8.toByteArray(document.querySelector('#"
                      ++ Id ++ "').value))" end || Src <- Source]
    ++ ["tuple(tuple(utf8.toByteArray('"++ Control ++"'), bin('detail')), event.detail)"],",") ++ "]",
    PostbackBin = wf_event:new(Postback, Control, Delegate, event, Data),
    [wf:f("document.querySelector('#~s').addEventListener('~s',function (event){", [Control,Type]),PostbackBin,"});"].


%%% @author Andreas Hasselberg <andreas.hasselberg@gmail.com>
%%% @doc
%%%
%%% @end

-module(elli_test).

-include("../include/elli.hrl").

-export([call/5]).

call(Method, RawPath, RequestHeaders, RequestBody, Opts) ->
    Callback = proplists:get_value(callback, Opts),
    CallbackArgs = proplists:get_value(callback_args, Opts),
    Req = elli_http:mk_req(Method, {abs_path, RawPath}, RequestHeaders,
			   RequestBody, {1,1}, undefined),
    ok = Callback:handle_event(elli_startup, [], CallbackArgs),
    Callback:handle(Req, CallbackArgs).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

hello_world_test() ->
    ?assertEqual({ok, [], <<"Hello World!">>},
		 call('GET', <<"/hello/world/">>, [], <<>>,
		      ?example_conf)).

-endif. %% TEST

Call with export to make the example easier to copy.

%%% @author Andreas Hasselberg <andreas.hasselberg@gmail.com>
%%% @doc
%%%
%%% @end

-module(elli_test).

-include("../include/elli.hrl").

-export([call/5]).

call(Method, RawPath, RequestHeaders, RequestBody, Opts) ->
    Callback = proplists:get_value(callback, Opts),
    CallbackArgs = proplists:get_value(callback_args, Opts),
    Req = elli_http:mk_req(Method, {abs_path, RawPath}, RequestHeaders,
			   RequestBody, {1,1}, undefined),
    ok = Callback:handle_event(elli_startup, [], CallbackArgs),
    Callback:handle(Req, CallbackArgs).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

hello_world_test() ->
    ?assertEqual({ok, [], <<"Hello World!">>},
		 elli_test:call('GET', <<"/hello/world/">>, [], <<>>,
		      ?example_conf)).

-endif. %% TEST