diff --git "a/data/erlang/data.json" "b/data/erlang/data.json" new file mode 100644--- /dev/null +++ "b/data/erlang/data.json" @@ -0,0 +1,100 @@ +{"size":478,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"% Nitrogen Web Framework for Erlang\n% Copyright (c) 2008 Rusty Klophaus\n% See MIT-LICENSE for licensing information.\n\n-module (element_spinner).\n-include (\"wf.inc\").\n-compile(export_all).\n\nreflect() -> record_info(fields, spinner).\n\nrender(_ControlID, Record) -> \n\twf:wire(spinner, #hide{}),\n\tTerms = #panel {\n\t\tid=spinner,\n\t\tclass=wf:f(\"spinner ~s\", [Record#spinner.class]),\n\t\tstyle=Record#spinner.style,\n\t\tbody=#image { image=Record#spinner.image }\n\t},\n\t\n\twf:render(Terms).\n\t\n","avg_line_length":21.7272727273,"max_line_length":51,"alphanum_fraction":0.6966527197} +{"size":6294,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2005-2012. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n%%\n%%----------------------------------------------------------------------\n%% Purpose: Verify the application specifics of the asn1 application\n%%----------------------------------------------------------------------\n-module(asn1_app_test).\n\n-compile(export_all).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nall() -> \n [fields, modules, exportall, app_depend].\n\ngroups() -> \n [].\n\ninit_per_group(_GroupName, Config) ->\n\tConfig.\n\nend_per_group(_GroupName, Config) ->\n\tConfig.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ninit_per_suite(suite) -> [];\ninit_per_suite(doc) -> [];\ninit_per_suite(Config) when is_list(Config) ->\n case is_app(asn1) of\n\t{ok, AppFile} ->\n\t io:format(\"AppFile: ~n~p~n\", [AppFile]),\n\t [{app_file, AppFile}|Config];\n\t{error, Reason} ->\n\t fail(Reason)\n end.\n\nis_app(App) ->\n LibDir = code:lib_dir(App),\n File = filename:join([LibDir, \"ebin\", atom_to_list(App) ++ \".app\"]),\n case file:consult(File) of\n\t{ok, [{application, App, AppFile}]} ->\n\t {ok, AppFile};\n\tError ->\n\t {error, {invalid_format, Error}}\n end.\n\n\nend_per_suite(suite) -> [];\nend_per_suite(doc) -> [];\nend_per_suite(Config) when is_list(Config) ->\n Config.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfields(suite) ->\n [];\nfields(doc) ->\n [];\nfields(Config) when is_list(Config) ->\n AppFile = key1search(app_file, Config),\n Fields = [vsn, description, modules, registered, applications],\n case check_fields(Fields, AppFile, []) of\n\t[] ->\n\t ok;\n\tMissing ->\n\t fail({missing_fields, Missing})\n end.\n\ncheck_fields([], _AppFile, Missing) ->\n Missing;\ncheck_fields([Field|Fields], AppFile, Missing) ->\n check_fields(Fields, AppFile, check_field(Field, AppFile, Missing)).\n\ncheck_field(Name, AppFile, Missing) ->\n io:format(\"checking field: ~p~n\", [Name]),\n case lists:keymember(Name, 1, AppFile) of\n\ttrue ->\n\t Missing;\n\tfalse ->\n\t [Name|Missing]\n end.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmodules(suite) ->\n [];\nmodules(doc) ->\n [];\nmodules(Config) when is_list(Config) ->\n AppFile = key1search(app_file, Config),\n Mods = key1search(modules, AppFile),\n EbinList = get_ebin_mods(asn1),\n case missing_modules(Mods, EbinList, []) of\n\t[] ->\n\t ok;\n\tMissing ->\n\t throw({error, {missing_modules, Missing}})\n end,\n case extra_modules(Mods, EbinList, []) of\n\t[] ->\n\t ok;\n\tExtra ->\n\t check_asn1ct_modules(Extra)\n%\t throw({error, {extra_modules, Extra}})\n end,\n {ok, Mods}.\n\t \nget_ebin_mods(App) ->\n LibDir = code:lib_dir(App),\n EbinDir = filename:join([LibDir,\"ebin\"]),\n {ok, Files0} = file:list_dir(EbinDir),\n Files1 = [lists:reverse(File) || File <- Files0],\n [list_to_atom(lists:reverse(Name)) || [$m,$a,$e,$b,$.|Name] <- Files1].\n\ncheck_asn1ct_modules(Extra) ->\n ASN1CTMods = [asn1ct,asn1ct_check,asn1_db,asn1ct_pretty_format,\n\t\t asn1ct_gen,asn1ct_gen_check,asn1ct_gen_per,\n\t\t asn1ct_name,asn1ct_constructed_per,asn1ct_constructed_ber,\n\t\t asn1ct_gen_ber,asn1ct_constructed_ber_bin_v2,\n\t\t asn1ct_gen_ber_bin_v2,asn1ct_value,\n\t\t asn1ct_tok,asn1ct_parser2,asn1ct_table,\n\t\t asn1ct_imm,asn1ct_func,asn1ct_rtt,\n\t\t asn1ct_eval_ext],\n case Extra -- ASN1CTMods of\n\t[] ->\n\t ok;\n\tExtra2 ->\n\t throw({error, {extra_modules, Extra2}})\n end.\n\nmissing_modules([], _Ebins, Missing) ->\n Missing;\nmissing_modules([Mod|Mods], Ebins, Missing) ->\n case lists:member(Mod, Ebins) of\n\ttrue ->\n\t missing_modules(Mods, Ebins, Missing);\n\tfalse ->\n\t io:format(\"missing module: ~p~n\", [Mod]),\n\t missing_modules(Mods, Ebins, [Mod|Missing])\n end.\n\n\nextra_modules(_Mods, [], Extra) ->\n Extra;\nextra_modules(Mods, [Mod|Ebins], Extra) ->\n case lists:member(Mod, Mods) of\n\ttrue ->\n\t extra_modules(Mods, Ebins, Extra);\n\tfalse ->\n\t io:format(\"supefluous module: ~p~n\", [Mod]),\n\t extra_modules(Mods, Ebins, [Mod|Extra])\n end.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nexportall(suite) ->\n [];\nexportall(doc) ->\n [];\nexportall(Config) when is_list(Config) ->\n AppFile = key1search(app_file, Config),\n Mods = key1search(modules, AppFile),\n check_export_all(Mods).\n\n\ncheck_export_all([]) ->\n ok;\ncheck_export_all([Mod|Mods]) ->\n case (catch apply(Mod, module_info, [compile])) of\n\t{'EXIT', {undef, _}} ->\n\t check_export_all(Mods);\n\tO ->\n case lists:keysearch(options, 1, O) of\n false ->\n check_export_all(Mods);\n {value, {options, List}} ->\n case lists:member(export_all, List) of\n true ->\n\t\t\t throw({error, {export_all, Mod}});\n\t\t\tfalse ->\n\t\t\t check_export_all(Mods)\n end\n end\n end.\n\n\t \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\napp_depend(suite) ->\n [];\napp_depend(doc) ->\n [];\napp_depend(Config) when is_list(Config) ->\n AppFile = key1search(app_file, Config),\n Apps = key1search(applications, AppFile),\n check_apps(Apps).\n\n\ncheck_apps([]) ->\n ok;\ncheck_apps([App|Apps]) ->\n case is_app(App) of\n\t{ok, _} ->\n\t check_apps(Apps);\n\tError ->\n\t throw({error, {missing_app, {App, Error}}})\n end.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfail(Reason) ->\n exit({suite_failed, Reason}).\n\nkey1search(Key, L) ->\n case lists:keysearch(Key, 1, L) of\n\tundefined ->\n\t fail({not_found, Key, L});\n\t{value, {Key, Value}} ->\n\t Value\n end.\n","avg_line_length":25.5853658537,"max_line_length":75,"alphanum_fraction":0.5633937083} +{"size":15749,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%------------------------------------------------------------------------\n%% Copyright 2019, OpenTelemetry Authors\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% @doc This module has the behaviour that each exporter must implement\n%% and creates the buffer of trace spans to be exported.\n%%\n%% The exporter process can be configured to export the current finished\n%% spans based on timeouts and the size of the finished spans table.\n%%\n%% Timeouts:\n%% exporting_timeout_ms: How long to let the exports run before killing.\n%% check_table_size_ms: Timeout to check the size of the export table.\n%% scheduled_delay_ms: How often to trigger running the exporters.\n%%\n%% The size limit of the current table where finished spans are stored can\n%% be configured with the `max_queue_size' option.\n%% @end\n%%%-----------------------------------------------------------------------\n-module(otel_batch_processor).\n\n-behaviour(gen_statem).\n-behaviour(otel_span_processor).\n\n-export([start_link\/1,\n on_start\/3,\n on_end\/2,\n set_exporter\/1,\n set_exporter\/2,\n report_cb\/1]).\n\n-export([init\/1,\n callback_mode\/0,\n idle\/3,\n exporting\/3,\n terminate\/3]).\n\n-include_lib(\"opentelemetry_api\/include\/opentelemetry.hrl\").\n-include_lib(\"kernel\/include\/logger.hrl\").\n-include(\"otel_span.hrl\").\n\n-record(data, {exporter :: {module(), term()} | undefined,\n resource :: otel_resource:t(),\n handed_off_table :: atom() | undefined,\n runner_pid :: pid() | undefined,\n max_queue_size :: integer() | infinity,\n exporting_timeout_ms :: integer(),\n check_table_size_ms :: integer() | infinity,\n scheduled_delay_ms :: integer()}).\n\n-define(CURRENT_TABLES_KEY, {?MODULE, current_table}).\n-define(TABLE_1, otel_export_table1).\n-define(TABLE_2, otel_export_table2).\n-define(CURRENT_TABLE, persistent_term:get(?CURRENT_TABLES_KEY)).\n\n-define(DEFAULT_MAX_QUEUE_SIZE, 2048).\n-define(DEFAULT_SCHEDULED_DELAY_MS, timer:seconds(5)).\n-define(DEFAULT_EXPORTER_TIMEOUT_MS, timer:minutes(5)).\n-define(DEFAULT_CHECK_TABLE_SIZE_MS, timer:seconds(1)).\n\n-define(ENABLED_KEY, {?MODULE, enabled_key}).\n\nstart_link(Opts) ->\n gen_statem:start_link({local, ?MODULE}, ?MODULE, [Opts], []).\n\n%% @equiv set_exporter(Exporter, [])\nset_exporter(Exporter) ->\n set_exporter(Exporter, []).\n\n%% @doc Sets the batch exporter `Exporter'.\n-spec set_exporter(module(), term()) -> ok.\nset_exporter(Exporter, Options) ->\n gen_statem:call(?MODULE, {set_exporter, {Exporter, Options}}).\n\n-spec on_start(otel_ctx:t(), opentelemetry:span(), otel_span_processor:processor_config())\n -> opentelemetry:span().\non_start(_Ctx, Span, _) ->\n Span.\n\n-spec on_end(opentelemetry:span(), otel_span_processor:processor_config())\n -> true | dropped | {error, invalid_span} | {error, no_export_buffer}.\non_end(#span{trace_flags=TraceFlags}, _) when not(?IS_SAMPLED(TraceFlags)) ->\n dropped;\non_end(Span=#span{}, _) ->\n do_insert(Span);\non_end(_Span, _) ->\n {error, invalid_span}.\n\ninit([Args]) ->\n process_flag(trap_exit, true),\n\n SizeLimit = maps:get(max_queue_size, Args, ?DEFAULT_MAX_QUEUE_SIZE),\n ExportingTimeout = maps:get(exporting_timeout_ms, Args, ?DEFAULT_EXPORTER_TIMEOUT_MS),\n ScheduledDelay = maps:get(scheduled_delay_ms, Args, ?DEFAULT_SCHEDULED_DELAY_MS),\n CheckTableSize = maps:get(check_table_size_ms, Args, ?DEFAULT_CHECK_TABLE_SIZE_MS),\n\n Exporter = init_exporter(maps:get(exporter, Args, undefined)),\n Resource = otel_tracer_provider:resource(),\n\n _Tid1 = new_export_table(?TABLE_1),\n _Tid2 = new_export_table(?TABLE_2),\n persistent_term:put(?CURRENT_TABLES_KEY, ?TABLE_1),\n\n enable(),\n\n {ok, idle, #data{exporter=Exporter,\n resource = Resource,\n handed_off_table=undefined,\n max_queue_size=case SizeLimit of\n infinity -> infinity;\n _ -> SizeLimit div erlang:system_info(wordsize)\n end,\n exporting_timeout_ms=ExportingTimeout,\n check_table_size_ms=CheckTableSize,\n scheduled_delay_ms=ScheduledDelay}}.\n\ncallback_mode() ->\n [state_functions, state_enter].\n\nidle(enter, _OldState, #data{scheduled_delay_ms=SendInterval}) ->\n {keep_state_and_data, [{{timeout, export_spans}, SendInterval, export_spans}]};\nidle(_, export_spans, Data) ->\n {next_state, exporting, Data};\nidle(EventType, Event, Data) ->\n handle_event_(idle, EventType, Event, Data).\n\nexporting({timeout, export_spans}, export_spans, _) ->\n {keep_state_and_data, [postpone]};\nexporting(enter, _OldState, Data=#data{exporting_timeout_ms=ExportingTimeout,\n scheduled_delay_ms=SendInterval}) ->\n {OldTableName, RunnerPid} = export_spans(Data),\n {keep_state, Data#data{runner_pid=RunnerPid,\n handed_off_table=OldTableName},\n [{state_timeout, ExportingTimeout, exporting_timeout},\n {{timeout, export_spans}, SendInterval, export_spans}]};\nexporting(state_timeout, exporting_timeout, Data=#data{handed_off_table=ExportingTable}) ->\n %% kill current exporting process because it is taking too long\n %% which deletes the exporting table, so create a new one and\n %% repeat the state to force another span exporting immediately\n Data1 = kill_runner(Data),\n new_export_table(ExportingTable),\n {repeat_state, Data1};\n%% important to verify runner_pid and FromPid are the same in case it was sent\n%% after kill_runner was called but before it had done the unlink\nexporting(info, {'EXIT', FromPid, _}, Data=#data{runner_pid=FromPid}) ->\n complete_exporting(Data);\n%% important to verify runner_pid and FromPid are the same in case it was sent\n%% after kill_runner was called but before it had done the unlink\nexporting(info, {completed, FromPid}, Data=#data{runner_pid=FromPid}) ->\n complete_exporting(Data);\nexporting(EventType, Event, Data) ->\n handle_event_(exporting, EventType, Event, Data).\n\nhandle_event_(_State, {timeout, check_table_size}, check_table_size, #data{max_queue_size=infinity}) ->\n keep_state_and_data;\nhandle_event_(_State, {timeout, check_table_size}, check_table_size, #data{max_queue_size=MaxQueueSize}) ->\n case ets:info(?CURRENT_TABLE, size) of\n M when M >= MaxQueueSize ->\n disable(),\n keep_state_and_data;\n _ ->\n enable(),\n keep_state_and_data\n end;\nhandle_event_(_, {call, From}, {set_exporter, Exporter}, Data=#data{exporter=OldExporter}) ->\n shutdown_exporter(OldExporter),\n {keep_state, Data#data{exporter=init_exporter(Exporter)}, [{reply, From, ok}]};\nhandle_event_(_, _, _, _) ->\n keep_state_and_data.\n\nterminate(_, _, _Data) ->\n %% TODO: flush buffers to exporter\n ok.\n\n%%\n\nenable()->\n persistent_term:put(?ENABLED_KEY, true).\n\ndisable() ->\n persistent_term:put(?ENABLED_KEY, false).\n\nis_enabled() ->\n persistent_term:get(?ENABLED_KEY, true).\n\ndo_insert(Span) ->\n try\n case is_enabled() of\n true ->\n ets:insert(?CURRENT_TABLE, Span);\n _ ->\n dropped\n end\n catch\n error:badarg ->\n {error, no_batch_span_processor};\n _:_ ->\n {error, other}\n end.\n\ncomplete_exporting(Data=#data{handed_off_table=ExportingTable})\n when ExportingTable =\/= undefined ->\n new_export_table(ExportingTable),\n {next_state, idle, Data#data{runner_pid=undefined,\n handed_off_table=undefined}}.\n\nkill_runner(Data=#data{runner_pid=RunnerPid}) ->\n erlang:unlink(RunnerPid),\n erlang:exit(RunnerPid, kill),\n Data#data{runner_pid=undefined,\n handed_off_table=undefined}.\n\nnew_export_table(Name) ->\n ets:new(Name, [public,\n named_table,\n {write_concurrency, true},\n duplicate_bag,\n %% OpenTelemetry exporter protos group by the\n %% instrumentation_library. So using instrumentation_library\n %% as the key means we can easily lookup all spans for\n %% for each instrumentation_library and export together.\n {keypos, #span.instrumentation_library}]).\n\ninit_exporter(undefined) ->\n undefined;\ninit_exporter({ExporterModule, Config}) when is_atom(ExporterModule) ->\n try ExporterModule:init(Config) of\n {ok, ExporterConfig} ->\n {ExporterModule, ExporterConfig};\n ignore ->\n undefined\n catch\n Kind:Reason:StackTrace ->\n %% logging in debug level since config argument in stacktrace could have secrets\n ?LOG_DEBUG(#{source => exporter,\n during => init,\n kind => Kind,\n reason => Reason,\n exporter => ExporterModule,\n stacktrace => StackTrace}, #{report_cb => fun ?MODULE:report_cb\/1}),\n\n %% print a more useful message about the failure if we can discern\n %% one from the failure reason and exporter used\n case {Kind, Reason} of\n {error, badarg} when ExporterModule =:= opentelemetry_exporter ->\n case maps:get(protocol, Config, undefined) of\n grpc ->\n %% grpc protocol uses grpcbox which is not included by default\n %% this will check if it is available so we can warn the user if\n %% the dependency needs to be added\n try grpcbox:module_info() of\n _ ->\n undefined\n catch\n _:_ ->\n ?LOG_WARNING(\"OTLP tracer, ~p, failed to initialize when using GRPC protocol and `grpcbox` module is not available in the code path. Verify that you have the `grpcbox` dependency included and rerun.\", [ExporterModule]),\n undefined\n end;\n _ ->\n %% same as the debug log above\n %% without the stacktrace and at a higher level\n ?LOG_WARNING(#{source => exporter,\n during => init,\n kind => Kind,\n reason => Reason,\n exporter => ExporterModule}, #{report_cb => fun ?MODULE:report_cb\/1}),\n undefined\n end;\n {error, undef} when ExporterModule =:= opentelemetry_exporter ->\n ?LOG_WARNING(\"Trace exporter module ~p not found. Verify you have included the `opentelemetry_exporter` dependency.\", [ExporterModule]),\n undefined;\n {error, undef} ->\n ?LOG_WARNING(\"Trace exporter module ~p not found. Verify you have included the dependency that contains the exporter module.\", [ExporterModule]),\n undefined;\n _ ->\n %% same as the debug log above\n %% without the stacktrace and at a higher level\n ?LOG_WARNING(#{source => exporter,\n during => init,\n kind => Kind,\n reason => Reason,\n exporter => ExporterModule}, #{report_cb => fun ?MODULE:report_cb\/1}),\n undefined\n end\n end;\ninit_exporter(ExporterModule) when is_atom(ExporterModule) ->\n init_exporter({ExporterModule, []}).\n\nshutdown_exporter(undefined) ->\n ok;\nshutdown_exporter({ExporterModule, Config}) ->\n ExporterModule:shutdown(Config).\n\nexport_spans(#data{exporter=Exporter,\n resource=Resource}) ->\n CurrentTable = ?CURRENT_TABLE,\n NewCurrentTable = case CurrentTable of\n ?TABLE_1 ->\n ?TABLE_2;\n ?TABLE_2 ->\n ?TABLE_1\n end,\n\n %% an atom is a single word so this does not trigger a global GC\n persistent_term:put(?CURRENT_TABLES_KEY, NewCurrentTable),\n %% set the table to accept inserts\n enable(),\n\n Self = self(),\n RunnerPid = erlang:spawn_link(fun() -> send_spans(Self, Resource, Exporter) end),\n ets:give_away(CurrentTable, RunnerPid, export),\n {CurrentTable, RunnerPid}.\n\n%% Additional benefit of using a separate process is calls to `register` won't\n%% timeout if the actual exporting takes longer than the call timeout\nsend_spans(FromPid, Resource, Exporter) ->\n receive\n {'ETS-TRANSFER', Table, FromPid, export} ->\n TableName = ets:rename(Table, current_send_table),\n export(Exporter, Resource, TableName),\n ets:delete(TableName),\n completed(FromPid)\n end.\n\ncompleted(FromPid) ->\n FromPid ! {completed, self()}.\n\nexport(undefined, _, _) ->\n true;\nexport({ExporterModule, Config}, Resource, SpansTid) ->\n %% don't let a exporter exception crash us\n %% and return true if exporter failed\n try\n ExporterModule:export(SpansTid, Resource, Config) =:= failed_not_retryable\n catch\n Kind:Reason:StackTrace ->\n ?LOG_INFO(#{source => exporter,\n during => export,\n kind => Kind,\n reason => Reason,\n exporter => ExporterModule,\n stacktrace => StackTrace}, #{report_cb => fun ?MODULE:report_cb\/1}),\n true\n end.\n\n%% logger format functions\nreport_cb(#{source := exporter,\n during := init,\n kind := Kind,\n reason := Reason,\n exporter := ExporterModule,\n stacktrace := StackTrace}) ->\n {\"OTLP tracer ~p failed to initialize: ~ts\",\n [ExporterModule, format_exception(Kind, Reason, StackTrace)]};\nreport_cb(#{source := exporter,\n during := init,\n kind := Kind,\n reason := Reason,\n exporter := ExporterModule}) ->\n {\"OTLP tracer ~p failed to initialize with exception ~p:~p\", [ExporterModule, Kind, Reason]};\nreport_cb(#{source := exporter,\n during := export,\n kind := Kind,\n reason := Reason,\n exporter := ExporterModule,\n stacktrace := StackTrace}) ->\n {\"exporter threw exception: exporter=~p ~ts\",\n [ExporterModule, format_exception(Kind, Reason, StackTrace)]}.\n\n-if(?OTP_RELEASE >= 24).\nformat_exception(Kind, Reason, StackTrace) ->\n erl_error:format_exception(Kind, Reason, StackTrace).\n-else.\nformat_exception(Kind, Reason, StackTrace) ->\n io_lib:format(\"~p:~p ~p\", [Kind, Reason, StackTrace]).\n-endif.\n","avg_line_length":40.6950904393,"max_line_length":255,"alphanum_fraction":0.5993396406} +{"size":2320,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%--------------------------------------------------------------------\n%% Copyright (c) 2021 EMQ Technologies Co., Ltd. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%--------------------------------------------------------------------\n\n%% Collection of functions for creating node dumps\n-module(emqx_node_dump).\n\n-export([ sys_info\/0\n , app_env_dump\/0\n ]).\n\nsys_info() ->\n #{ release => emqx_app:get_release()\n , otp_version => emqx_vm:get_otp_version()\n }.\n\napp_env_dump() ->\n censor(ets:tab2list(ac_tab)).\n\ncensor([]) ->\n [];\ncensor([{{env, App, Key}, Val} | Rest]) ->\n [{{env, App, Key}, censor([Key, App], Val)} | censor(Rest)];\ncensor([_ | Rest]) ->\n censor(Rest).\n\ncensor(Path, {Key, Val}) when is_atom(Key) ->\n {Key, censor([Key|Path], Val)};\ncensor(Path, M) when is_map(M) ->\n Fun = fun(Key, Val) ->\n censor([Key|Path], Val)\n end,\n maps:map(Fun, M);\ncensor(Path, L = [Fst|_]) when is_tuple(Fst) ->\n [censor(Path, I) || I <- L];\ncensor(Path, Val) ->\n case Path of\n [password|_] ->\n obfuscate_value(Val);\n [secret|_] ->\n obfuscate_value(Val);\n _ ->\n Val\n end.\n\nobfuscate_value(Val) when is_binary(Val) ->\n <<\"********\">>;\nobfuscate_value(_Val) ->\n \"********\".\n\n-ifdef(TEST).\n\n-include_lib(\"eunit\/include\/eunit.hrl\").\n\ncensor_test() ->\n ?assertMatch( [{{env, emqx, listeners}, #{password := <<\"********\">>}}]\n , censor([foo, {{env, emqx, listeners}, #{password => <<\"secret\">>}}, {app, bar}])\n ),\n ?assertMatch( [{{env, emqx, listeners}, [{foo, 1}, {password, \"********\"}]}]\n , censor([{{env, emqx, listeners}, [{foo, 1}, {password, \"secret\"}]}])\n ).\n\n-endif. %% TEST\n","avg_line_length":30.5263157895,"max_line_length":98,"alphanum_fraction":0.5392241379} +{"size":1615,"ext":"erl","lang":"Erlang","max_stars_count":45.0,"content":"%%% Copyright (c) 2015, Michael Santos \n%%%\n%%% Permission to use, copy, modify, and\/or distribute this software for any\n%%% purpose with or without fee is hereby granted, provided that the above\n%%% copyright notice and this permission notice appear in all copies.\n%%%\n%%% THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n%%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n%%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n%%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n%%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n%%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n%%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n-module(alcove_codec_SUITE).\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n-include_lib(\"alcove\/include\/alcove.hrl\").\n\n-export([\n all\/0\n]).\n\n-export([\n decode\/1\n]).\n\nall() ->\n [decode].\n\n%%\n%% Tests\n%%\n\ndecode(_Config) ->\n % Length, Message type, Term\n Msg = <<\n 0,\n 37,\n 0,\n 3,\n 0,\n 0,\n 1,\n 39,\n 0,\n 29,\n 0,\n 3,\n 0,\n 0,\n 2,\n 39,\n 0,\n 21,\n 0,\n 3,\n 0,\n 0,\n 3,\n 39,\n 0,\n 13,\n 0,\n 4,\n 131,\n 109,\n 0,\n 0,\n 0,\n 5,\n 48,\n 46,\n 50,\n 46,\n 48\n >>,\n\n {alcove_call, [295, 551, 807], <<\"0.2.0\">>} = alcove_codec:decode(Msg).\n","avg_line_length":20.4430379747,"max_line_length":76,"alphanum_fraction":0.5448916409} +{"size":16794,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2008-2012. All Rights Reserved.\n%%\n%% The contents of this file are subject to the Erlang Public License,\n%% Version 1.1, (the \"License\"); you may not use this file except in\n%% compliance with the License. You should have received a copy of the\n%% Erlang Public License along with this software. If not, it can be\n%% retrieved online at http:\/\/www.erlang.org\/.\n%%\n%% Software distributed under the License is distributed on an \"AS IS\"\n%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See\n%% the License for the specific language governing rights and limitations\n%% under the License.\n%%\n%% %CopyrightEnd%\n%% This file is generated DO NOT EDIT\n\n%% @doc See external documentation: wxMouseEvent<\/a>.\n%%
Use {@link wxEvtHandler:connect\/3.} with EventType:<\/dt>\n%%
left_down<\/em>, left_up<\/em>, middle_down<\/em>, middle_up<\/em>, right_down<\/em>, right_up<\/em>, motion<\/em>, enter_window<\/em>, leave_window<\/em>, left_dclick<\/em>, middle_dclick<\/em>, right_dclick<\/em>, mousewheel<\/em>, nc_left_down<\/em>, nc_left_up<\/em>, nc_middle_down<\/em>, nc_middle_up<\/em>, nc_right_down<\/em>, nc_right_up<\/em>, nc_motion<\/em>, nc_enter_window<\/em>, nc_leave_window<\/em>, nc_left_dclick<\/em>, nc_middle_dclick<\/em>, nc_right_dclick<\/em><\/dd><\/dl>\n%% See also the message variant {@link wxEvtHandler:wxMouse(). #wxMouse{}} event record type.\n%%\n%%

This class is derived (and can use functions) from:\n%%
{@link wxEvent}\n%% <\/p>\n%% @type wxMouseEvent(). An object reference, The representation is internal\n%% and can be changed without notice. It can't be used for comparsion\n%% stored on disc or distributed for use on other nodes.\n\n-module(wxMouseEvent).\n-include(\"wxe.hrl\").\n-export([altDown\/1,button\/2,buttonDClick\/1,buttonDClick\/2,buttonDown\/1,buttonDown\/2,\n buttonUp\/1,buttonUp\/2,cmdDown\/1,controlDown\/1,dragging\/1,entering\/1,\n getButton\/1,getLinesPerAction\/1,getLogicalPosition\/2,getPosition\/1,\n getWheelDelta\/1,getWheelRotation\/1,getX\/1,getY\/1,isButton\/1,isPageScroll\/1,\n leaving\/1,leftDClick\/1,leftDown\/1,leftIsDown\/1,leftUp\/1,metaDown\/1,\n middleDClick\/1,middleDown\/1,middleIsDown\/1,middleUp\/1,moving\/1,rightDClick\/1,\n rightDown\/1,rightIsDown\/1,rightUp\/1,shiftDown\/1]).\n\n%% inherited exports\n-export([getId\/1,getSkipped\/1,getTimestamp\/1,isCommandEvent\/1,parent_class\/1,\n resumePropagation\/2,shouldPropagate\/1,skip\/1,skip\/2,stopPropagation\/1]).\n\n-export_type([wxMouseEvent\/0]).\n%% @hidden\nparent_class(wxEvent) -> true;\nparent_class(_Class) -> erlang:error({badtype, ?MODULE}).\n\n-type wxMouseEvent() :: wx:wx_object().\n%% @doc See
external documentation<\/a>.\n-spec altDown(This) -> boolean() when\n\tThis::wxMouseEvent().\naltDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_AltDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec button(This, But) -> boolean() when\n\tThis::wxMouseEvent(), But::integer().\nbutton(#wx_ref{type=ThisT,ref=ThisRef},But)\n when is_integer(But) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_Button,\n <>).\n\n%% @equiv buttonDClick(This, [])\n-spec buttonDClick(This) -> boolean() when\n\tThis::wxMouseEvent().\n\nbuttonDClick(This)\n when is_record(This, wx_ref) ->\n buttonDClick(This, []).\n\n%% @doc See external documentation<\/a>.\n-spec buttonDClick(This, [Option]) -> boolean() when\n\tThis::wxMouseEvent(),\n\tOption :: {but, integer()}.\nbuttonDClick(#wx_ref{type=ThisT,ref=ThisRef}, Options)\n when is_list(Options) ->\n ?CLASS(ThisT,wxMouseEvent),\n MOpts = fun({but, But}, Acc) -> [<<1:32\/?UI,But:32\/?UI>>|Acc];\n (BadOpt, _) -> erlang:error({badoption, BadOpt}) end,\n BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),\n wxe_util:call(?wxMouseEvent_ButtonDClick,\n <>).\n\n%% @equiv buttonDown(This, [])\n-spec buttonDown(This) -> boolean() when\n\tThis::wxMouseEvent().\n\nbuttonDown(This)\n when is_record(This, wx_ref) ->\n buttonDown(This, []).\n\n%% @doc See external documentation<\/a>.\n-spec buttonDown(This, [Option]) -> boolean() when\n\tThis::wxMouseEvent(),\n\tOption :: {but, integer()}.\nbuttonDown(#wx_ref{type=ThisT,ref=ThisRef}, Options)\n when is_list(Options) ->\n ?CLASS(ThisT,wxMouseEvent),\n MOpts = fun({but, But}, Acc) -> [<<1:32\/?UI,But:32\/?UI>>|Acc];\n (BadOpt, _) -> erlang:error({badoption, BadOpt}) end,\n BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),\n wxe_util:call(?wxMouseEvent_ButtonDown,\n <>).\n\n%% @equiv buttonUp(This, [])\n-spec buttonUp(This) -> boolean() when\n\tThis::wxMouseEvent().\n\nbuttonUp(This)\n when is_record(This, wx_ref) ->\n buttonUp(This, []).\n\n%% @doc See external documentation<\/a>.\n-spec buttonUp(This, [Option]) -> boolean() when\n\tThis::wxMouseEvent(),\n\tOption :: {but, integer()}.\nbuttonUp(#wx_ref{type=ThisT,ref=ThisRef}, Options)\n when is_list(Options) ->\n ?CLASS(ThisT,wxMouseEvent),\n MOpts = fun({but, But}, Acc) -> [<<1:32\/?UI,But:32\/?UI>>|Acc];\n (BadOpt, _) -> erlang:error({badoption, BadOpt}) end,\n BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),\n wxe_util:call(?wxMouseEvent_ButtonUp,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec cmdDown(This) -> boolean() when\n\tThis::wxMouseEvent().\ncmdDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_CmdDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec controlDown(This) -> boolean() when\n\tThis::wxMouseEvent().\ncontrolDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_ControlDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec dragging(This) -> boolean() when\n\tThis::wxMouseEvent().\ndragging(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_Dragging,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec entering(This) -> boolean() when\n\tThis::wxMouseEvent().\nentering(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_Entering,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getButton(This) -> integer() when\n\tThis::wxMouseEvent().\ngetButton(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetButton,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getPosition(This) -> {X::integer(), Y::integer()} when\n\tThis::wxMouseEvent().\ngetPosition(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetPosition,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getLogicalPosition(This, Dc) -> {X::integer(), Y::integer()} when\n\tThis::wxMouseEvent(), Dc::wxDC:wxDC().\ngetLogicalPosition(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=DcT,ref=DcRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n ?CLASS(DcT,wxDC),\n wxe_util:call(?wxMouseEvent_GetLogicalPosition,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getLinesPerAction(This) -> integer() when\n\tThis::wxMouseEvent().\ngetLinesPerAction(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetLinesPerAction,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getWheelRotation(This) -> integer() when\n\tThis::wxMouseEvent().\ngetWheelRotation(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetWheelRotation,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getWheelDelta(This) -> integer() when\n\tThis::wxMouseEvent().\ngetWheelDelta(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetWheelDelta,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getX(This) -> integer() when\n\tThis::wxMouseEvent().\ngetX(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetX,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec getY(This) -> integer() when\n\tThis::wxMouseEvent().\ngetY(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_GetY,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec isButton(This) -> boolean() when\n\tThis::wxMouseEvent().\nisButton(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_IsButton,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec isPageScroll(This) -> boolean() when\n\tThis::wxMouseEvent().\nisPageScroll(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_IsPageScroll,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec leaving(This) -> boolean() when\n\tThis::wxMouseEvent().\nleaving(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_Leaving,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec leftDClick(This) -> boolean() when\n\tThis::wxMouseEvent().\nleftDClick(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_LeftDClick,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec leftDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nleftDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_LeftDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec leftIsDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nleftIsDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_LeftIsDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec leftUp(This) -> boolean() when\n\tThis::wxMouseEvent().\nleftUp(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_LeftUp,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec metaDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nmetaDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_MetaDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec middleDClick(This) -> boolean() when\n\tThis::wxMouseEvent().\nmiddleDClick(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_MiddleDClick,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec middleDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nmiddleDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_MiddleDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec middleIsDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nmiddleIsDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_MiddleIsDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec middleUp(This) -> boolean() when\n\tThis::wxMouseEvent().\nmiddleUp(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_MiddleUp,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec moving(This) -> boolean() when\n\tThis::wxMouseEvent().\nmoving(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_Moving,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec rightDClick(This) -> boolean() when\n\tThis::wxMouseEvent().\nrightDClick(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_RightDClick,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec rightDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nrightDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_RightDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec rightIsDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nrightIsDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_RightIsDown,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec rightUp(This) -> boolean() when\n\tThis::wxMouseEvent().\nrightUp(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_RightUp,\n <>).\n\n%% @doc See external documentation<\/a>.\n-spec shiftDown(This) -> boolean() when\n\tThis::wxMouseEvent().\nshiftDown(#wx_ref{type=ThisT,ref=ThisRef}) ->\n ?CLASS(ThisT,wxMouseEvent),\n wxe_util:call(?wxMouseEvent_ShiftDown,\n <>).\n\n %% From wxEvent\n%% @hidden\nstopPropagation(This) -> wxEvent:stopPropagation(This).\n%% @hidden\nskip(This, Options) -> wxEvent:skip(This, Options).\n%% @hidden\nskip(This) -> wxEvent:skip(This).\n%% @hidden\nshouldPropagate(This) -> wxEvent:shouldPropagate(This).\n%% @hidden\nresumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).\n%% @hidden\nisCommandEvent(This) -> wxEvent:isCommandEvent(This).\n%% @hidden\ngetTimestamp(This) -> wxEvent:getTimestamp(This).\n%% @hidden\ngetSkipped(This) -> wxEvent:getSkipped(This).\n%% @hidden\ngetId(This) -> wxEvent:getId(This).\n","avg_line_length":42.8418367347,"max_line_length":576,"alphanum_fraction":0.7312730737} +{"size":876,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%% coding: latin-1\n%%------------------------------------------------------------\n%%\n%% Implementation stub file\n%% \n%% Target: CosPropertyService_ConflictingProperty\n%% Source: \/net\/isildur\/ldisk\/daily_build\/19_prebuild_opu_o.2017-03-14_21\/otp_src_19\/lib\/cosProperty\/src\/CosProperty.idl\n%% IC vsn: 4.4.2\n%% \n%% This file is automatically generated. DO NOT EDIT IT.\n%%\n%%------------------------------------------------------------\n\n-module('CosPropertyService_ConflictingProperty').\n-ic_compiled(\"4_4_2\").\n\n\n-include(\"CosPropertyService.hrl\").\n\n-export([tc\/0,id\/0,name\/0]).\n\n\n\n%% returns type code\ntc() -> {tk_except,\"IDL:omg.org\/CosPropertyService\/ConflictingProperty:1.0\",\n \"ConflictingProperty\",[]}.\n\n%% returns id\nid() -> \"IDL:omg.org\/CosPropertyService\/ConflictingProperty:1.0\".\n\n%% returns name\nname() -> \"CosPropertyService_ConflictingProperty\".\n\n\n\n","avg_line_length":24.3333333333,"max_line_length":120,"alphanum_fraction":0.6164383562} +{"size":36059,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%%\n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2005-2013. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%%\n\n-module(zlib_SUITE).\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n\n-compile(export_all).\n\n-define(error(Format,Args),\n\tput(test_server_loc,{?MODULE,?LINE}),\n\terror(Format,Args,?MODULE,?LINE)).\n\n%% Learn erts team how to really write tests ;-)\n-define(m(ExpectedRes,Expr),\n\tfun() ->\n\t\tACtual1 = (catch (Expr)),\n\t\ttry case ACtual1 of\n\t\t\tExpectedRes -> ACtual1\n\t\t end\n\t\tcatch \n\t\t error:{case_clause,ACtuAl} ->\t\t\t\n\t\t\t?error(\"Not Matching Actual result was:~n ~p ~n\",\n\t\t\t [ACtuAl]),\n\t\t\tACtuAl\n\t\tend\n\tend()).\n\n-define(BARG, {'EXIT',{badarg,[{zlib,_,_,_}|_]}}).\n-define(DATA_ERROR, {'EXIT',{data_error,[{zlib,_,_,_}|_]}}).\n\ninit_per_testcase(_Func, Config) ->\n Config.\n\nend_per_testcase(_Func, _Config) ->\n ok.\n\nerror(Format, Args, File, Line) ->\n io:format(\"~p:~p: ERROR: \" ++ Format, [File,Line|Args]),\n group_leader() ! {failed, File, Line}.\n\n%% Hopefully I don't need this to get it to work with the testserver..\n%% Fail = #'REASON'{file = filename:basename(File),\n%% \t\t line = Line,\n%% \t\t desc = Args},\n%% case global:whereis_name(mnesia_test_case_sup) of\n%% \tundefined -> \n%% \t ignore;\n%% \tPid -> \n%% \t Pid ! Fail\n%% \t %% \t global:send(mnesia_test_case_sup, Fail),\n%% end,\n%% log(\"<>ERROR<>~n\" ++ Format, Args, File, Line).\n\nsuite() ->\n [{ct_hooks,[ts_install_cth]},\n {timetrap,{minutes,1}}].\n\nall() -> \n [{group, api}, {group, examples}, {group, func}, smp,\n otp_9981,\n otp_7359].\n\ngroups() -> \n [{api, [],\n [api_open_close, api_deflateInit,\n api_deflateSetDictionary, api_deflateReset,\n api_deflateParams, api_deflate, api_deflateEnd,\n api_inflateInit, api_inflateSetDictionary,\n api_inflateSync, api_inflateReset, api_inflate, api_inflateChunk,\n api_inflateEnd, api_setBufsz, api_getBufsz, api_crc32,\n api_adler32, api_getQSize, api_un_compress, api_un_zip,\n api_g_un_zip]},\n {examples, [], [intro]},\n {func, [],\n [zip_usage, gz_usage, gz_usage2, compress_usage,\n dictionary_usage, large_deflate, crc, adler]}].\n\ninit_per_suite(Config) ->\n Config.\n\nend_per_suite(_Config) ->\n ok.\n\ninit_per_group(_GroupName, Config) ->\n Config.\n\nend_per_group(_GroupName, Config) ->\n Config.\n\n\n\n%% Test open\/0 and close\/1.\napi_open_close(Config) when is_list(Config) ->\n Fd1 = zlib:open(),\n Fd2 = zlib:open(),\n ?m(false,Fd1 == Fd2),\n ?m(ok,zlib:close(Fd1)),\n ?m(?BARG, zlib:close(Fd1)),\n ?m(ok,zlib:close(Fd2)),\n\n %% Make sure that we don't get any EXIT messages if trap_exit is enabled.\n process_flag(trap_exit, true),\n Fd3 = zlib:open(),\n ?m(ok,zlib:close(Fd3)),\n receive\n\tAny -> ct:fail({unexpected_message,Any})\n after 10 -> ok\n end.\n\n%% Test deflateInit\/2 and \/6.\napi_deflateInit(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(?BARG, zlib:deflateInit(gurka, none)),\n ?m(?BARG, zlib:deflateInit(gurka, gurka)),\n ?m(?BARG, zlib:deflateInit(Z1, gurka)),\n Levels = [none, default, best_speed, best_compression] ++ lists:seq(0,9),\n lists:foreach(fun(Level) ->\n\t\t\t Z = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z, Level)),\n\t\t\t ?m(ok,zlib:close(Z))\n\t\t end, Levels),\n %% \/6\n ?m(?BARG, zlib:deflateInit(Z1,gurka,deflated,-15,8,default)),\n\n ?m(?BARG, zlib:deflateInit(Z1,default,undefined,-15,8,default)),\n\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,48,8,default)),\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-20,8,default)),\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-7,8,default)),\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,7,8,default)),\n\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-15,0,default)),\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-15,10,default)), \n\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-15,8,0)),\n ?m(?BARG, zlib:deflateInit(Z1,default,deflated,-15,8,undefined)),\n\n lists:foreach(fun(Level) ->\n\t\t\t Z = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z, Level, deflated, -15, 8, default)),\n\t\t\t ?m(ok,zlib:close(Z))\n\t\t end, Levels),\n\n lists:foreach(fun(Wbits) ->\n\t\t\t Z11 = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z11,best_compression,deflated,\n\t\t\t\t\t\t Wbits,8,default)),\n\t\t\t Z12 = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z12,default,deflated,-Wbits,8,default)),\n\t\t\t ?m(ok,zlib:close(Z11)),\n\t\t\t ?m(ok,zlib:close(Z12))\n\t\t end, lists:seq(8, 15)),\n\n lists:foreach(fun(MemLevel) ->\n\t\t\t Z = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z,default,deflated,-15, \n\t\t\t\t\t\t MemLevel,default)),\n\t\t\t ?m(ok,zlib:close(Z))\n\t\t end, lists:seq(1,8)),\n\n Strategies = [filtered,huffman_only,rle,default],\n lists:foreach(fun(Strategy) ->\n\t\t\t Z = zlib:open(),\n\t\t\t ?m(ok, zlib:deflateInit(Z,best_speed,deflated,-15,8,Strategy)),\n\t\t\t ?m(ok,zlib:close(Z))\n\t\t end, Strategies),\n ?m(ok, zlib:deflateInit(Z1,default,deflated,-15,8,default)),\n ?m({'EXIT',_}, zlib:deflateInit(Z1,none,deflated,-15,8,default)), %% ?? \n ?m(ok, zlib:close(Z1)).\n\n%% Test deflateSetDictionary.\napi_deflateSetDictionary(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(Id when is_integer(Id), zlib:deflateSetDictionary(Z1, <<1,1,2,3,4,5,1>>)),\n ?m(Id when is_integer(Id), zlib:deflateSetDictionary(Z1, [1,1,2,3,4,5,1])),\n ?m(?BARG, zlib:deflateSetDictionary(Z1, gurka)),\n ?m(?BARG, zlib:deflateSetDictionary(Z1, 128)),\n ?m(_, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, none)),\n ?m({'EXIT',{stream_error,_}},zlib:deflateSetDictionary(Z1,<<1,1,2,3,4,5,1>>)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test deflateReset.\napi_deflateReset(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(_, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, none)),\n ?m(ok, zlib:deflateReset(Z1)),\n ?m(ok, zlib:deflateReset(Z1)),\n %% FIXME how do I make this go wrong??\n ?m(ok, zlib:close(Z1)).\n\n%% Test deflateParams.\napi_deflateParams(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(_, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, none)),\n ?m(ok, zlib:deflateParams(Z1, best_compression, huffman_only)),\n ?m(_, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, sync)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test deflate.\napi_deflate(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m([B] when is_binary(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, finish)),\n ?m(ok, zlib:deflateReset(Z1)),\n ?m([B] when is_binary(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, finish)),\n ?m(ok, zlib:deflateReset(Z1)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, none)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, sync)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, full)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<>>, finish)),\n\n ?m(?BARG, zlib:deflate(gurka, <<1,1,1,1,1,1,1,1,1>>, full)),\n ?m(?BARG, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, asdj)),\n ?m(?BARG, zlib:deflate(Z1, <<1,1,1,1,1,1,1,1,1>>, 198)),\n %% Causes problems ERROR REPORT\n ?m(?BARG, zlib:deflate(Z1, [asdj,asd], none)),\n\n ?m(ok, zlib:close(Z1)).\n\n%% Test deflateEnd.\napi_deflateEnd(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(ok, zlib:deflateEnd(Z1)),\n ?m({'EXIT', {einval,_}}, zlib:deflateEnd(Z1)), %% ??\n ?m(?BARG, zlib:deflateEnd(gurka)),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<\"Kilroy was here\">>)),\n ?m({'EXIT', {data_error,_}}, zlib:deflateEnd(Z1)),\n ?m(ok, zlib:deflateInit(Z1, default)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<\"Kilroy was here\">>)),\n ?m(B when is_list(B), zlib:deflate(Z1, <<\"Kilroy was here\">>, finish)),\n ?m(ok, zlib:deflateEnd(Z1)),\n\n ?m(ok, zlib:close(Z1)).\n\n%% Test inflateInit \/1 and \/2.\napi_inflateInit(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(?BARG, zlib:inflateInit(gurka)),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m({'EXIT',{einval,_}}, zlib:inflateInit(Z1, 15)), %% ??\n lists:foreach(fun(Wbits) ->\n\t\t\t Z11 = zlib:open(),\n\t\t\t ?m(ok, zlib:inflateInit(Z11,Wbits)),\n\t\t\t Z12 = zlib:open(),\n\t\t\t ?m(ok, zlib:inflateInit(Z12,-Wbits)),\n\t\t\t ?m(ok,zlib:close(Z11)),\n\t\t\t ?m(ok,zlib:close(Z12))\n\t\t end, lists:seq(8,15)),\n ?m(?BARG, zlib:inflateInit(gurka, -15)),\n ?m(?BARG, zlib:inflateInit(Z1, 7)),\n ?m(?BARG, zlib:inflateInit(Z1, -7)),\n ?m(?BARG, zlib:inflateInit(Z1, 48)),\n ?m(?BARG, zlib:inflateInit(Z1, -16)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test inflateSetDictionary.\napi_inflateSetDictionary(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m(?BARG, zlib:inflateSetDictionary(gurka,<<1,1,1,1,1>>)),\n ?m(?BARG, zlib:inflateSetDictionary(Z1,102)),\n ?m(?BARG, zlib:inflateSetDictionary(Z1,gurka)),\n Dict = <<1,1,1,1,1>>,\n ?m({'EXIT',{stream_error,_}}, zlib:inflateSetDictionary(Z1,Dict)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test inflateSync.\napi_inflateSync(Config) when is_list(Config) ->\n {skip,\"inflateSync\/1 sucks\"}.\n%% Z1 = zlib:open(),\n%% ?m(ok, zlib:deflateInit(Z1)),\n%% B1list0 = zlib:deflate(Z1, \"gurkan gurra ger galna tunnor\", full),\n%% B2 = zlib:deflate(Z1, \"grodan boll\", finish),\n%% io:format(\"~p\\n\", [B1list0]),\n%% io:format(\"~p\\n\", [B2]),\n%% ?m(ok, zlib:deflateEnd(Z1)),\n%% B1 = clobber(14, list_to_binary(B1list0)),\n%% Compressed = list_to_binary([B1,B2]),\n%% io:format(\"~p\\n\", [Compressed]),\n\n%% ?m(ok, zlib:inflateInit(Z1)),\n%% ?m(?BARG, zlib:inflateSync(gurka)),\n%% ?m({'EXIT',{data_error,_}}, zlib:inflate(Z1, Compressed)),\n%% ?m(ok, zlib:inflateSync(Z1)),\n%% Ubs = zlib:inflate(Z1, []),\n%% <<\"grodan boll\">> = list_to_binary(Ubs),\n%% ?m(ok, zlib:close(Z1)).\n\nclobber(N, Bin) when is_binary(Bin) ->\n T = list_to_tuple(binary_to_list(Bin)),\n Byte = case element(N, T) of\n\t 255 -> 254;\n\t B -> B+1\n\t end,\n list_to_binary(tuple_to_list(setelement(N, T, Byte))).\n\n%% Test inflateReset.\napi_inflateReset(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m(?BARG, zlib:inflateReset(gurka)),\n ?m(ok, zlib:inflateReset(Z1)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test inflate.\napi_inflate(Config) when is_list(Config) ->\n Data = [<<1,2,2,3,3,3,4,4,4,4>>],\n Compressed = zlib:compress(Data),\n Z1 = zlib:open(),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m([], zlib:inflate(Z1, <<>>)),\n ?m(Data, zlib:inflate(Z1, Compressed)),\n ?m(ok, zlib:inflateEnd(Z1)),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m(Data, zlib:inflate(Z1, Compressed)),\n ?m(?BARG, zlib:inflate(gurka, Compressed)),\n ?m(?BARG, zlib:inflate(Z1, 4384)),\n ?m(?BARG, zlib:inflate(Z1, [atom_list])), \n ?m(ok, zlib:inflateEnd(Z1)),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m({'EXIT',{data_error,_}}, zlib:inflate(Z1, <<2,1,2,1,2>>)), \n ?m(ok, zlib:close(Z1)).\n\n%% Test inflateChunk.\napi_inflateChunk(Config) when is_list(Config) ->\n ChunkSize = 1024,\n Data = << <<(I rem 150)>> || I <- lists:seq(1, 3 * ChunkSize) >>,\n Part1 = binary:part(Data, 0, ChunkSize),\n Part2 = binary:part(Data, ChunkSize, ChunkSize),\n Part3 = binary:part(Data, ChunkSize * 2, ChunkSize),\n Compressed = zlib:compress(Data),\n Z1 = zlib:open(),\n zlib:setBufSize(Z1, ChunkSize),\n ?m(ok, zlib:inflateInit(Z1)),\n ?m([], zlib:inflateChunk(Z1, <<>>)),\n ?m({more, Part1}, zlib:inflateChunk(Z1, Compressed)),\n ?m({more, Part2}, zlib:inflateChunk(Z1)),\n ?m(Part3, zlib:inflateChunk(Z1)),\n ?m(ok, zlib:inflateEnd(Z1)),\n\n ?m(ok, zlib:inflateInit(Z1)),\n ?m({more, Part1}, zlib:inflateChunk(Z1, Compressed)),\n\n ?m(ok, zlib:inflateReset(Z1)),\n\n zlib:setBufSize(Z1, size(Data)),\n ?m(Data, zlib:inflateChunk(Z1, Compressed)),\n ?m(ok, zlib:inflateEnd(Z1)),\n\n ?m(ok, zlib:inflateInit(Z1)),\n ?m(?BARG, zlib:inflateChunk(gurka, Compressed)),\n ?m(?BARG, zlib:inflateChunk(Z1, 4384)),\n ?m({'EXIT',{data_error,_}}, zlib:inflateEnd(Z1)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test inflateEnd.\napi_inflateEnd(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m({'EXIT',{einval,_}}, zlib:inflateEnd(Z1)), \n ?m(ok, zlib:inflateInit(Z1)),\n ?m(?BARG, zlib:inflateEnd(gurka)),\n ?m({'EXIT',{data_error,_}}, zlib:inflateEnd(Z1)),\n ?m({'EXIT',{einval,_}}, zlib:inflateEnd(Z1)), \n ?m(ok, zlib:inflateInit(Z1)),\n ?m(B when is_list(B), zlib:inflate(Z1, zlib:compress(\"abc\"))),\n ?m(ok, zlib:inflateEnd(Z1)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test getBufsz.\napi_getBufsz(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(Val when is_integer(Val), zlib:getBufSize(Z1)),\n ?m(?BARG, zlib:getBufSize(gurka)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test setBufsz.\napi_setBufsz(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(?BARG, zlib:setBufSize(Z1, gurka)),\n ?m(?BARG, zlib:setBufSize(gurka, 1232330)),\n Sz = ?m( Val when is_integer(Val), zlib:getBufSize(Z1)),\n ?m(ok, zlib:setBufSize(Z1, Sz*2)),\n DSz = Sz*2,\n ?m(DSz, zlib:getBufSize(Z1)),\n ?m(ok, zlib:close(Z1)).\n\n%%% Debug function ??\n%% Test getQSize.\napi_getQSize(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n Q = ?m(Val when is_integer(Val), zlib:getQSize(Z1)),\n io:format(\"QSize ~p ~n\", [Q]),\n ?m(?BARG, zlib:getQSize(gurka)),\n ?m(ok, zlib:close(Z1)).\n\n%% Test crc32.\napi_crc32(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1,best_speed,deflated,-15,8,default)),\n Bin = <<1,1,1,1,1,1,1,1,1>>,\n Compressed1 = ?m(_, zlib:deflate(Z1, Bin, none)),\n Compressed2 = ?m(_, zlib:deflate(Z1, <<>>, finish)),\n Compressed = list_to_binary(Compressed1 ++ Compressed2),\n CRC1 = ?m( CRC1 when is_integer(CRC1), zlib:crc32(Z1)),\n ?m(CRC1 when is_integer(CRC1), zlib:crc32(Z1,Bin)),\n ?m(CRC1 when is_integer(CRC1), zlib:crc32(Z1,binary_to_list(Bin))),\n ?m(CRC2 when is_integer(CRC2), zlib:crc32(Z1,Compressed)),\n CRC2 = ?m(CRC2 when is_integer(CRC2), zlib:crc32(Z1,0,Compressed)),\n ?m(CRC3 when CRC2 \/= CRC3, zlib:crc32(Z1,234,Compressed)),\n ?m(?BARG, zlib:crc32(gurka)),\n ?m(?BARG, zlib:crc32(Z1, not_a_binary)),\n ?m(?BARG, zlib:crc32(gurka, <<1,1,2,4,4>>)),\n ?m(?BARG, zlib:crc32(Z1, 2298929, not_a_binary)),\n ?m(?BARG, zlib:crc32(Z1, not_an_int, <<123,123,123,35,231>>)),\n ?m(?BARG, zlib:crc32_combine(Z1, not_an_int, 123123, 123)),\n ?m(?BARG, zlib:crc32_combine(Z1, noint, 123123, 123)),\n ?m(?BARG, zlib:crc32_combine(Z1, 123123, noint, 123)),\n ?m(?BARG, zlib:crc32_combine(Z1, 123123, 123, noint)),\n ?m(ok, zlib:deflateEnd(Z1)),\n ?m(ok, zlib:close(Z1)). \n\n%% Test adler32.\napi_adler32(Config) when is_list(Config) ->\n Z1 = zlib:open(),\n ?m(ok, zlib:deflateInit(Z1,best_speed,deflated,-15,8,default)),\n Bin = <<1,1,1,1,1,1,1,1,1>>,\n Compressed1 = ?m(_, zlib:deflate(Z1, Bin, none)),\n Compressed2 = ?m(_, zlib:deflate(Z1, <<>>, finish)),\n Compressed = list_to_binary(Compressed1 ++ Compressed2),\n ?m(ADLER1 when is_integer(ADLER1), zlib:adler32(Z1,Bin)),\n ?m(ADLER1 when is_integer(ADLER1), zlib:adler32(Z1,binary_to_list(Bin))),\n ADLER2 = ?m(ADLER2 when is_integer(ADLER2), zlib:adler32(Z1,Compressed)),\n ?m(ADLER2 when is_integer(ADLER2), zlib:adler32(Z1,1,Compressed)),\n ?m(ADLER3 when ADLER2 \/= ADLER3, zlib:adler32(Z1,234,Compressed)),\n ?m(?BARG, zlib:adler32(Z1, not_a_binary)),\n ?m(?BARG, zlib:adler32(gurka, <<1,1,2,4,4>>)),\n ?m(?BARG, zlib:adler32(Z1, 2298929, not_a_binary)),\n ?m(?BARG, zlib:adler32(Z1, not_an_int, <<123,123,123,35,231>>)),\n ?m(?BARG, zlib:adler32_combine(Z1, noint, 123123, 123)),\n ?m(?BARG, zlib:adler32_combine(Z1, 123123, noint, 123)),\n ?m(?BARG, zlib:adler32_combine(Z1, 123123, 123, noint)),\n ?m(ok, zlib:deflateEnd(Z1)),\n ?m(ok, zlib:close(Z1)). \n\n%% Test compress.\napi_un_compress(Config) when is_list(Config) ->\n ?m(?BARG,zlib:compress(not_a_binary)),\n Bin = <<1,11,1,23,45>>,\n Comp = zlib:compress(Bin),\n ?m(?BARG,zlib:uncompress(not_a_binary)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<171,171,171,171,171>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<120>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<120,156>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<120,156,3>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<120,156,3,0>>)),\n ?m({'EXIT',{data_error,_}}, zlib:uncompress(<<0,156,3,0,0,0,0,1>>)),\n ?m(Bin, zlib:uncompress(binary_to_list(Comp))),\n ?m(Bin, zlib:uncompress(Comp)).\n\n%% Test zip.\napi_un_zip(Config) when is_list(Config) ->\n ?m(?BARG,zlib:zip(not_a_binary)),\n Bin = <<1,11,1,23,45>>,\n Comp = zlib:zip(Bin),\n ?m(Comp, zlib:zip(binary_to_list(Bin))),\n ?m(?BARG,zlib:unzip(not_a_binary)),\n ?m({'EXIT',{data_error,_}}, zlib:unzip(<<171,171,171,171,171>>)),\n ?m({'EXIT',{data_error,_}}, zlib:unzip(<<>>)),\n ?m(Bin, zlib:unzip(Comp)),\n ?m(Bin, zlib:unzip(binary_to_list(Comp))),\n\n %% OTP-6396\n B = <<131,104,19,100,0,13,99,95,99,105,100,95,99,115,103,115,110,95,50,97,1,107,0,4,208,161,246,29,107,0,3,237,166,224,107,0,6,66,240,153,0,2,10,1,0,8,97,116,116,97,99,104,101,100,104,2,100,0,22,117,112,100,97,116,101,95,112,100,112,95,99,111,110,116,101,120,116,95,114,101,113,107,0,114,69,3,12,1,11,97,31,113,150,64,104,132,61,64,104,12,3,197,31,113,150,64,104,132,61,64,104,12,1,11,97,31,115,150,64,104,116,73,64,104,0,0,0,0,0,0,65,149,16,61,65,149,16,61,1,241,33,4,5,0,33,4,4,10,6,10,181,4,10,6,10,181,38,15,99,111,109,109,97,110,100,1,114,45,97,112,110,45,49,3,99,111,109,5,109,110,99,57,57,6,109,99,99,50,52,48,4,103,112,114,115,8,0,104,2,104,2,100,0,8,97,99,116,105,118,97,116,101,104,23,100,0,11,112,100,112,95,99,111,110,116,1,120,116,100,0,7,112,114,105,109,97,114,121,97,1,100,0,9,117,110,100,101,102,105,110,101,100,97,1,97,4,97,4,97,7,100,0,9,117,110,100,101,102,105,110,101,100,100,0,9,117,110,100,101,102,105,110,10100,100,0,9,117,110,100,101,102,105,110,101,100,100,0,5,102,97,108,115,101,100,0,9,117,110,100,101,102,105,110,101,100,100,0,9,117,110,100,101,102,105,110,101,100,100,0,9,117,110,100,101,102,105,1,101,100,97,0,100,0,9,117,110,100,101,102,105,110,101,100,107,0,4,16,0,1,144,107,0,4,61,139,186,181,107,0,4,10,8,201,49,100,0,9,117,110,100,101,102,105,110,101,100,100,0,9,117,110,100,101,102,105,0,101,100,100,0,9,117,110,100,101,102,105,110,101,100,104,2,104,3,98,0,0,7,214,97,11,97,20,104,3,97,17,97,16,97,21,106,108,0,0,0,3,104,2,97,1,104,2,104,3,98,0,0,7,214,97,11,97,20,104,3,97,17,97,167,20,104,2,97,4,104,2,104,3,98,0,0,7,214,97,11,97,20,104,3,97,17,97,16,97,21,104,2,97,10,104,2,104,3,98,0,0,7,214,97,11,97,20,104,3,97,17,97,16,97,26,106,100,0,5,118,101,114,57,57,100,0,9,117,110,0,101,102,105,110,101,100,107,0,2,0,244,107,0,4,10,6,102,195,107,0,4,10,6,102,195,100,0,9,117,110,100,101,102,105,110,101,100,100,0,9,117,110,100,101,102,105,110,101,100,107,0,125,248,143,0,203,25115,157,116,65,185,65,172,55,87,164,88,225,50,203,251,115,157,116,65,185,65,172,55,87,164,88,225,50,0,0,82,153,50,0,200,98,87,148,237,193,185,65,149,167,69,144,14,16,153,50,3,81,70,94,13,109,193,1,120,5,181,113,198,118,50,3,81,70,94,13,109,193,185,120,5,181,113,198,118,153,3,81,70,94,13,109,193,185,120,5,181,113,198,118,153,50,16,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,113,92,2,119,128,0,0,108,0,0,1,107,0,114,69,3,12,1,11,97,31,113,150,64,104,132,61,64,104,12,3,11,97,31,113,150,64,104,132,61,64,104,12,1,11,97,31,115,150,64,104,116,73,64,104,0,0,0,0,0,0,65,149,16,61,65,149,16,61,1,241,33,4,0,33,4,4,10,6,10,181,4,10,6,10,181,38,15,99,111,109,109,97,110,100,101,114,45,97,112,110,45,49,3,99,111,109,5,109,110,99,57,57,6,109,99,99,50,52,48,4,103,112,114,115,8,0,106>>,\n Z = zlib:zip(B),\n ?m(B, zlib:unzip(Z)).\n\n%% Test gunzip.\napi_g_un_zip(Config) when is_list(Config) ->\n ?m(?BARG,zlib:gzip(not_a_binary)),\n Bin = <<1,11,1,23,45>>,\n Comp = zlib:gzip(Bin),\n ?m(Comp, zlib:gzip(binary_to_list(Bin))),\n ?m(?BARG, zlib:gunzip(not_a_binary)),\n ?m(?DATA_ERROR, zlib:gunzip(<<171,171,171,171,171>>)),\n ?m(?DATA_ERROR, zlib:gunzip(<<>>)),\n ?m(Bin, zlib:gunzip(Comp)),\n ?m(Bin, zlib:gunzip(binary_to_list(Comp))),\n\n %% Bad CRC; bad length.\n BadCrc = bad_crc_data(),\n ?m({'EXIT',{data_error,_}},(catch zlib:gunzip(BadCrc))),\n BadLen = bad_len_data(),\n ?m({'EXIT',{data_error,_}},(catch zlib:gunzip(BadLen))),\n ok.\n\nbad_crc_data() ->\n %% zlib:zip(<<42>>), one byte changed.\n <<31,139,8,0,0,0,0,0,0,3,211,2,0,91,39,185,9,1,0,0,0>>.\n\nbad_len_data() ->\n %% zlib:zip(<<42>>), one byte changed.\n <<31,139,8,0,0,0,0,0,0,3,211,2,0,91,38,185,9,2,0,0,0>>.\n\n\nintro(Config) when is_list(Config) ->\n D = <<\"This is a binary\">>,\n [put({ex, N}, <<\"This is a binary\">>) || N <- [0,1,2,3,4]],\n put({ex, 5}, end_of_data),\n put(ex,0),\n Read = fun() ->\n\t\t N = get(ex),\n\t\t put(ex,N+1),\n\t\t get({ex,N})\n\t end,\n\n Z = zlib:open(),\n ok = zlib:deflateInit(Z,default),\n\n Compress = fun(end_of_data, _Cont) -> [];\n\t\t (Data, Cont) ->\n\t\t [zlib:deflate(Z, Data)|Cont(Read(),Cont)]\n\t end,\n Compressed = Compress(Read(),Compress),\n Last = zlib:deflate(Z, [], finish),\n ok = zlib:deflateEnd(Z),\n zlib:close(Z),\n Res = list_to_binary([Compressed|Last]),\n Orig = list_to_binary(lists:duplicate(5, D)),\n ?m(Orig, zlib:uncompress(Res)).\n\n\n%% Test deflate large file, which had a bug reported on erlang-bugs.\nlarge_deflate(Config) when is_list(Config) ->\n large_deflate_do().\nlarge_deflate_do() ->\n Z = zlib:open(),\n Plain = rand_bytes(zlib:getBufSize(Z)*5),\n ok = zlib:deflateInit(Z),\n _ZlibHeader = zlib:deflate(Z, [], full),\n Deflated = zlib:deflate(Z, Plain, full),\n ?m(ok, zlib:close(Z)),\n ?m(Plain, zlib:unzip(list_to_binary([Deflated, 3, 0]))).\n\nrand_bytes(Sz) ->\n L = <<8,2,3,6,1,2,3,2,3,4,8,7,3,7,2,3,4,7,5,8,9,3>>,\n rand_bytes(erlang:md5(L),Sz).\n\nrand_bytes(Bin, Sz) when byte_size(Bin) >= Sz ->\n <> = Bin,\n Res;\nrand_bytes(Bin, Sz) ->\n rand_bytes(<<(erlang:md5(Bin))\/binary, Bin\/binary>>, Sz).\n\n\n%% Test a standard compressed zip file.\nzip_usage(Config) when is_list(Config) ->\n zip_usage(zip_usage({get_arg,Config}));\nzip_usage({get_arg,Config}) ->\n Out = conf(data_dir,Config),\n {ok,ZIP} = file:read_file(filename:join(Out,\"zipdoc.zip\")),\n {ok,ORIG} = file:read_file(filename:join(Out,\"zipdoc\")),\n {run,ZIP,ORIG};\nzip_usage({run,ZIP,ORIG}) -> \n <<_:14\/binary, CRC:32\/little,\n CompSz:32\/little, UnCompSz:32\/little,_:31\/binary,\n Compressed:CompSz\/binary, _\/binary>> = ZIP,\n\n %%io:format(\"CRC ~p CSz ~p UnCSz ~p ~n\", [CRC,CompSz,UnCompSz]),\n Split = split_bin(Compressed,[]),\n Z = zlib:open(),\n\n ?m(ok, zlib:inflateInit(Z, -15)),\n Bs = [zlib:inflate(Z, Part) || Part <- Split],\n UC0 = list_to_binary(Bs),\n ?m(UnCompSz, byte_size(UC0)),\n ?m(CRC, zlib:crc32(Z)),\n ?m(true, zlib:crc32(Z,UC0) == zlib:crc32(Z,ORIG)),\n ?m(ok, zlib:inflateEnd(Z)),\n\n UC1 = zlib:unzip(Compressed),\n ?m(UnCompSz, byte_size(UC1)),\n ?m(true, zlib:crc32(Z,UC1) == zlib:crc32(Z,ORIG)),\n\n ?m(ok, zlib:inflateInit(Z, -15)),\n UC2 = zlib:inflate(Z, Compressed),\n ?m(UnCompSz, byte_size(list_to_binary(UC2))),\n ?m(CRC, zlib:crc32(Z)),\n ?m(true, zlib:crc32(Z,UC2) == zlib:crc32(Z,ORIG)),\n ?m(ok, zlib:inflateEnd(Z)),\n\n ?m(ok, zlib:inflateInit(Z, -15)),\n UC3 = zlib:inflate(Z, Split), % Test multivec.\n ?m(UnCompSz, byte_size(list_to_binary(UC3))),\n ?m(true, zlib:crc32(Z,UC3) == zlib:crc32(Z,ORIG)),\n ?m(CRC, zlib:crc32(Z)),\n ?m(ok, zlib:inflateEnd(Z)),\n\n ?m(ok, zlib:inflateInit(Z, -15)),\n ?m(ok, zlib:setBufSize(Z, UnCompSz *2)),\n UC4 = zlib:inflate(Z, Compressed),\n ?m(UnCompSz, byte_size(list_to_binary(UC4))),\n ?m(CRC, zlib:crc32(Z)),\n ?m(CRC, zlib:crc32(Z,UC4)),\n ?m(true, zlib:crc32(Z,UC4) == zlib:crc32(Z,ORIG)),\n ?m(ok, zlib:inflateEnd(Z)),\n\n C1 = zlib:zip(ORIG),\n UC5 = zlib:unzip(C1),\n ?m(CRC, zlib:crc32(Z,UC5)),\n ?m(true,zlib:crc32(Z,UC5) == zlib:crc32(Z,ORIG)),\n\n ?m(ok, zlib:deflateInit(Z, default, deflated, -15, 8, default)),\n C2 = zlib:deflate(Z, ORIG, finish),\n ?m(true, C1 == list_to_binary(C2)),\n ?m(ok, zlib:deflateEnd(Z)),\n\n ?m(ok, zlib:deflateInit(Z, none, deflated, -15, 8, filtered)),\n ?m(ok, zlib:deflateParams(Z, default, default)),\n C3 = zlib:deflate(Z, ORIG, finish),\n ?m(true, C1 == list_to_binary(C3)),\n ?m(ok, zlib:deflateEnd(Z)),\n\n ok = zlib:close(Z),\n ok.\n\n%% Test a standard compressed gzipped file.\ngz_usage(Config) when is_list(Config) ->\n gz_usage(gz_usage({get_arg,Config}));\ngz_usage({get_arg,Config}) ->\n Out = conf(data_dir,Config),\n {ok,GZIP} = file:read_file(filename:join(Out,\"zipdoc.1.gz\")),\n {ok,ORIG} = file:read_file(filename:join(Out,\"zipdoc\")),\n {ok,GZIP2} = file:read_file(filename:join(Out,\"zipdoc.txt.gz\")),\n {run,GZIP,ORIG,GZIP2}; \ngz_usage({run,GZIP,ORIG,GZIP2}) ->\n Z = zlib:open(),\n UC1 = zlib:gunzip(GZIP),\n ?m(true,zlib:crc32(Z,UC1) == zlib:crc32(Z,ORIG)),\n UC3 = zlib:gunzip(GZIP2),\n ?m(true,zlib:crc32(Z,UC3) == zlib:crc32(Z,ORIG)),\n Compressed = zlib:gzip(ORIG),\n UC5 = zlib:gunzip(Compressed),\n ?m(true,zlib:crc32(Z,UC5) == zlib:crc32(Z,ORIG)),\n ok = zlib:close(Z).\n\n%% Test more of a standard compressed gzipped file.\ngz_usage2(Config) ->\n case os:find_executable(\"gzip\") of\n\tName when is_list(Name) ->\n\t Z = zlib:open(),\n\t Out = conf(data_dir,Config),\n\t {ok,ORIG} = file:read_file(filename:join(Out,\"zipdoc\")),\n\t Compressed = zlib:gzip(ORIG),\n\t GzOutFile = filename:join(Out,\"out.gz\"),\n\t OutFile = filename:join(Out,\"out.txt\"),\n\t ?m(ok, file:write_file(GzOutFile,Compressed)),\n\t os:cmd(\"gzip -c -d \" ++ GzOutFile ++ \" > \" ++ OutFile),\n\t case file:read_file(OutFile) of\n\t\t{ok,ExtDecompressed} ->\n\t\t ?m(true, \n\t\t zlib:crc32(Z,ExtDecompressed) == zlib:crc32(Z,ORIG));\n\t\tError ->\n\t\t io:format(\"Couldn't test external decompressor ~p\\n\", \n\t\t\t [Error])\n\t end,\n\t ok = zlib:close(Z),\n\t ok;\n\tfalse ->\n\t {skipped,\"No gzip in path\"}\n end.\n\n\n\n%% Test that (de)compress funcs work with standard tools, for example\n%% a chunk from a png file.\ncompress_usage(Config) when is_list(Config) ->\n compress_usage(compress_usage({get_arg,Config}));\ncompress_usage({get_arg,Config}) ->\n Out = conf(data_dir,Config),\n {ok,C1} = file:read_file(filename:join(Out,\"png-compressed.zlib\")),\n {run,C1};\ncompress_usage({run,C1}) ->\n Z = zlib:open(),\n %% See that we can uncompress a file generated with external prog.\n UC1 = zlib:uncompress(C1),\n %% Check that the crc are correct.\n ?m(4125865008,zlib:crc32(Z,UC1)),\n C2 = zlib:compress(UC1),\n UC2 = zlib:uncompress(C2),\n %% Check that the crc are correct.\n ?m(4125865008,zlib:crc32(Z,UC2)),\n\n ok = zlib:close(Z),\n\n D = [<<\"We tests some partial\">>,\n\t <<\"data, sent over\">>,\n\t <<\"the stream\">>,\n\t <<\"we check that we can unpack\">>,\n\t <<\"every message we get\">>],\n\n ZC = zlib:open(),\n ZU = zlib:open(),\n Test = fun(finish, {_,Tot}) ->\n\t\t Compressed = zlib:deflate(ZC, <<>>, finish),\n\t\t Data = zlib:inflate(ZU, Compressed),\n\t\t [Tot|Data];\n\t (Data, {Op,Tot}) ->\n\t\t Compressed = zlib:deflate(ZC, Data, Op),\n\t\t Res1 = ?m([Data],zlib:inflate(ZU, Compressed)),\n\t\t {Op, [Tot|Res1]}\n\t end,\n zlib:deflateInit(ZC),\n zlib:inflateInit(ZU),\n T1 = lists:foldl(Test,{sync,[]},D++[finish]),\n ?m(true, list_to_binary(D) == list_to_binary(T1)),\n zlib:deflateEnd(ZC),\n zlib:inflateEnd(ZU),\n\n zlib:deflateInit(ZC),\n zlib:inflateInit(ZU),\n T2 = lists:foldl(Test,{full,[]},D++[finish]),\n ?m(true, list_to_binary(D) == list_to_binary(T2)),\n zlib:deflateEnd(ZC),\n zlib:inflateEnd(ZU),\n\n ok = zlib:close(ZC),\n ok = zlib:close(ZU).\n\n\n%% Check that crc works as expected.\ncrc(Config) when is_list(Config) ->\n crc(crc({get_arg,Config}));\ncrc({get_arg,Config}) ->\n Out = conf(data_dir,Config),\n {ok,C1} = file:read_file(filename:join(Out,\"zipdoc\")),\n {run,C1};\ncrc({run,C1}) ->\n Z = zlib:open(),\n Crc = zlib:crc32(Z, C1),\n Bins = split_bin(C1,[]),\n %%io:format(\"Length ~p ~p ~n\", [length(Bins), [size(Bin) || Bin <- Bins]]),\n Last = lists:last(Bins),\n SCrc = lists:foldl(fun(Bin,Crc0) -> \n\t\t\t Crc1 = zlib:crc32(Z, Crc0, Bin),\n\t\t\t ?m(false, Crc == Crc1 andalso Bin \/= Last),\n\t\t\t Crc1\n\t\t end, 0, Bins),\n ?m(Crc,SCrc),\n [First|Rest] = Bins,\n Combine = fun(Bin, CS1) ->\n\t\t CS2 = zlib:crc32(Z, Bin),\n\t\t S2 = byte_size(Bin),\n\t\t zlib:crc32_combine(Z,CS1,CS2,S2)\n\t end,\n Comb = lists:foldl(Combine, zlib:crc32(Z, First), Rest),\n ?m(Crc,Comb),\n ok = zlib:close(Z).\n\n%% Check that adler works as expected.\nadler(Config) when is_list(Config) ->\n adler(adler({get_arg,Config}));\nadler({get_arg,Config}) ->\n Out = conf(data_dir,Config),\n File1 = filename:join(Out,\"zipdoc\"),\n {ok,C1} = file:read_file(File1),\n {run,C1};\nadler({run,C1}) ->\n Z = zlib:open(),\n ?m(1, zlib:adler32(Z,<<>>)),\n Crc = zlib:adler32(Z, C1),\n Bins = split_bin(C1,[]),\n Last = lists:last(Bins),\n SCrc = lists:foldl(fun(Bin,Crc0) -> \n\t\t\t Crc1 = zlib:adler32(Z, Crc0, Bin),\n\t\t\t ?m(false, Crc == Crc1 andalso Bin \/= Last),\n\t\t\t Crc1\n\t\t end, zlib:adler32(Z,<<>>), Bins),\n ?m(Crc,SCrc),\n [First|Rest] = Bins,\n Combine = fun(Bin, CS1) ->\n\t\t CS2 = zlib:adler32(Z, Bin),\n\t\t S2 = byte_size(Bin),\n\t\t zlib:adler32_combine(Z,CS1,CS2,S2)\n\t end,\n Comb = lists:foldl(Combine, zlib:adler32(Z, First), Rest),\n ?m(Crc,Comb),\n ok = zlib:close(Z).\n\n%% Test dictionary usage.\ndictionary_usage(Config) when is_list(Config) ->\n dictionary_usage(dictionary_usage({get_arg,Config}));\ndictionary_usage({get_arg,_Config}) ->\n {run}; % no args\ndictionary_usage({run}) ->\n Z1 = zlib:open(),\n Dict = <<\"Anka\">>,\n Data = <<\"Kalle Anka\">>,\n ?m(ok, zlib:deflateInit(Z1)),\n DictID = zlib:deflateSetDictionary(Z1, Dict),\n %% io:format(\"DictID = ~p\\n\", [DictID]),\n B1 = zlib:deflate(Z1, Data),\n B2 = zlib:deflate(Z1, <<>>, finish),\n ?m(ok, zlib:deflateEnd(Z1)),\n ?m(ok, zlib:close(Z1)),\n Compressed = list_to_binary([B1,B2]),\n %% io:format(\"~p\\n\", [Compressed]),\n\n %% Now uncompress.\n Z2 = zlib:open(),\n ?m(ok, zlib:inflateInit(Z2)),\n {'EXIT',{{need_dictionary,DictID},_}} = (catch zlib:inflate(Z2, Compressed)),\n ?m(ok, zlib:inflateSetDictionary(Z2, Dict)),\n ?m(ok, zlib:inflateSetDictionary(Z2, binary_to_list(Dict))),\n Uncompressed = ?m(B when is_list(B), zlib:inflate(Z2, [])),\n ?m(ok, zlib:inflateEnd(Z2)),\n ?m(ok, zlib:close(Z2)), \n ?m(Data, list_to_binary(Uncompressed)).\n\nsplit_bin(<>, Acc) ->\n split_bin(Rest, [Part|Acc]);\nsplit_bin(Last,Acc) ->\n lists:reverse([Last|Acc]).\n\n\n%% Check concurrent access to zlib driver.\nsmp(Config) ->\n case erlang:system_info(smp_support) of\n\ttrue ->\n\t NumOfProcs = lists:min([8,erlang:system_info(schedulers)]),\n\t io:format(\"smp starting ~p workers\\n\",[NumOfProcs]),\n\n\t %% Tests to run in parallel.\n\t Funcs = [zip_usage, gz_usage, compress_usage, dictionary_usage,\n\t\t crc, adler],\n\n\t %% We get all function arguments here to avoid repeated parallel\n\t %% file read access.\n\t FnAList = lists:map(fun(F) -> {F,?MODULE:F({get_arg,Config})}\n\t\t\t\tend, Funcs),\t \n\n\t Pids = [spawn_link(?MODULE, worker, [rand:uniform(9999),\n\t\t\t\t\t\t list_to_tuple(FnAList),\n\t\t\t\t\t\t self()])\n\t\t || _ <- lists:seq(1,NumOfProcs)],\n\t wait_pids(Pids);\n\n\tfalse ->\n\t {skipped,\"No smp support\"}\n end.\n\n\nworker(Seed, FnATpl, Parent) ->\n io:format(\"smp worker ~p, seed=~p~n\",[self(),Seed]),\n rand:seed(exsplus, {Seed,Seed,Seed}),\n worker_loop(100, FnATpl),\n Parent ! self().\n\nworker_loop(0, _FnATpl) ->\n large_deflate_do(), % the time consuming one as finale\n ok;\nworker_loop(N, FnATpl) ->\n {F,A} = element(rand:uniform(tuple_size(FnATpl)), FnATpl),\n ?MODULE:F(A),\n worker_loop(N-1, FnATpl).\n\nwait_pids([]) -> \n ok;\nwait_pids(Pids) ->\n receive\n\tPid ->\n\t true = lists:member(Pid,Pids),\n\t Others = lists:delete(Pid,Pids),\n\t io:format(\"wait_pid got ~p, still waiting for ~p\\n\",[Pid,Others]),\n\t wait_pids(Others)\n end.\n\n\n%% Deflate\/inflate data with size close to multiple of internal buffer size.\notp_7359(_Config) ->\n %% Find compressed size\n ZTry = zlib:open(),\n ok = zlib:deflateInit(ZTry),\n ISize = zlib:getBufSize(ZTry),\n IData = list_to_binary([Byte band 255 || Byte <- lists:seq(1,ISize)]),\n ISize = byte_size(IData),\n\n DSize = iolist_size(zlib:deflate(ZTry, IData, sync)),\n zlib:close(ZTry),\n\n io:format(\"Deflated try ~p -> ~p bytes~n\", [ISize, DSize]),\n\n %% Try deflate and inflate with different internal buffer sizes\n ISpan = 1,\n DSpan = 10, % use larger span around deflated size as it may vary depending on buf size\n\n Cases = [{DS,IS} || DMul<-[1,2],\n\t\t\tDS <- lists:seq((DSize div DMul)-DSpan,\n\t\t\t\t\t(DSize div DMul)+DSpan),\n\t\t\tIMul<-[1,2],\n\t\t\tIS <- lists:seq((ISize div IMul)-ISpan,\n\t\t\t\t\t(ISize div IMul)+ISpan)],\n\n lists:foreach(fun(Case) -> otp_7359_def_inf(IData,Case) end,\n\t\t Cases).\n\n\notp_7359_def_inf(Data,{DefSize,InfSize}) -> \n %%io:format(\"Try: DefSize=~p InfSize=~p~n\", [DefSize,InfSize]),\n ZDef = zlib:open(),\n ok = zlib:deflateInit(ZDef),\n ok = zlib:setBufSize(ZDef,DefSize),\n DefData = iolist_to_binary(zlib:deflate(ZDef, Data, sync)),\n %%io:format(\"Deflated ~p(~p) -> ~p(~p) bytes~n\", \n %% [byte_size(Data), InfSize, byte_size(DefData), DefSize]),\n ok = zlib:close(ZDef),\n\n ZInf = zlib:open(),\n ok = zlib:inflateInit(ZInf),\n ok = zlib:setBufSize(ZInf,InfSize),\n Data = iolist_to_binary(zlib:inflate(ZInf, DefData)),\n ok = zlib:close(ZInf),\n ok.\n\notp_9981(Config) when is_list(Config) ->\n Ports = lists:sort(erlang:ports()),\n Invalid = <<\"My invalid data\">>,\n catch zlib:compress(invalid),\n Ports = lists:sort(erlang:ports()),\n catch zlib:uncompress(Invalid),\n Ports = lists:sort(erlang:ports()),\n catch zlib:zip(invalid),\n Ports = lists:sort(erlang:ports()),\n catch zlib:unzip(Invalid),\n Ports = lists:sort(erlang:ports()),\n catch zlib:gzip(invalid),\n Ports = lists:sort(erlang:ports()),\n catch zlib:gunzip(Invalid),\n Ports = lists:sort(erlang:ports()),\n ok.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Helps with testing directly %%%%%%%%%%%%%\n\nconf(What,Config) ->\n try proplists:get_value(What,Config) of\n\tundefined ->\n\t \".\/zlib_SUITE_data\";\n\tDir ->\n\t Dir\n catch\n\t_:_ -> \".\/zlib_SUITE_data\"\n end.\n\nt() -> t([all]).\n\nt(What) when not is_list(What) ->\n t([What]);\nt(What) ->\n lists:foreach(fun(T) ->\n\t\t\t try ?MODULE:T([])\n\t\t\t catch _E:_R ->\n\t\t\t\t Line = get(test_server_loc),\n\t\t\t\t io:format(\"Failed ~p:~p ~p ~p ~p~n\", \n\t\t\t\t\t [T,Line,_E,_R, erlang:get_stacktrace()])\n\t\t\t end\n\t\t end, expand(What)).\n\nexpand(All) ->\n lists:reverse(expand(All,[])).\nexpand([H|T], Acc) -> \n case ?MODULE:H(suite) of\n\t[] -> expand(T,[H|Acc]);\n\tCs -> \n\t R = expand(Cs, Acc),\n\t expand(T, R)\n end;\nexpand([], Acc) -> Acc.\n\n","avg_line_length":35.8439363817,"max_line_length":2678,"alphanum_fraction":0.6127457778} +{"size":2189,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%--------------------------------------------------------------------\n%% Copyright (c) 2021 EMQ Technologies Co., Ltd. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%--------------------------------------------------------------------\n\n-module(emqx_plugin_libs_pool).\n\n-export([ start_pool\/3\n , stop_pool\/1\n , pool_name\/1\n , health_check\/3\n ]).\n\npool_name(ID) when is_binary(ID) ->\n list_to_atom(binary_to_list(ID)).\n\nstart_pool(Name, Mod, Options) ->\n case ecpool:start_sup_pool(Name, Mod, Options) of\n {ok, _} -> logger:log(info, \"Initiated ~0p Successfully\", [Name]);\n {error, {already_started, _Pid}} ->\n stop_pool(Name),\n start_pool(Name, Mod, Options);\n {error, Reason} ->\n logger:log(error, \"Initiate ~0p failed ~0p\", [Name, Reason]),\n error({start_pool_failed, Name})\n end.\n\nstop_pool(Name) ->\n case ecpool:stop_sup_pool(Name) of\n ok -> logger:log(info, \"Destroyed ~0p Successfully\", [Name]);\n {error, not_found} -> ok;\n {error, Reason} ->\n logger:log(error, \"Destroy ~0p failed, ~0p\", [Name, Reason]),\n error({stop_pool_failed, Name})\n end.\n\nhealth_check(PoolName, CheckFunc, State) when is_function(CheckFunc) ->\n Status = [begin\n case ecpool_worker:client(Worker) of\n {ok, Conn} -> CheckFunc(Conn);\n _ -> false\n end\n end || {_WorkerName, Worker} <- ecpool:workers(PoolName)],\n case length(Status) > 0 andalso lists:all(fun(St) -> St =:= true end, Status) of\n true -> {ok, State};\n false -> {error, test_query_failed, State}\n end.\n","avg_line_length":37.1016949153,"max_line_length":84,"alphanum_fraction":0.5925079945} +{"size":23828,"ext":"erl","lang":"Erlang","max_stars_count":21.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 1996-2016. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n-module(edlin).\n\n%% A simple Emacs-like line editor.\n%% About Latin-1 characters: see the beginning of erl_scan.erl.\n\n-export([init\/0,init\/1,start\/1,start\/2,edit_line\/2,prefix_arg\/1]).\n-export([erase_line\/1,erase_inp\/1,redraw_line\/1]).\n-export([length_before\/1,length_after\/1,prompt\/1]).\n-export([current_line\/1, current_chars\/1]).\n%%-export([expand\/1]).\n\n-export([edit_line1\/2]).\n\n-import(lists, [reverse\/1, reverse\/2]).\n\n-export([over_word\/3]).\n\n\n%% A Continuation has the structure:\n%%\t{line,Prompt,CurrentLine,EditPrefix}\n\n%% init()\n%% Initialise the line editor. This must be done once per process using\n%% the editor.\n\ninit() ->\n put(kill_buffer, []).\n\ninit(Pid) ->\n %% copy the kill_buffer from the process Pid\n CopiedKillBuf =\n\tcase erlang:process_info(Pid, dictionary) of\n\t {dictionary,Dict} ->\n\t\tcase proplists:get_value(kill_buffer, Dict) of\n\t\t undefined -> [];\n\t\t Buf -> Buf\n\t\tend;\n\t undefined ->\n\t\t[]\n\tend,\n put(kill_buffer, CopiedKillBuf).\n\n%% start(Prompt)\n%% edit(Characters, Continuation)\n%% Return\n%%\t{done,Line,Rest,Requests}\n%%\t{more_chars,Cont,Requests}\n%%\t{blink,Cont,Requests}\n%%\t{undefined,Char,Rest,Cont,Requests}\n\nstart(Pbs) ->\n start(Pbs, none).\n\n%% Only two modes used: 'none' and 'search'. Other modes can be\n%% handled inline through specific character handling.\nstart(Pbs, Mode) ->\n {more_chars,{line,Pbs,{[],[]},Mode},[{put_chars,unicode,Pbs}]}.\n\nedit_line(Cs, {line,P,L,{blink,N}}) ->\n edit(Cs, P, L, none, [{move_rel,N}]);\nedit_line(Cs, {line,P,L,M}) ->\n edit(Cs, P, L, M, []).\n\nedit_line1(Cs, {line,P,L,{blink,N}}) ->\n edit(Cs, P, L, none, [{move_rel,N}]);\nedit_line1(Cs, {line,P,{[],[]},none}) ->\n {more_chars, {line,P,{lists:reverse(Cs),[]},none},[{put_chars, unicode, Cs}]};\nedit_line1(Cs, {line,P,L,M}) ->\n edit(Cs, P, L, M, []).\n\nedit([C|Cs], P, Line, {blink,_}, [_|Rs]) ->\t%Remove blink here\n edit([C|Cs], P, Line, none, Rs);\nedit([C|Cs], P, {Bef,Aft}, Prefix, Rs0) ->\n case key_map(C, Prefix) of\n\tmeta ->\n\t edit(Cs, P, {Bef,Aft}, meta, Rs0);\n meta_o ->\n edit(Cs, P, {Bef,Aft}, meta_o, Rs0);\n meta_csi ->\n edit(Cs, P, {Bef,Aft}, meta_csi, Rs0);\n meta_meta ->\n edit(Cs, P, {Bef,Aft}, meta_meta, Rs0);\n {csi, _} = Csi ->\n edit(Cs, P, {Bef,Aft}, Csi, Rs0);\n\tmeta_left_sq_bracket ->\n\t edit(Cs, P, {Bef,Aft}, meta_left_sq_bracket, Rs0);\n\tsearch_meta ->\n\t edit(Cs, P, {Bef,Aft}, search_meta, Rs0);\n\tsearch_meta_left_sq_bracket ->\n\t edit(Cs, P, {Bef,Aft}, search_meta_left_sq_bracket, Rs0);\n\tctlx ->\n\t edit(Cs, P, {Bef,Aft}, ctlx, Rs0);\n\tnew_line ->\n\t {done, reverse(Bef, Aft ++ \"\\n\"), Cs,\n\t reverse(Rs0, [{move_rel,length(Aft)},{put_chars,unicode,\"\\n\"}])};\n\tredraw_line ->\n\t Rs1 = erase(P, Bef, Aft, Rs0),\n\t Rs = redraw(P, Bef, Aft, Rs1),\n\t edit(Cs, P, {Bef,Aft}, none, Rs);\n\ttab_expand ->\n\t {expand, Bef, Cs,\n\t {line, P, {Bef, Aft}, none},\n\t reverse(Rs0)};\n\n%% \ttab ->\n%% \t %% Always redraw the line since expand\/1 might have printed\n%% \t %% possible expansions.\n%% \t case expand(Bef) of\n%% \t\t{yes,Str} ->\n%% \t\t edit([redraw_line|\n%% \t\t\t (Str ++ Cs)], P, {Bef,Aft}, none, Rs0);\n%% \t\tno ->\n%% \t\t %% don't beep if there's only whitespace before\n%% \t\t %% us - user may have pasted in a lot of indented stuff.\n%% \t\t case whitespace_only(Bef) of\n%% \t\t\tfalse ->\n%% \t\t\t edit([redraw_line|Cs], P, {Bef,Aft}, none,\n%% \t\t\t\t [beep|Rs0]);\n%% \t\t\ttrue ->\n%% \t\t\t edit([redraw_line|Cs], P, {Bef,Aft}, none, [Rs0])\n%% \t\t end\n%% \t end;\n\t{undefined,C} ->\n\t {undefined,{none,Prefix,C},Cs,{line,P,{Bef,Aft},none},\n\t reverse(Rs0)};\n\tOp ->\n\t case do_op(Op, Bef, Aft, Rs0) of\n\t\t{blink,N,Line,Rs} ->\n\t\t edit(Cs, P, Line, {blink,N}, Rs);\n\t\t{Line, Rs, Mode} -> % allow custom modes from do_op\n\t\t edit(Cs, P, Line, Mode, Rs);\n\t\t{Line,Rs} ->\n\t\t edit(Cs, P, Line, none, Rs)\n\t end\n end;\nedit([], P, L, {blink,N}, Rs) ->\n {blink,{line,P,L,{blink,N}},reverse(Rs)};\nedit([], P, L, Prefix, Rs) ->\n {more_chars,{line,P,L,Prefix},reverse(Rs)};\nedit(eof, _, {Bef,Aft}, _, Rs) ->\n {done,reverse(Bef, Aft),[],reverse(Rs, [{move_rel,length(Aft)}])}.\n\n%% %% Assumes that arg is a string\n%% %% Horizontal whitespace only.\n%% whitespace_only([]) ->\n%% true;\n%% whitespace_only([C|Rest]) ->\n%% case C of\n%% \t$\\s ->\n%% \t whitespace_only(Rest);\n%% \t$\\t ->\n%% \t whitespace_only(Rest);\n%% \t_ ->\n%% \t false\n%% end.\n\n%% prefix_arg(Argument)\n%% Take a prefix argument and return its numeric value.\n\nprefix_arg(none) -> 1;\nprefix_arg({ctlu,N}) -> N;\nprefix_arg(N) -> N.\n\n%% key_map(Char, Prefix)\n%% Map a character and a prefix to an action.\n\nkey_map(A, _) when is_atom(A) -> A;\t\t% so we can push keywords\nkey_map($\\^A, none) -> beginning_of_line;\nkey_map($\\^B, none) -> backward_char;\nkey_map($\\^D, none) -> forward_delete_char;\nkey_map($\\^E, none) -> end_of_line;\nkey_map($\\^F, none) -> forward_char;\nkey_map($\\^H, none) -> backward_delete_char;\nkey_map($\\t, none) -> tab_expand;\nkey_map($\\^L, none) -> redraw_line;\nkey_map($\\n, none) -> new_line;\nkey_map($\\^K, none) -> kill_line;\nkey_map($\\r, none) -> new_line;\nkey_map($\\^T, none) -> transpose_char;\nkey_map($\\^U, none) -> ctlu;\nkey_map($\\^], none) -> auto_blink;\nkey_map($\\^X, none) -> ctlx;\nkey_map($\\^Y, none) -> yank;\nkey_map($\\^W, none) -> backward_kill_word;\nkey_map($\\e, none) -> meta;\nkey_map($), Prefix) when Prefix =\/= meta,\n Prefix =\/= search,\n Prefix =\/= search_meta -> {blink,$),$(};\nkey_map($}, Prefix) when Prefix =\/= meta,\n Prefix =\/= search,\n Prefix =\/= search_meta -> {blink,$},${};\nkey_map($], Prefix) when Prefix =\/= meta,\n Prefix =\/= search,\n Prefix =\/= search_meta -> {blink,$],$[};\nkey_map($B, meta) -> backward_word;\nkey_map($D, meta) -> kill_word;\nkey_map($F, meta) -> forward_word;\nkey_map($T, meta) -> transpose_word;\nkey_map($Y, meta) -> yank_pop;\nkey_map($b, meta) -> backward_word;\nkey_map($d, meta) -> kill_word;\nkey_map($f, meta) -> forward_word;\nkey_map($t, meta) -> transpose_word;\nkey_map($y, meta) -> yank_pop;\nkey_map($O, meta) -> meta_o;\nkey_map($H, meta_o) -> beginning_of_line;\nkey_map($F, meta_o) -> end_of_line;\nkey_map($\\177, none) -> backward_delete_char;\nkey_map($\\177, meta) -> backward_kill_word;\nkey_map($[, meta) -> meta_left_sq_bracket;\nkey_map($H, meta_left_sq_bracket) -> beginning_of_line;\nkey_map($F, meta_left_sq_bracket) -> end_of_line;\nkey_map($D, meta_left_sq_bracket) -> backward_char;\nkey_map($C, meta_left_sq_bracket) -> forward_char;\n% support a few + combinations...\n% - forward: \\e\\e[C, \\e[5C, \\e[1;5C\n% - backward: \\e\\e[D, \\e[5D, \\e[1;5D\nkey_map($\\e, meta) -> meta_meta;\nkey_map($[, meta_meta) -> meta_csi;\nkey_map($C, meta_csi) -> forward_word;\nkey_map($D, meta_csi) -> backward_word;\nkey_map($1, meta_left_sq_bracket) -> {csi, \"1\"};\nkey_map($3, meta_left_sq_bracket) -> {csi, \"3\"};\nkey_map($5, meta_left_sq_bracket) -> {csi, \"5\"};\nkey_map($5, {csi, \"1;\"}) -> {csi, \"1;5\"};\nkey_map($~, {csi, \"3\"}) -> forward_delete_char;\nkey_map($C, {csi, \"5\"}) -> forward_word;\nkey_map($C, {csi, \"1;5\"}) -> forward_word;\nkey_map($D, {csi, \"5\"}) -> backward_word;\nkey_map($D, {csi, \"1;5\"}) -> backward_word;\nkey_map($;, {csi, \"1\"}) -> {csi, \"1;\"};\nkey_map(C, none) when C >= $\\s ->\n {insert,C};\n%% for search, we need smarter line handling and so\n%% we cheat a bit on the dispatching, and allow to\n%% return a mode.\nkey_map($\\^H, search) -> {search, backward_delete_char};\nkey_map($\\177, search) -> {search, backward_delete_char};\nkey_map($\\^R, search) -> {search, skip_up};\nkey_map($\\^S, search) -> {search, skip_down};\nkey_map($\\n, search) -> {search, search_found};\nkey_map($\\r, search) -> {search, search_found};\nkey_map($\\^A, search) -> {search, search_quit};\nkey_map($\\^B, search) -> {search, search_quit};\nkey_map($\\^D, search) -> {search, search_quit};\nkey_map($\\^E, search) -> {search, search_quit};\nkey_map($\\^F, search) -> {search, search_quit};\nkey_map($\\t, search) -> {search, search_quit};\nkey_map($\\^L, search) -> {search, search_quit};\nkey_map($\\^T, search) -> {search, search_quit};\nkey_map($\\^U, search) -> {search, search_quit};\nkey_map($\\^], search) -> {search, search_quit};\nkey_map($\\^X, search) -> {search, search_quit};\nkey_map($\\^Y, search) -> {search, search_quit};\nkey_map($\\e, search) -> search_meta;\nkey_map($[, search_meta) -> search_meta_left_sq_bracket;\nkey_map(_, search_meta) -> {search, search_quit};\nkey_map(_C, search_meta_left_sq_bracket) -> {search, search_quit};\nkey_map(C, search) -> {insert_search,C};\nkey_map(C, _) -> {undefined,C}.\n\n%% do_op(Action, Before, After, Requests)\n\ndo_op({insert,C}, Bef, [], Rs) ->\n {{[C|Bef],[]},[{put_chars, unicode,[C]}|Rs]};\ndo_op({insert,C}, Bef, Aft, Rs) ->\n {{[C|Bef],Aft},[{insert_chars, unicode, [C]}|Rs]};\n%% Search mode prompt always looks like (search)`$TERMS': $RESULT.\n%% the {insert_search, _} handlings allow to share this implementation\n%% correctly with group.erl. This module provides $TERMS, and group.erl\n%% is in charge of providing $RESULT.\n%% This require a bit of trickery. Because search disables moving around\n%% on the line (left\/right arrow keys and other shortcuts that just exit\n%% search mode), we can use the Bef and Aft variables to hold each\n%% part of the line. Bef takes charge of \"(search)`$TERMS\" and Aft\n%% takes charge of \"': $RESULT\".\ndo_op({insert_search, C}, Bef, [], Rs) ->\n Aft=\"': \",\n {{[C|Bef],Aft},\n [{insert_chars, unicode, [C]++Aft}, {delete_chars,-3} | Rs],\n search};\ndo_op({insert_search, C}, Bef, Aft, Rs) ->\n Offset= length(Aft),\n NAft = \"': \",\n {{[C|Bef],NAft},\n [{insert_chars, unicode, [C]++NAft}, {delete_chars,-Offset} | Rs],\n search};\ndo_op({search, backward_delete_char}, [_|Bef], Aft, Rs) ->\n Offset= length(Aft)+1,\n NAft = \"': \",\n {{Bef,NAft},\n [{insert_chars, unicode, NAft}, {delete_chars,-Offset}|Rs],\n search};\ndo_op({search, backward_delete_char}, [], _Aft, Rs) ->\n Aft=\"': \",\n {{[],Aft}, Rs, search};\ndo_op({search, skip_up}, Bef, Aft, Rs) ->\n Offset= length(Aft),\n NAft = \"': \",\n {{[$\\^R|Bef],NAft}, % we insert ^R as a flag to whoever called us\n [{insert_chars, unicode, NAft}, {delete_chars,-Offset}|Rs],\n search};\ndo_op({search, skip_down}, Bef, Aft, Rs) ->\n Offset= length(Aft),\n NAft = \"': \",\n {{[$\\^S|Bef],NAft}, % we insert ^S as a flag to whoever called us\n [{insert_chars, unicode, NAft}, {delete_chars,-Offset}|Rs],\n search};\ndo_op({search, search_found}, _Bef, Aft, Rs) ->\n \"': \"++NAft = Aft,\n {{[],NAft},\n [{put_chars, unicode, \"\\n\"}, {move_rel,-length(Aft)} | Rs],\n search_found};\ndo_op({search, search_quit}, _Bef, Aft, Rs) ->\n \"': \"++NAft = Aft,\n {{[],NAft},\n [{put_chars, unicode, \"\\n\"}, {move_rel,-length(Aft)} | Rs],\n search_quit};\n%% do blink after $$\ndo_op({blink,C,M}, Bef=[$$,$$|_], Aft, Rs) ->\n N = over_paren(Bef, C, M),\n {blink,N+1,{[C|Bef],Aft},[{move_rel,-(N+1)},{insert_chars, unicode,[C]}|Rs]};\n%% don't blink after a $\ndo_op({blink,C,_}, Bef=[$$|_], Aft, Rs) ->\n do_op({insert,C}, Bef, Aft, Rs);\n%do_op({blink,C,M}, Bef, [], Rs) ->\n% N = over_paren(Bef, C, M),\n% {blink,N+1,{[C|Bef],[]},[{move_rel,-(N+1)},{put_chars,[C]}|Rs]};\ndo_op({blink,C,M}, Bef, Aft, Rs) ->\n case over_paren(Bef, C, M) of\n\tbeep ->\n\t {{[C|Bef], Aft}, [beep,{insert_chars, unicode, [C]}|Rs]};\n\tN -> {blink,N+1,{[C|Bef],Aft},\n\t [{move_rel,-(N+1)},{insert_chars, unicode,[C]}|Rs]}\n end;\ndo_op(auto_blink, Bef, Aft, Rs) ->\n case over_paren_auto(Bef) of\n\t{N, Paren} ->\n\t {blink,N+1,\n\t {[Paren|Bef], Aft},[{move_rel,-(N+1)},{insert_chars, unicode,[Paren]}|Rs]};\n\t% N is likely 0\n\tN -> {blink,N+1,{Bef,Aft},\n\t [{move_rel,-(N+1)}|Rs]}\n end;\ndo_op(forward_delete_char, Bef, [_|Aft], Rs) ->\n {{Bef,Aft},[{delete_chars,1}|Rs]};\ndo_op(backward_delete_char, [_|Bef], Aft, Rs) ->\n {{Bef,Aft},[{delete_chars,-1}|Rs]};\ndo_op(transpose_char, [C1,C2|Bef], [], Rs) ->\n {{[C2,C1|Bef],[]},[{put_chars, unicode,[C1,C2]},{move_rel,-2}|Rs]};\ndo_op(transpose_char, [C2|Bef], [C1|Aft], Rs) ->\n {{[C2,C1|Bef],Aft},[{put_chars, unicode,[C1,C2]},{move_rel,-1}|Rs]};\ndo_op(kill_word, Bef, Aft0, Rs) ->\n {Aft1,Kill0,N0} = over_non_word(Aft0, [], 0),\n {Aft,Kill,N} = over_word(Aft1, Kill0, N0),\n put(kill_buffer, reverse(Kill)),\n {{Bef,Aft},[{delete_chars,N}|Rs]};\ndo_op(backward_kill_word, Bef0, Aft, Rs) ->\n {Bef1,Kill0,N0} = over_non_word(Bef0, [], 0),\n {Bef,Kill,N} = over_word(Bef1, Kill0, N0),\n put(kill_buffer, Kill),\n {{Bef,Aft},[{delete_chars,-N}|Rs]};\ndo_op(kill_line, Bef, Aft, Rs) ->\n put(kill_buffer, Aft),\n {{Bef,[]},[{delete_chars,length(Aft)}|Rs]};\ndo_op(yank, Bef, [], Rs) ->\n Kill = get(kill_buffer),\n {{reverse(Kill, Bef),[]},[{put_chars, unicode,Kill}|Rs]};\ndo_op(yank, Bef, Aft, Rs) ->\n Kill = get(kill_buffer),\n {{reverse(Kill, Bef),Aft},[{insert_chars, unicode,Kill}|Rs]};\ndo_op(forward_char, Bef, [C|Aft], Rs) ->\n {{[C|Bef],Aft},[{move_rel,1}|Rs]};\ndo_op(backward_char, [C|Bef], Aft, Rs) ->\n {{Bef,[C|Aft]},[{move_rel,-1}|Rs]};\ndo_op(forward_word, Bef0, Aft0, Rs) ->\n {Aft1,Bef1,N0} = over_non_word(Aft0, Bef0, 0),\n {Aft,Bef,N} = over_word(Aft1, Bef1, N0),\n {{Bef,Aft},[{move_rel,N}|Rs]};\ndo_op(backward_word, Bef0, Aft0, Rs) ->\n {Bef1,Aft1,N0} = over_non_word(Bef0, Aft0, 0),\n {Bef,Aft,N} = over_word(Bef1, Aft1, N0),\n {{Bef,Aft},[{move_rel,-N}|Rs]};\ndo_op(beginning_of_line, [C|Bef], Aft, Rs) ->\n {{[],reverse(Bef, [C|Aft])},[{move_rel,-(length(Bef)+1)}|Rs]};\ndo_op(beginning_of_line, [], Aft, Rs) ->\n {{[],Aft},Rs};\ndo_op(end_of_line, Bef, [C|Aft], Rs) ->\n {{reverse(Aft, [C|Bef]),[]},[{move_rel,length(Aft)+1}|Rs]};\ndo_op(end_of_line, Bef, [], Rs) ->\n {{Bef,[]},Rs};\ndo_op(ctlu, Bef, Aft, Rs) ->\n put(kill_buffer, reverse(Bef)),\n {{[], Aft}, [{delete_chars, -length(Bef)} | Rs]};\ndo_op(beep, Bef, Aft, Rs) ->\n {{Bef,Aft},[beep|Rs]};\ndo_op(_, Bef, Aft, Rs) ->\n {{Bef,Aft},[beep|Rs]}.\n\n%% over_word(Chars, InitialStack, InitialCount) ->\n%%\t{RemainingChars,CharStack,Count}\n%% over_non_word(Chars, InitialStack, InitialCount) ->\n%%\t{RemainingChars,CharStack,Count}\n%% Step over word\/non-word characters pushing the stepped over ones on\n%% the stack.\n\n\nover_word(Cs, Stack, N) ->\n L = length([1 || $\\' <- Cs]),\n case L rem 2 of\n\t0 ->\n\t over_word1(Cs, Stack, N);\n\t1 ->\n\t until_quote(Cs, Stack, N)\n end.\n\nuntil_quote([$\\'|Cs], Stack, N) ->\n {Cs, [$\\'|Stack], N+1};\nuntil_quote([C|Cs], Stack, N) ->\n until_quote(Cs, [C|Stack], N+1).\n\nover_word1([$\\'=C|Cs], Stack, N) ->\n until_quote(Cs, [C|Stack], N+1);\nover_word1(Cs, Stack, N) ->\n over_word2(Cs, Stack, N).\n\nover_word2([C|Cs], Stack, N) ->\n case word_char(C) of\n\ttrue -> over_word2(Cs, [C|Stack], N+1);\n\tfalse -> {[C|Cs],Stack,N}\n end;\nover_word2([], Stack, N) when is_integer(N) ->\n {[],Stack,N}.\n\nover_non_word([C|Cs], Stack, N) ->\n case word_char(C) of\n\ttrue -> {[C|Cs],Stack,N};\n\tfalse -> over_non_word(Cs, [C|Stack], N+1)\n end;\nover_non_word([], Stack, N) ->\n {[],Stack,N}.\n\nword_char(C) when C >= $A, C =< $Z -> true;\nword_char(C) when C >= $\u00c0, C =< $\u00de, C =\/= $\u00d7 -> true;\nword_char(C) when C >= $a, C =< $z -> true;\nword_char(C) when C >= $\u00df, C =< $\u00ff, C =\/= $\u00f7 -> true;\nword_char(C) when C >= $0, C =< $9 -> true;\nword_char(C) when C =:= $_ -> true;\nword_char(_) -> false.\n\n%% over_white(Chars, InitialStack, InitialCount) ->\n%%\t{RemainingChars,CharStack,Count}\n\n%% over_white([$\\s|Cs], Stack, N) ->\n%% over_white(Cs, [$\\s|Stack], N+1);\n%% over_white([$\\t|Cs], Stack, N) ->\n%% over_white(Cs, [$\\t|Stack], N+1);\n%% over_white(Cs, Stack, N) ->\n%% {Cs,Stack,N}.\n\n%% over_paren(Chars, Paren, Match)\n%% over_paren(Chars, Paren, Match, Depth, N)\n%% Step over parentheses until matching Paren is found at depth 0. Don't\n%% do proper parentheses matching check. Paren has NOT been added.\n\nover_paren(Chars, Paren, Match) ->\n over_paren(Chars, Paren, Match, 1, 1, []).\n\n\nover_paren([C,$$,$$|Cs], Paren, Match, D, N, L) ->\n over_paren([C|Cs], Paren, Match, D, N+2, L);\nover_paren([_,$$|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D, N+2, L);\nover_paren([Match|_], _Paren, Match, 1, N, _) ->\n N;\nover_paren([Match|Cs], Paren, Match, D, N, [Match|L]) ->\n over_paren(Cs, Paren, Match, D-1, N+1, L);\nover_paren([Paren|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D+1, N+1, [Match|L]);\n\nover_paren([$)|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D, N+1, [$(|L]);\nover_paren([$]|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D, N+1, [$[|L]);\nover_paren([$}|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D, N+1, [${|L]);\n\nover_paren([$(|Cs], Paren, Match, D, N, [$(|L]) ->\n over_paren(Cs, Paren, Match, D, N+1, L);\nover_paren([$[|Cs], Paren, Match, D, N, [$[|L]) ->\n over_paren(Cs, Paren, Match, D, N+1, L);\nover_paren([${|Cs], Paren, Match, D, N, [${|L]) ->\n over_paren(Cs, Paren, Match, D, N+1, L);\n\nover_paren([$(|_], _, _, _, _, _) ->\n beep;\nover_paren([$[|_], _, _, _, _, _) ->\n beep;\nover_paren([${|_], _, _, _, _, _) ->\n beep;\n\nover_paren([_|Cs], Paren, Match, D, N, L) ->\n over_paren(Cs, Paren, Match, D, N+1, L);\nover_paren([], _, _, _, _, _) ->\n 0.\n\nover_paren_auto(Chars) ->\n over_paren_auto(Chars, 1, 1, []).\n\n\nover_paren_auto([C,$$,$$|Cs], D, N, L) ->\n over_paren_auto([C|Cs], D, N+2, L);\nover_paren_auto([_,$$|Cs], D, N, L) ->\n over_paren_auto(Cs, D, N+2, L);\n\nover_paren_auto([$(|_], _, N, []) ->\n {N, $)};\nover_paren_auto([$[|_], _, N, []) ->\n {N, $]};\nover_paren_auto([${|_], _, N, []) ->\n {N, $}};\n\nover_paren_auto([$)|Cs], D, N, L) ->\n over_paren_auto(Cs, D, N+1, [$(|L]);\nover_paren_auto([$]|Cs], D, N, L) ->\n over_paren_auto(Cs, D, N+1, [$[|L]);\nover_paren_auto([$}|Cs], D, N, L) ->\n over_paren_auto(Cs, D, N+1, [${|L]);\n\nover_paren_auto([$(|Cs], D, N, [$(|L]) ->\n over_paren_auto(Cs, D, N+1, L);\nover_paren_auto([$[|Cs], D, N, [$[|L]) ->\n over_paren_auto(Cs, D, N+1, L);\nover_paren_auto([${|Cs], D, N, [${|L]) ->\n over_paren_auto(Cs, D, N+1, L);\n\nover_paren_auto([_|Cs], D, N, L) ->\n over_paren_auto(Cs, D, N+1, L);\nover_paren_auto([], _, _, _) ->\n 0.\n\n%% erase_line(Line)\n%% erase_inp(Line)\n%% redraw_line(Line)\n%% length_before(Line)\n%% length_after(Line)\n%% prompt(Line)\n%% current_line(Line)\n%% Various functions for accessing bits of a line.\n\nerase_line({line,Pbs,{Bef,Aft},_}) ->\n reverse(erase(Pbs, Bef, Aft, [])).\n\nerase_inp({line,_,{Bef,Aft},_}) ->\n reverse(erase([], Bef, Aft, [])).\n\nerase(Pbs, Bef, Aft, Rs) ->\n [{delete_chars,-length(Pbs)-length(Bef)},{delete_chars,length(Aft)}|Rs].\n\nredraw_line({line,Pbs,{Bef,Aft},_}) ->\n reverse(redraw(Pbs, Bef, Aft, [])).\n\nredraw(Pbs, Bef, Aft, Rs) ->\n [{move_rel,-length(Aft)},{put_chars, unicode,reverse(Bef, Aft)},{put_chars, unicode,Pbs}|Rs].\n\nlength_before({line,Pbs,{Bef,_Aft},_}) ->\n length(Pbs) + length(Bef).\n\nlength_after({line,_,{_Bef,Aft},_}) ->\n length(Aft).\n\nprompt({line,Pbs,_,_}) ->\n Pbs.\n\ncurrent_line({line,_,{Bef, Aft},_}) ->\n reverse(Bef, Aft ++ \"\\n\").\n\ncurrent_chars({line,_,{Bef,Aft},_}) ->\n reverse(Bef, Aft).\n\n%% %% expand(CurrentBefore) ->\n%% %%\t{yes,Expansion} | no\n%% %% Try to expand the word before as either a module name or a function\n%% %% name. We can handle white space around the seperating ':' but the\n%% %% function name must be on the same line. CurrentBefore is reversed\n%% %% and over_word\/3 reverses the characters it finds. In certain cases\n%% %% possible expansions are printed.\n\n%% expand(Bef0) ->\n%% {Bef1,Word,_} = over_word(Bef0, [], 0),\n%% case over_white(Bef1, [], 0) of\n%% \t{[$:|Bef2],_White,_Nwh} ->\n%% \t {Bef3,_White1,_Nwh1} = over_white(Bef2, [], 0),\n%% \t {_,Mod,_Nm} = over_word(Bef3, [], 0),\n%% \t expand_function_name(Mod, Word);\n%% \t{_,_,_} ->\n%% \t expand_module_name(Word)\n%% end.\n\n%% expand_module_name(Prefix) ->\n%% match(Prefix, code:all_loaded(), \":\").\n\n%% expand_function_name(ModStr, FuncPrefix) ->\n%% Mod = list_to_atom(ModStr),\n%% case erlang:module_loaded(Mod) of\n%% \ttrue ->\n%% \t L = apply(Mod, module_info, []),\n%% \t case lists:keyfind(exports, 1, L) of\n%% \t\t{_, Exports} ->\n%% \t\t match(FuncPrefix, Exports, \"(\");\n%% \t\t_ ->\n%% \t\t no\n%% \t end;\n%% \tfalse ->\n%% \t no\n%% end.\n\n%% match(Prefix, Alts, Extra) ->\n%% Matches = match1(Prefix, Alts),\n%% case longest_common_head([N || {N,_} <- Matches]) of\n%% \t{partial, []} ->\n%% \t print_matches(Matches),\n%% \t no;\n%% \t{partial, Str} ->\n%% \t case lists:nthtail(length(Prefix), Str) of\n%% \t\t[] ->\n%% \t\t print_matches(Matches),\n%% \t\t {yes, []};\n%% \t\tRemain ->\n%% \t\t {yes, Remain}\n%% \t end;\n%% \t{complete, Str} ->\n%% \t {yes, lists:nthtail(length(Prefix), Str) ++ Extra};\n%% \tno ->\n%% \t no\n%% end.\n\n%% %% Print the list of names L in multiple columns.\n%% print_matches(L) ->\n%% io:nl(),\n%% col_print(lists:sort(L)),\n%% ok.\n\n%% col_print([]) -> ok;\n%% col_print(L) -> col_print(L, field_width(L), 0).\n\n%% col_print(X, Width, Len) when Width + Len > 79 ->\n%% io:nl(),\n%% col_print(X, Width, 0);\n%% col_print([{H0,A}|T], Width, Len) ->\n%% H = if\n%% \t %% If the second element is an integer, we assume it's an\n%% \t %% arity, and meant to be printed.\n%% \t integer(A) ->\n%% \t\tH0 ++ \"\/\" ++ integer_to_list(A);\n%% \t true ->\n%% \t\tH0\n%% \tend,\n%% io:format(\"~-*s\",[Width,H]),\n%% col_print(T, Width, Len+Width);\n%% col_print([], _, _) ->\n%% io:nl().\n\n%% field_width([{H,_}|T]) -> field_width(T, length(H)).\n\n%% field_width([{H,_}|T], W) ->\n%% case length(H) of\n%% \tL when L > W -> field_width(T, L);\n%% \t_ -> field_width(T, W)\n%% end;\n%% field_width([], W) when W < 40 ->\n%% W + 4;\n%% field_width([], _) ->\n%% 40.\n\n%% match1(Prefix, Alts) ->\n%% match1(Prefix, Alts, []).\n\n%% match1(Prefix, [{H,A}|T], L) ->\n%% case prefix(Prefix, Str = atom_to_list(H)) of\n%% \ttrue ->\n%% \t match1(Prefix, T, [{Str,A}|L]);\n%% \tfalse ->\n%% \t match1(Prefix, T, L)\n%% end;\n%% match1(_, [], L) ->\n%% L.\n\n%% longest_common_head([]) ->\n%% no;\n%% longest_common_head(LL) ->\n%% longest_common_head(LL, []).\n\n%% longest_common_head([[]|_], L) ->\n%% {partial, reverse(L)};\n%% longest_common_head(LL, L) ->\n%% case same_head(LL) of\n%% \ttrue ->\n%% \t [[H|_]|_] = LL,\n%% \t LL1 = all_tails(LL),\n%% \t case all_nil(LL1) of\n%% \t\tfalse ->\n%% \t\t longest_common_head(LL1, [H|L]);\n%% \t\ttrue ->\n%% \t\t {complete, reverse([H|L])}\n%% \t end;\n%% \tfalse ->\n%% \t {partial, reverse(L)}\n%% end.\n\n%% same_head([[H|_]|T1]) -> same_head(H, T1).\n\n%% same_head(H, [[H|_]|T]) -> same_head(H, T);\n%% same_head(_, []) -> true;\n%% same_head(_, _) -> false.\n\n%% all_tails(LL) -> all_tails(LL, []).\n\n%% all_tails([[_|T]|T1], L) -> all_tails(T1, [T|L]);\n%% all_tails([], L) -> L.\n\n%% all_nil([]) -> true;\n%% all_nil([[] | Rest]) -> all_nil(Rest);\n%% all_nil(_) -> false.\n","avg_line_length":32.0268817204,"max_line_length":97,"alphanum_fraction":0.5800738627} +{"size":24476,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%% -*-mode:erlang;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-\n%%% ex: set ft=erlang fenc=utf-8 sts=4 ts=4 sw=4 et:\n%%%\n%%% Copyright 2015 Panagiotis Papadomitsos. All Rights Reserved.\n%%% Copyright 2021 Miniclip. All Rights Reserved.\n%%%\n%%% Original concept inspired and some code copied from\n%%% https:\/\/erlangcentral.org\/wiki\/index.php?title=Building_a_Non-blocking_TCP_server_using_OTP_principles\n\n-module(gen_rpc_client).\n-author(\"Panagiotis Papadomitsos \").\n\n%%% Behaviour\n-behaviour(gen_server).\n\n%%% Include the HUT library\n-include_lib(\"hut\/include\/hut.hrl\").\n%%% Include this library's name macro\n-include(\"app.hrl\").\n%%% Include helpful guard macros\n-include(\"guards.hrl\").\n%%% Include helpful guard macros\n-include(\"types.hrl\").\n\n%%% Local state\n-record(state, {socket :: port(),\n driver :: atom(),\n driver_mod :: atom(),\n driver_closed :: atom(),\n driver_error :: atom()}).\n-elvis([{elvis_style, state_record_and_type, disable}]).\n\n%%% Supervisor functions\n-export([start_link\/1, stop\/1]).\n\n%%% Server functions\n-export([call\/3, call\/4, call\/5, call\/6, cast\/3, cast\/4, cast\/5]).\n\n-export([async_call\/3, async_call\/4, yield\/1, nb_yield\/1, nb_yield\/2]).\n\n-export([eval_everywhere\/3, eval_everywhere\/4, eval_everywhere\/5]).\n\n-export([multicall\/3, multicall\/4, multicall\/5]).\n\n-export([abcast\/2, abcast\/3, sbcast\/2, sbcast\/3]).\n\n%%% Behaviour callbacks\n-export([init\/1, handle_call\/3, handle_cast\/2,\n handle_info\/2, terminate\/2, code_change\/3]).\n\n%%% Process exports\n-export([async_call_worker\/5, cast_worker\/4]).\n\n-define(IS_TIMEOUT(A), (is_integer(A) andalso A >= 0) orelse A =:= infinity).\n\n-ignore_xref(start_link\/1).\n-ignore_xref(stop\/1).\n\n-elvis([{elvis_style, god_modules, disable}]).\n\n%%% ===================================================\n%%% Supervisor functions\n%%% ===================================================\n-spec start_link(node_or_tuple()) -> {ok, pid()} | ignore | {error, term()}.\nstart_link(NodeOrTuple) when ?is_node_or_tuple(NodeOrTuple) ->\n PidName = gen_rpc_helper:make_process_name(\"client\", NodeOrTuple),\n gen_server:start_link({local,PidName}, ?MODULE, {NodeOrTuple}, []).\n\n-spec stop(node_or_tuple()) -> ok.\nstop(NodeOrTuple) when ?is_node_or_tuple(NodeOrTuple) ->\n PidName = gen_rpc_helper:make_process_name(\"client\", NodeOrTuple),\n gen_server:stop(PidName, normal, infinity).\n\n%%% ===================================================\n%%% Server functions\n%%% ===================================================\n%% Simple server call with no args and default timeout values\n-spec call(node_or_tuple(), atom() | tuple(), atom()) -> term() | {badrpc,term()} | {badtcp,term()}.\ncall(NodeOrTuple, M, F) ->\n call(NodeOrTuple, M, F, [], undefined, undefined).\n\n%% Simple server call with args and default timeout values\n-spec call(node_or_tuple(), atom() | tuple(), atom(), list()) -> term() | {badrpc,term()} | {badtcp,term()}.\ncall(NodeOrTuple, M, F, A) ->\n call(NodeOrTuple, M, F, A, undefined, undefined).\n\n%% Simple server call with custom receive timeout value\n-spec call(node_or_tuple(), atom() | tuple(), atom(), list(), timeout() | undefined) -> term() | {badrpc,term()} | {badtcp,term()}.\ncall(NodeOrTuple, M, F, A, RecvTO) ->\n call(NodeOrTuple, M, F, A, RecvTO, undefined).\n\n%% Simple server call with custom receive and send timeout values\n%% This is the function that all of the above call\n-spec call(node_or_tuple(), atom() | tuple(), atom(), list(), timeout() | undefined, timeout() | undefined) ->\n term() | {badrpc,term()} | {badtcp,term()}.\ncall(NodeOrTuple, M, F, A, RecvTO, SendTO) when ?is_node_or_tuple(NodeOrTuple), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A),\n RecvTO =:= undefined orelse ?IS_TIMEOUT(RecvTO),\n SendTO =:= undefined orelse ?IS_TIMEOUT(SendTO) ->\n %% Create a unique name for the client because we register as such\n PidName = gen_rpc_helper:make_process_name(\"client\", NodeOrTuple),\n case erlang:whereis(PidName) of\n undefined ->\n ?log(info, \"event=client_process_not_found target=\\\"~p\\\" action=spawning_client\", [NodeOrTuple]),\n case gen_rpc_dispatcher:start_client(NodeOrTuple) of\n {ok, NewPid} ->\n %% We take care of CALL inside the gen_server\n %% This is not resilient enough if the caller's mailbox is full\n %% but it's good enough for now\n try\n gen_server:call(NewPid, {{call,M,F,A}, SendTO}, gen_rpc_helper:get_call_receive_timeout(RecvTO))\n catch\n exit:{timeout,_Reason} -> {badrpc,timeout};\n exit:OtherReason -> {badrpc, {unknown_error, OtherReason}}\n end;\n {error, Reason} ->\n Reason\n end;\n Pid ->\n ?log(debug, \"event=client_process_found pid=\\\"~p\\\" target=\\\"~p\\\"\", [Pid, NodeOrTuple]),\n try\n gen_server:call(Pid, {{call,M,F,A}, SendTO}, gen_rpc_helper:get_call_receive_timeout(RecvTO))\n catch\n exit:{timeout,_Reason} -> {badrpc,timeout};\n exit:OtherReason -> {badrpc, {unknown_error, OtherReason}}\n end\n end.\n\n%% Simple server cast with no args and default timeout values\n-spec cast(node_or_tuple(), atom() | tuple(), atom()) -> true.\ncast(NodeOrTuple, M, F) ->\n cast(NodeOrTuple, M, F, [], undefined).\n\n%% Simple server cast with args and default timeout values\n-spec cast(node_or_tuple(), atom() | tuple(), atom(), list()) -> true.\ncast(NodeOrTuple, M, F, A) ->\n cast(NodeOrTuple, M, F, A, undefined).\n\n%% Simple server cast with custom send timeout value\n%% This is the function that all of the above casts call\n-spec cast(node_or_tuple(), atom() | tuple(), atom(), list(), timeout() | undefined) -> true.\ncast(NodeOrTuple, M, F, A, SendTO) when ?is_node_or_tuple(NodeOrTuple), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A),\n SendTO =:= undefined orelse ?IS_TIMEOUT(SendTO) ->\n _WorkerPid = erlang:spawn(?MODULE, cast_worker, [NodeOrTuple, {cast,M,F,A}, undefined, SendTO]),\n true.\n\n%% Evaluate {M, F, A} on connected nodes.\n-spec eval_everywhere([node_or_tuple()], atom() | tuple(), atom()) -> abcast.\neval_everywhere(Nodes, M, F) ->\n eval_everywhere(Nodes, M, F, [], undefined).\n\n%% Evaluate {M, F, A} on connected nodes.\n-spec eval_everywhere([node_or_tuple()], atom() | tuple(), atom(), list()) -> abcast.\neval_everywhere(Nodes, M, F, A) ->\n eval_everywhere(Nodes, M, F, A, undefined).\n\n%% Evaluate {M, F, A} on connected nodes.\n-spec eval_everywhere([node_or_tuple()], atom() | tuple(), atom(), list(), timeout() | undefined) -> abcast.\neval_everywhere(Nodes, M, F, A, SendTO) when is_list(Nodes), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A),\n SendTO =:= undefined orelse ?IS_TIMEOUT(SendTO) ->\n _ = [erlang:spawn(?MODULE, cast_worker, [Node, {cast,M,F,A}, abcast, SendTO]) || Node <- Nodes],\n abcast.\n\n%% Simple server async_call with no args\n-spec async_call(node_or_tuple(), atom() | tuple(), atom()) -> {pid(), reference()}.\nasync_call(NodeOrTuple, M, F) ->\n async_call(NodeOrTuple, M, F, []).\n\n%% Simple server async_call with args\n-spec async_call(node_or_tuple(), atom() | tuple(), atom(), list()) -> {pid(), reference()}.\nasync_call(NodeOrTuple, M, F, A) when ?is_node_or_tuple(NodeOrTuple), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A) ->\n Ref = erlang:make_ref(),\n Pid = erlang:spawn(?MODULE, async_call_worker, [NodeOrTuple, M, F, A, Ref]),\n {Pid, Ref}.\n\n%% Simple server yield with key. Delegate to nb_yield. Default timeout form configuration.\n-spec yield({pid(), reference()}) -> term().\nyield(Key) ->\n {value,Result} = nb_yield(Key, infinity),\n Result.\n\n%% Simple server non-blocking yield with key, default timeout value of 0\n-spec nb_yield({pid(), reference()}) -> {value,term()} | timeout.\nnb_yield(Key)->\n nb_yield(Key, 0).\n\n%% Simple server non-blocking yield with key and custom timeout value\n-spec nb_yield({pid(), reference()}, timeout()) -> {value,term()} | timeout.\nnb_yield({Pid,Ref}, Timeout) when is_pid(Pid), is_reference(Ref), ?IS_TIMEOUT(Timeout) ->\n Pid ! {self(), Ref, yield},\n receive\n {Pid, Ref, async_call, Result} ->\n {value,Result}\n after\n Timeout ->\n ?log(debug, \"event=nb_yield_timeout async_call_pid=\\\"~p\\\" async_call_ref=\\\"~p\\\"\", [Pid, Ref]),\n timeout\n end.\n\n%% \"Concurrent\" call to a set of servers\n-spec multicall(atom() | tuple(), atom(), list()) -> {list(), list()}.\nmulticall(M, F, A) when is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A) ->\n multicall([node()|gen_rpc:nodes()], M, F, A).\n\n-spec multicall(list() | atom() | tuple(), atom() | tuple(), atom() | list(), list() | timeout()) -> {list(), list()}.\nmulticall(M, F, A, Timeout) when is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A), ?IS_TIMEOUT(Timeout) ->\n multicall([node()|gen_rpc:nodes()], M, F, A, Timeout);\n\nmulticall(Nodes, M, F, A) when is_list(Nodes), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A) ->\n Keys = [async_call(Node, M, F, A) || Node <- Nodes],\n parse_multicall_results(Keys, Nodes, undefined).\n\n-spec multicall(list(), atom() | tuple(), atom(), list(), timeout()) -> {list(), list()}.\nmulticall(Nodes, M, F, A, Timeout) when is_list(Nodes), is_atom(M) orelse is_tuple(M), is_atom(F), is_list(A), ?IS_TIMEOUT(Timeout) ->\n Keys = [async_call(Node, M, F, A) || Node <- Nodes],\n parse_multicall_results(Keys, Nodes, Timeout).\n\n-spec abcast(atom(), term()) -> abcast.\nabcast(Name, Msg) when is_atom(Name) ->\n abcast([node()|gen_rpc:nodes()], Name, Msg).\n\n-spec abcast(list(), atom(), term()) -> abcast.\nabcast(Nodes, Name, Msg) when is_list(Nodes), is_atom(Name) ->\n _ = [erlang:spawn(?MODULE, cast_worker, [Node, {abcast,Name,Msg}, abcast, undefined]) || Node <- Nodes],\n abcast.\n\n-spec sbcast(atom(), term()) -> {list(), list()}.\nsbcast(Name, Msg) when is_atom(Name) ->\n sbcast([node()|gen_rpc:nodes()], Name, Msg).\n\n-spec sbcast(list(), atom(), term()) -> {list(), list()}.\nsbcast(Nodes, Name, Msg) when is_list(Nodes), is_atom(Name) ->\n Ref = erlang:make_ref(),\n Workers = [{erlang:spawn(?MODULE, cast_worker, [Node, {sbcast, Name, Msg, {self(), Ref, Node}}, undefined, undefined]), Node} || Node <- Nodes],\n parse_sbcast_results(Workers, Ref).\n\n%%% ===================================================\n%%% Behaviour callbacks\n%%% ===================================================\n%% If we're called with a key, remove it, the key is only relevant\n%% at the process name level\ninit({{Node,_Key}}) ->\n init({Node});\n\ninit({Node}) ->\n ok = gen_rpc_helper:set_optimal_process_flags(),\n case gen_rpc_helper:get_client_config_per_node(Node) of\n {error, Reason} ->\n ?log(error, \"event=external_source_error action=falling_back_to_local reason=\\\"~p\\\"\", [Reason]),\n {stop, {badrpc, {external_source_error, Reason}}};\n {Driver, Port} ->\n {DriverMod, DriverClosed, DriverError} = gen_rpc_helper:get_client_driver_options(Driver),\n ?log(info, \"event=initializing_client driver=~s node=\\\"~s\\\" port=~B\", [Driver, Node, Port]),\n case DriverMod:connect(Node, Port) of\n {ok, Socket} ->\n case DriverMod:authenticate_server(Socket) of\n ok ->\n {ok, #state{socket=Socket,\n driver=Driver,\n driver_mod=DriverMod,\n driver_closed=DriverClosed,\n driver_error=DriverError}, gen_rpc_helper:get_inactivity_timeout(?MODULE)};\n {error, ReasonTuple} ->\n ?log(error, \"event=client_authentication_failed driver=~s reason=\\\"~p\\\"\", [Driver, ReasonTuple]),\n {stop, ReasonTuple}\n end;\n {error, {_Class,Reason}} ->\n %% This should be badtcp but to conform with\n %% the RPC library we return badrpc\n {stop, {badrpc,Reason}}\n end\n end.\n\n%% This is the actual CALL handler\nhandle_call({{call,_M,_F,_A} = PacketTuple, SendTO}, Caller, #state{socket=Socket, driver=Driver, driver_mod=DriverMod} = State) ->\n Packet = erlang:term_to_binary({PacketTuple, Caller}),\n ?log(debug, \"message=call event=constructing_call_term driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller]),\n ok = DriverMod:set_send_timeout(Socket, SendTO),\n case DriverMod:send(Socket, Packet) of\n {error, Reason} ->\n ?log(error, \"message=call event=transmission_failed driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\" reason=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller, Reason]),\n {stop, Reason, Reason, State};\n ok ->\n ?log(debug, \"message=call event=transmission_succeeded driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller]),\n %% We need to enable the socket and perform the call only if the call succeeds\n ok = DriverMod:activate_socket(Socket),\n {noreply, State, gen_rpc_helper:get_inactivity_timeout(?MODULE)}\n end;\n\n%% Catch-all for calls - die if we get a message we don't expect\nhandle_call(Msg, _Caller, #state{socket=Socket, driver=Driver} = State) ->\n ?log(error, \"event=uknown_call_received driver=~s socket=\\\"~s\\\" message=\\\"~p\\\" action=stopping\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Msg]),\n {stop, {unknown_call, Msg}, {unknown_call, Msg}, State}.\n\n%% This is the actual CAST handler for CAST\nhandle_cast({{cast,_M,_F,_A} = PacketTuple, SendTO}, State) ->\n send_cast(PacketTuple, State, SendTO, false);\n\n%% This is the actual CAST handler for ABCAST\nhandle_cast({{abcast,_Name,_Msg} = PacketTuple, undefined}, State) ->\n send_cast(PacketTuple, State, undefined, false);\n\n%% This is the actual CAST handler for SBCAST\nhandle_cast({{sbcast,_Name,_Msg,_Caller} = PacketTuple, undefined}, State) ->\n send_cast(PacketTuple, State, undefined, true);\n\n%% This is the actual ASYNC CALL handler\nhandle_cast({{async_call,_M,_F,_A} = PacketTuple, Caller, Ref}, #state{socket=Socket, driver=Driver, driver_mod=DriverMod} = State) ->\n Packet = erlang:term_to_binary({PacketTuple, {Caller,Ref}}),\n ?log(debug, \"message=async_call event=constructing_async_call_term socket=\\\"~s\\\" worker_pid=\\\"~p\\\" async_call_ref=\\\"~p\\\"\",\n [gen_rpc_helper:socket_to_string(Socket), Caller, Ref]),\n ok = DriverMod:set_send_timeout(Socket, undefined),\n case DriverMod:send(Socket, Packet) of\n {error, Reason} ->\n ?log(error, \"message=async_call event=transmission_failed driver=~s socket=\\\"~s\\\" worker_pid=\\\"~p\\\" call_ref=\\\"~p\\\" reason=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller, Ref, Reason]),\n {stop, Reason, Reason, State};\n ok ->\n ?log(debug, \"message=async_call event=transmission_succeeded driver=~s socket=\\\"~s\\\" worker_pid=\\\"~p\\\" call_ref=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller, Ref]),\n %% We need to enable the socket and perform the call only if the call succeeds\n ok = DriverMod:activate_socket(Socket),\n %% Reply will be handled from the worker\n {noreply, State, gen_rpc_helper:get_inactivity_timeout(?MODULE)}\n end;\n\n%% Catch-all for casts - die if we get a message we don't expect\nhandle_cast(Msg, #state{socket=Socket, driver=Driver} = State) ->\n ?log(error, \"event=uknown_cast_received driver=~s socket=\\\"~s\\\" message=\\\"~p\\\" action=stopping\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Msg]),\n {stop, {unknown_cast, Msg}, State}.\n\n%% Handle any TCP packet coming in\nhandle_info({Driver,Socket,Data}, #state{socket=Socket, driver=Driver, driver_mod=DriverMod} = State) ->\n _Reply = case erlang:binary_to_term(Data) of\n {call, Caller, Reply} ->\n ?log(debug, \"event=call_reply_received driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\" action=sending_reply\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller]),\n gen_server:reply(Caller, Reply);\n {async_call, {Caller, Ref}, Reply} ->\n ?log(debug, \"event=async_call_reply_received driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\" action=sending_reply\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller]),\n Caller ! {self(), Ref, async_call, Reply};\n {sbcast, {Caller, Ref, Node}, Reply} ->\n ?log(debug, \"event=sbcast_reply_received driver=~s socket=\\\"~s\\\" caller=\\\"~p\\\" reference=\\\"~p\\\" action=sending_reply\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Caller, Ref]),\n Caller ! {Ref, Node, Reply};\n OtherData ->\n ?log(error, \"event=erroneous_reply_received driver=~s socket=\\\"~s\\\" data=\\\"~p\\\" action=ignoring\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), OtherData])\n end,\n ok = DriverMod:activate_socket(Socket),\n {noreply, State, gen_rpc_helper:get_inactivity_timeout(?MODULE)};\n\nhandle_info({DriverClosed, Socket}, #state{socket=Socket, driver=Driver, driver_closed=DriverClosed} = State) ->\n ?log(error, \"message=channel_closed driver=~s socket=\\\"~s\\\" action=stopping\", [Driver, gen_rpc_helper:socket_to_string(Socket)]),\n {stop, normal, State};\n\nhandle_info({DriverError, Socket, Reason}, #state{socket=Socket, driver=Driver, driver_error=DriverError} = State) ->\n ?log(error, \"message=channel_error driver=~s socket=\\\"~s\\\" reason=\\\"~p\\\" action=stopping\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Reason]),\n {stop, normal, State};\n\n%% Handle the inactivity timeout gracefully\nhandle_info(timeout, #state{socket=Socket, driver=Driver} = State) ->\n ?log(info, \"message=timeout event=client_inactivity_timeout driver=~s socket=\\\"~s\\\" action=stopping\",\n [Driver, gen_rpc_helper:socket_to_string(Socket)]),\n {stop, normal, State};\n\n%% Catch-all for info - our protocol is strict so die!\nhandle_info(Msg, #state{socket=Socket, driver=Driver} = State) ->\n ?log(error, \"event=uknown_message_received driver=~s socket=\\\"~s\\\" message=\\\"~p\\\" action=stopping\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Msg]),\n {stop, {unknown_info, Msg}, State}.\n\n%% Stub functions\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\nterminate(_Reason, _State) ->\n ok.\n\n%%% ===================================================\n%%% Private functions\n%%% ===================================================\nsend_cast(PacketTuple, #state{socket=Socket, driver=Driver, driver_mod=DriverMod} = State, SendTO, Activate) ->\n Packet = erlang:term_to_binary(PacketTuple),\n ?log(debug, \"event=constructing_cast_term driver=~s socket=\\\"~s\\\" cast=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), PacketTuple]),\n ok = DriverMod:set_send_timeout(Socket, SendTO),\n case DriverMod:send(Socket, Packet) of\n {error, Reason} ->\n ?log(error, \"message=cast event=transmission_failed driver=~s socket=\\\"~s\\\" reason=\\\"~p\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket), Reason]),\n {stop, Reason, State};\n ok ->\n ok = case Activate of\n true -> DriverMod:activate_socket(Socket);\n _ -> ok\n end,\n ?log(debug, \"message=cast event=transmission_succeeded driver=~s socket=\\\"~s\\\"\",\n [Driver, gen_rpc_helper:socket_to_string(Socket)]),\n {noreply, State, gen_rpc_helper:get_inactivity_timeout(?MODULE)}\n end.\n\ncast_worker(NodeOrTuple, Cast, Ret, SendTO) ->\n %% Create a unique name for the client because we register as such\n PidName = gen_rpc_helper:make_process_name(\"client\", NodeOrTuple),\n case erlang:whereis(PidName) of\n undefined ->\n ?log(info, \"event=client_process_not_found target=\\\"~p\\\" action=spawning_client\", [NodeOrTuple]),\n case gen_rpc_dispatcher:start_client(NodeOrTuple) of\n {ok, NewPid} ->\n %% We take care of CALL inside the gen_server\n %% This is not resilient enough if the caller's mailbox is full\n %% but it's good enough for now\n ok = gen_server:cast(NewPid, {Cast,SendTO}),\n Ret;\n {error, _Reason} ->\n Ret\n end;\n Pid ->\n ?log(debug, \"event=client_process_found pid=\\\"~p\\\" target=\\\"~p\\\"\", [Pid, NodeOrTuple]),\n ok = gen_server:cast(Pid, {Cast,SendTO}),\n Ret\n end.\n\nasync_call_worker(NodeOrTuple, M, F, A, Ref) ->\n TTL = gen_rpc_helper:get_async_call_inactivity_timeout(),\n PidName = gen_rpc_helper:make_process_name(\"client\", NodeOrTuple),\n SrvPid = case erlang:whereis(PidName) of\n undefined ->\n ?log(info, \"event=client_process_not_found target=\\\"~p\\\" action=spawning_client\", [NodeOrTuple]),\n case gen_rpc_dispatcher:start_client(NodeOrTuple) of\n {ok, NewPid} ->\n ok = gen_server:cast(NewPid, {{async_call,M,F,A}, self(), Ref}),\n NewPid;\n {error, {badrpc,_} = RpcError} ->\n RpcError\n end;\n Pid ->\n ?log(debug, \"event=client_process_found pid=\\\"~p\\\" target=\\\"~p\\\"\", [Pid, NodeOrTuple]),\n ok = gen_server:cast(Pid, {{async_call,M,F,A}, self(), Ref}),\n Pid\n end,\n case SrvPid of\n SrvPid when is_pid(SrvPid) ->\n receive\n %% Wait for the reply from the node's gen_rpc client process\n {SrvPid,Ref,async_call,Reply} ->\n %% Wait for a yield request from the caller\n receive\n {YieldPid,Ref,yield} ->\n YieldPid ! {self(), Ref, async_call, Reply}\n after\n TTL ->\n exit({error, async_call_cleanup_timeout_reached})\n end\n after\n TTL ->\n exit({error, async_call_cleanup_timeout_reached})\n end;\n TRpcError ->\n %% Wait for a yield request from the caller\n receive\n {YieldPid,Ref,yield} ->\n YieldPid ! {self(), Ref, async_call, TRpcError}\n after\n TTL ->\n exit({error, async_call_cleanup_timeout_reached})\n end\n end.\n\nparse_multicall_results(Keys, Nodes, undefined) ->\n parse_multicall_results(Keys, Nodes, infinity);\n\nparse_multicall_results(Keys, Nodes, Timeout) ->\n AsyncResults = [nb_yield(Key, Timeout) || Key <- Keys],\n {RealResults, RealBadNodes, _} = lists:foldl(fun\n ({value, {BadReply, _Reason}}, {Results, BadNodes, [Node|RestNodes]}) when BadReply =:= badrpc; BadReply =:= badtcp ->\n {Results, [Node|BadNodes], RestNodes};\n ({value, Value}, {Results, BadNodes, [_Node|RestNodes]}) ->\n {[Value|Results], BadNodes, RestNodes};\n (timeout, {Results, BadNodes, [Node|RestNodes]}) ->\n {Results, [Node|BadNodes], RestNodes}\n end, {[], [], Nodes}, AsyncResults),\n {RealResults, RealBadNodes}.\n\nparse_sbcast_results(WorkerPids, Ref) ->\n Timeout = gen_rpc_helper:get_sbcast_receive_timeout(),\n parse_sbcast_results(WorkerPids, Ref, {[], []}, Timeout).\n\nparse_sbcast_results([{_Pid,Node}|WorkerPids], Ref, {Good, Bad}, Timeout) ->\n receive\n {Ref, Node, error} ->\n parse_sbcast_results(WorkerPids, Ref, {Good, [Node|Bad]}, Timeout);\n {Ref, Node, success} ->\n parse_sbcast_results(WorkerPids, Ref, {[Node|Good], Bad}, Timeout)\n after\n Timeout ->\n parse_sbcast_results(WorkerPids, Ref, {Good, [Node|Bad]}, Timeout)\n end;\n\nparse_sbcast_results([], _Ref, Results, _Timeout) ->\n Results.\n","avg_line_length":48.0864440079,"max_line_length":148,"alphanum_fraction":0.610598137} +{"size":4907,"ext":"erl","lang":"Erlang","max_stars_count":136.0,"content":"%%\n%% Copyright (c) 2015-2016 Christopher Meiklejohn. All Rights Reserved.\n%%\n%% This file is provided to you under the Apache License,\n%% Version 2.0 (the \"License\"); you may not use this file\n%% except in compliance with the License. You may obtain\n%% a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing,\n%% software distributed under the License is distributed on an\n%% \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n%% KIND, either express or implied. See the License for the\n%% specific language governing permissions and limitations\n%% under the License.\n%%\n%% -------------------------------------------------------------------\n\n%% @doc Pure PNCounter CRDT: pure op-based grow-only counter.\n%%\n%% @reference Carlos Baquero, Paulo S\u00e9rgio Almeida, and Ali Shoker\n%% Making Operation-based CRDTs Operation-based (2014)\n%% [http:\/\/haslab.uminho.pt\/ashoker\/files\/opbaseddais14.pdf]\n\n-module(pure_pncounter).\n-author(\"Georges Younes \").\n\n-behaviour(type).\n-behaviour(pure_type).\n\n-define(TYPE, ?MODULE).\n\n-ifdef(TEST).\n-include_lib(\"eunit\/include\/eunit.hrl\").\n-endif.\n\n-export([new\/0, new\/1]).\n-export([mutate\/3, query\/1, equal\/2, reset\/2]).\n\n-export_type([pure_pncounter\/0, pure_pncounter_op\/0]).\n\n-opaque pure_pncounter() :: {?TYPE, payload()}.\n-type payload() :: {pure_type:polog(), integer()}.\n-type pure_pncounter_op() :: increment | decrement | {increment, integer()} | {decrement, integer()}.\n\n%% @doc Create a new, empty `pure_pncounter()'\n-spec new() -> pure_pncounter().\nnew() ->\n {?TYPE, {orddict:new(), 0}}.\n\n%% @doc Create a new, empty `pure_pncounter()'\n-spec new([term()]) -> pure_pncounter().\nnew([]) ->\n new().\n\n%% @doc Update a `pure_pncounter()'.\n-spec mutate(pure_pncounter_op(), pure_type:id(), pure_pncounter()) ->\n {ok, pure_pncounter()}.\nmutate(increment, _VV, {?TYPE, {POLog, PurePNCounter}}) ->\n PurePNCounter1 = {?TYPE, {POLog, PurePNCounter + 1}},\n {ok, PurePNCounter1};\nmutate({increment, Val}, _VV, {?TYPE, {POLog, PurePNCounter}}) ->\n PurePNCounter1 = {?TYPE, {POLog, PurePNCounter + Val}},\n {ok, PurePNCounter1};\nmutate(decrement, _VV, {?TYPE, {POLog, PurePNCounter}}) ->\n PurePNCounter1 = {?TYPE, {POLog, PurePNCounter - 1}},\n {ok, PurePNCounter1};\nmutate({decrement, Val}, _VV, {?TYPE, {POLog, PurePNCounter}}) ->\n PurePNCounter1 = {?TYPE, {POLog, PurePNCounter - Val}},\n {ok, PurePNCounter1}.\n\n%% @doc Clear\/reset the state to initial state.\n-spec reset(pure_type:id(), pure_pncounter()) -> pure_pncounter().\nreset(VV, {?TYPE, _}=CRDT) ->\n pure_type:reset(VV, CRDT).\n\n%% @doc Return the value of the `pure_pncounter()'.\n-spec query(pure_pncounter()) -> integer().\nquery({?TYPE, {_POLog, PurePNCounter}}) ->\n PurePNCounter.\n\n%% @doc Check if two `pure_pncounter()' instances have the same value.\n-spec equal(pure_pncounter(), pure_pncounter()) -> boolean().\nequal({?TYPE, {_POLog1, PurePNCounter1}}, {?TYPE, {_POLog2, PurePNCounter2}}) ->\n PurePNCounter1 == PurePNCounter2.\n\n%% ===================================================================\n%% EUnit tests\n%% ===================================================================\n-ifdef(TEST).\n\nnew_test() ->\n ?assertEqual({?TYPE, {[], 0}}, new()).\n\nquery_test() ->\n PurePNCounter0 = new(),\n PurePNCounter1 = {?TYPE, {[], 15}},\n ?assertEqual(0, query(PurePNCounter0)),\n ?assertEqual(15, query(PurePNCounter1)).\n\nincrement_test() ->\n PurePNCounter0 = new(),\n {ok, PurePNCounter1} = mutate(increment, [], PurePNCounter0),\n {ok, PurePNCounter2} = mutate(increment, [], PurePNCounter1),\n {ok, PurePNCounter3} = mutate({increment, 5}, [], PurePNCounter2),\n ?assertEqual({?TYPE, {[], 1}}, PurePNCounter1),\n ?assertEqual({?TYPE, {[], 2}}, PurePNCounter2),\n ?assertEqual({?TYPE, {[], 7}}, PurePNCounter3).\n\ndecrement_test() ->\n PurePNCounter0 = {?TYPE, {[], 1}},\n {ok, PurePNCounter1} = mutate(decrement, [], PurePNCounter0),\n {ok, PurePNCounter2} = mutate(decrement, [], PurePNCounter1),\n {ok, PurePNCounter3} = mutate({decrement, 5}, [], PurePNCounter2),\n {ok, PurePNCounter4} = mutate({decrement, -8}, [], PurePNCounter3),\n ?assertEqual({?TYPE, {[], 0}}, PurePNCounter1),\n ?assertEqual({?TYPE, {[], -1}}, PurePNCounter2),\n ?assertEqual({?TYPE, {[], -6}}, PurePNCounter3),\n ?assertEqual({?TYPE, {[], 2}}, PurePNCounter4).\n\nreset_test() ->\n PurePNCounter1 = {?TYPE, {[], 54}},\n PurePNCounter2 = reset([], PurePNCounter1),\n ?assertEqual({?TYPE, {[], 0}}, PurePNCounter2).\n\nequal_test() ->\n PurePNCounter1 = {?TYPE, {[], 1}},\n PurePNCounter2 = {?TYPE, {[], 2}},\n PurePNCounter3 = {?TYPE, {[], 3}},\n ?assert(equal(PurePNCounter1, PurePNCounter1)),\n ?assertNot(equal(PurePNCounter2, PurePNCounter1)),\n ?assertNot(equal(PurePNCounter2, PurePNCounter3)).\n\n-endif.\n","avg_line_length":36.0808823529,"max_line_length":101,"alphanum_fraction":0.6315467699} +{"size":409,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"-module(bank).\n-export([start\/0, start_server\/0, stop\/0]).\n-include(\"common.hrl\").\n\nstart_server() ->\n ?CVI(\"Start App:~p end\", [cvserver]),\n net_adm:ping('cvnice@192.168.20.89'),\n application:start(cvserver).\n\n\n\nstart() ->\n ?CVI(\"Start ~p All APP!\", [?MODULE]),\n db_mysql:start().\n%% game:start().\n\n\nstop() ->\n ?CVI(\"Stop ~p All APP!\", [?MODULE]),\n db_mysql:stop().\n%% game:stop().","avg_line_length":19.4761904762,"max_line_length":43,"alphanum_fraction":0.5721271394} +{"size":25047,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2011-2014. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n\n-module(observer_lib).\n\n-export([get_wx_parent\/1,\n\t display_info_dialog\/1, display_yes_no_dialog\/1,\n\t display_progress_dialog\/2, destroy_progress_dialog\/0,\n\t wait_for_progress\/0, report_progress\/1,\n\t user_term\/3, user_term_multiline\/3,\n\t interval_dialog\/4, start_timer\/1, stop_timer\/1,\n\t display_info\/2, fill_info\/2, update_info\/2, to_str\/1,\n\t create_menus\/3, create_menu_item\/3,\n\t create_attrs\/0,\n\t set_listctrl_col_size\/2,\n\t create_status_bar\/1,\n\t html_window\/1, html_window\/2\n\t]).\n\n-include_lib(\"wx\/include\/wx.hrl\").\n-include(\"observer_defs.hrl\").\n\n-define(SINGLE_LINE_STYLE, ?wxBORDER_NONE bor ?wxTE_READONLY bor ?wxTE_RICH2).\n-define(MULTI_LINE_STYLE, ?SINGLE_LINE_STYLE bor ?wxTE_MULTILINE).\n\n\nget_wx_parent(Window) ->\n Parent = wxWindow:getParent(Window),\n case wx:is_null(Parent) of\n\ttrue -> Window;\n\tfalse -> get_wx_parent(Parent)\n end.\n\ninterval_dialog(Parent0, {Timer, Value}, Min, Max) ->\n Parent = get_wx_parent(Parent0),\n Dialog = wxDialog:new(Parent, ?wxID_ANY, \"Update Interval\",\n\t\t\t [{style, ?wxDEFAULT_DIALOG_STYLE bor\n\t\t\t\t?wxRESIZE_BORDER}]),\n Panel = wxPanel:new(Dialog),\n Check = wxCheckBox:new(Panel, ?wxID_ANY, \"Periodical refresh\"),\n wxCheckBox:setValue(Check, Timer \/= false),\n Style = ?wxSL_HORIZONTAL bor ?wxSL_AUTOTICKS bor ?wxSL_LABELS,\n Slider = wxSlider:new(Panel, ?wxID_ANY, Value, Min, Max,\n\t\t\t [{style, Style}, {size, {200, -1}}]),\n wxWindow:enable(Slider, [{enable, Timer \/= false}]),\n InnerSizer = wxBoxSizer:new(?wxVERTICAL),\n Buttons = wxDialog:createButtonSizer(Dialog, ?wxOK bor ?wxCANCEL),\n Flags = [{flag, ?wxEXPAND bor ?wxALL}, {border, 2}],\n wxSizer:add(InnerSizer, Check, Flags),\n wxSizer:add(InnerSizer, Slider, Flags),\n wxPanel:setSizer(Panel, InnerSizer),\n TopSizer = wxBoxSizer:new(?wxVERTICAL),\n wxSizer:add(TopSizer, Panel, [{flag, ?wxEXPAND bor ?wxALL}, {border, 5}]),\n wxSizer:add(TopSizer, Buttons, [{flag, ?wxEXPAND}]),\n wxWindow:setSizerAndFit(Dialog, TopSizer),\n wxSizer:setSizeHints(TopSizer, Dialog),\n wxCheckBox:connect(Check, command_checkbox_clicked,\n\t\t [{callback, fun(#wx{event=#wxCommand{commandInt=Enable0}},_) ->\n\t\t\t\t\t Enable = Enable0 > 0,\n\t\t\t\t\t wxWindow:enable(Slider, [{enable, Enable}])\n\t\t\t\t end}]),\n Res = case wxDialog:showModal(Dialog) of\n\t ?wxID_OK ->\n\t\t Enabled = wxCheckBox:isChecked(Check),\n\t\t setup_timer(Enabled, {Timer, wxSlider:getValue(Slider)});\n\t ?wxID_CANCEL ->\n\t\t {Timer, Value}\n\t end,\n wxDialog:destroy(Dialog),\n Res.\n\nstop_timer(Timer = {false, _}) -> Timer;\nstop_timer(Timer = {true, _}) -> Timer;\nstop_timer(Timer = {_, Intv}) ->\n setup_timer(false, Timer),\n {true, Intv}.\nstart_timer(Intv) when is_integer(Intv) ->\n setup_timer(true, {true, Intv});\nstart_timer(Timer) ->\n setup_timer(true, Timer).\n\nsetup_timer(false, {Timer, Value})\n when is_boolean(Timer) ->\n {false, Value};\nsetup_timer(true, {false, Value}) ->\n {ok, Timer} = timer:send_interval(Value * 1000, refresh_interval),\n {Timer, Value};\nsetup_timer(Bool, {Timer, Old}) ->\n timer:cancel(Timer),\n setup_timer(Bool, {false, Old}).\n\ndisplay_info_dialog(Str) ->\n display_info_dialog(\"\",Str).\ndisplay_info_dialog(Title,Str) ->\n Dlg = wxMessageDialog:new(wx:null(), Str, [{caption,Title}]),\n wxMessageDialog:showModal(Dlg),\n wxMessageDialog:destroy(Dlg),\n ok.\n\ndisplay_yes_no_dialog(Str) ->\n Dlg = wxMessageDialog:new(wx:null(), Str, [{style,?wxYES_NO}]),\n R = wxMessageDialog:showModal(Dlg),\n wxMessageDialog:destroy(Dlg),\n R.\n\n%% display_info(Parent, [{Title, [{Label, Info}]}]) -> {Panel, Sizer, InfoFieldsToUpdate}\ndisplay_info(Frame, Info) ->\n Panel = wxPanel:new(Frame),\n wxWindow:setBackgroundColour(Panel, {255,255,255}),\n Sizer = wxBoxSizer:new(?wxVERTICAL),\n wxSizer:addSpacer(Sizer, 5),\n Add = fun(BoxInfo) ->\n\t\t case create_box(Panel, BoxInfo) of\n\t\t {Box, InfoFs} ->\n\t\t\t wxSizer:add(Sizer, Box, [{flag, ?wxEXPAND bor ?wxALL},\n\t\t\t\t\t\t {border, 5}]),\n\t\t\t wxSizer:addSpacer(Sizer, 5),\n\t\t\t InfoFs;\n\t\t undefined ->\n\t\t\t []\n\t\t end\n\t end,\n InfoFs = [Add(I) || I <- Info],\n wxWindow:setSizerAndFit(Panel, Sizer),\n {Panel, Sizer, InfoFs}.\n\nfill_info([{dynamic, Key}|Rest], Data)\n when is_atom(Key); is_function(Key) ->\n %% Special case used by crashdump_viewer when the value decides\n %% which header to use\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\t{Str,Value} -> [{Str, Value} | fill_info(Rest, Data)]\n end;\nfill_info([{Str, Key}|Rest], Data) when is_atom(Key); is_function(Key) ->\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\tValue -> [{Str, Value} | fill_info(Rest, Data)]\n end;\nfill_info([{Str,Attrib,Key}|Rest], Data) when is_atom(Key); is_function(Key) ->\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\tValue -> [{Str,Attrib,Value} | fill_info(Rest, Data)]\n end;\nfill_info([{Str, {Format, Key}}|Rest], Data)\n when is_atom(Key); is_function(Key), is_atom(Format) ->\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\tValue -> [{Str, {Format, Value}} | fill_info(Rest, Data)]\n end;\nfill_info([{Str, Attrib, {Format, Key}}|Rest], Data)\n when is_atom(Key); is_function(Key), is_atom(Format) ->\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\tValue -> [{Str, Attrib, {Format, Value}} | fill_info(Rest, Data)]\n end;\nfill_info([{Str,SubStructure}|Rest], Data) when is_list(SubStructure) ->\n [{Str, fill_info(SubStructure, Data)}|fill_info(Rest,Data)];\nfill_info([{Str,Attrib,SubStructure}|Rest], Data) ->\n [{Str, Attrib, fill_info(SubStructure, Data)}|fill_info(Rest,Data)];\nfill_info([{Str, Key = {K,N}}|Rest], Data) when is_atom(K), is_integer(N) ->\n case get_value(Key, Data) of\n\tundefined -> [undefined | fill_info(Rest, Data)];\n\tValue -> [{Str, Value} | fill_info(Rest, Data)]\n end;\nfill_info([], _) -> [].\n\nget_value(Fun, Data) when is_function(Fun) ->\n Fun(Data);\nget_value(Key, Data) ->\n proplists:get_value(Key,Data).\n\nupdate_info([Fields|Fs], [{_Header, SubStructure}| Rest]) ->\n update_info2(Fields, SubStructure),\n update_info(Fs, Rest);\nupdate_info([Fields|Fs], [{_Header, _Attrib, SubStructure}| Rest]) ->\n update_info2(Fields, SubStructure),\n update_info(Fs, Rest);\nupdate_info([], []) ->\n ok.\n\nupdate_info2([undefined|Fs], [_|Rest]) ->\n update_info2(Fs, Rest);\nupdate_info2([Scroll = {_, _, _}|Fs], [{_, NewInfo}|Rest]) ->\n update_scroll_boxes(Scroll, NewInfo),\n update_info2(Fs, Rest);\nupdate_info2([Field|Fs], [{_Str, {click, Value}}|Rest]) ->\n wxTextCtrl:setValue(Field, to_str(Value)),\n update_info2(Fs, Rest);\nupdate_info2([Field|Fs], [{_Str, Value}|Rest]) ->\n wxTextCtrl:setValue(Field, to_str(Value)),\n update_info2(Fs, Rest);\nupdate_info2([Field|Fs], [undefined|Rest]) ->\n wxTextCtrl:setValue(Field, \"\"),\n update_info2(Fs, Rest);\nupdate_info2([], []) -> ok.\n\nupdate_scroll_boxes({_, _, 0}, {_, []}) -> ok;\nupdate_scroll_boxes({Win, Sizer, _}, {Type, List}) ->\n [wxSizerItem:deleteWindows(Child) || Child <- wxSizer:getChildren(Sizer)],\n BC = wxWindow:getBackgroundColour(Win),\n Cursor = wxCursor:new(?wxCURSOR_HAND),\n add_entries(Type, List, Win, Sizer, BC, Cursor),\n wxCursor:destroy(Cursor),\n wxSizer:recalcSizes(Sizer),\n wxWindow:refresh(Win),\n ok.\n\nto_str(Value) when is_atom(Value) ->\n atom_to_list(Value);\nto_str({Unit, X}) when (Unit==bytes orelse Unit==time_ms) andalso is_list(X) ->\n try list_to_integer(X) of\n\tB -> to_str({Unit,B})\n catch error:badarg -> X\n end;\nto_str({bytes, B}) ->\n KB = B div 1024,\n MB = KB div 1024,\n GB = MB div 1024,\n if\n\tGB > 10 -> integer_to_list(GB) ++ \" GB\";\n\tMB > 10 -> integer_to_list(MB) ++ \" MB\";\n\tKB > 0 -> integer_to_list(KB) ++ \" kB\";\n\ttrue -> integer_to_list(B) ++ \" B\"\n end;\nto_str({time_ms, MS}) ->\n S = MS div 1000,\n Min = S div 60,\n Hours = Min div 60,\n Days = Hours div 24,\n if\n\tDays > 0 -> integer_to_list(Days) ++ \" Days\";\n\tHours > 0 -> integer_to_list(Hours) ++ \" Hours\";\n\tMin > 0 -> integer_to_list(Min) ++ \" Mins\";\n\ttrue -> integer_to_list(S) ++ \" Secs\"\n end;\n\nto_str({func, {F,A}}) when is_atom(F), is_integer(A) ->\n lists:concat([F, \"\/\", A]);\nto_str({func, {F,'_'}}) when is_atom(F) ->\n atom_to_list(F);\nto_str({{format,Fun},Value}) when is_function(Fun) ->\n Fun(Value);\nto_str({A, B}) when is_atom(A), is_atom(B) ->\n lists:concat([A, \":\", B]);\nto_str({M,F,A}) when is_atom(M), is_atom(F), is_integer(A) ->\n lists:concat([M, \":\", F, \"\/\", A]);\nto_str(Value) when is_list(Value) ->\n case lists:all(fun(X) -> is_integer(X) end, Value) of\n\ttrue -> Value;\n\tfalse ->\n\t lists:foldl(fun(X, Acc) ->\n\t\t\t\tto_str(X) ++ \" \" ++ Acc end,\n\t\t\t\"\", Value)\n end;\nto_str(Port) when is_port(Port) ->\n erlang:port_to_list(Port);\nto_str(Pid) when is_pid(Pid) ->\n pid_to_list(Pid);\nto_str(No) when is_integer(No) ->\n integer_to_list(No);\nto_str(Float) when is_float(Float) ->\n io_lib:format(\"~.3f\", [Float]);\nto_str(Term) ->\n io_lib:format(\"~w\", [Term]).\n\ncreate_menus([], _MenuBar, _Type) -> ok;\ncreate_menus(Menus, MenuBar, Type) ->\n Add = fun({Tag, Ms}, Index) ->\n\t\t create_menu(Tag, Ms, Index, MenuBar, Type)\n\t end,\n [{First, _}|_] = Menus,\n Index = if Type =:= default -> 0;\n\t First =:= \"File\" -> 0;\n\t true -> 1\n\t end,\n wx:foldl(Add, Index, Menus),\n ok.\n\ncreate_menu(\"File\", MenuItems, Index, MenuBar, Type) ->\n if\n\tType =:= plugin ->\n\t MenuId = wxMenuBar:findMenu(MenuBar, \"File\"),\n\t Menu = wxMenuBar:getMenu(MenuBar, MenuId),\n\t lists:foldl(fun(Record, N) ->\n\t\t\t\tcreate_menu_item(Record, Menu, N)\n\t\t\tend, 0, MenuItems),\n\t Index + 1;\n\ttrue ->\n\t Menu = wxMenu:new(),\n\t lists:foldl(fun(Record, N) ->\n\t\t\t\tcreate_menu_item(Record, Menu, N)\n\t\t\tend, 0, MenuItems),\n\t wxMenuBar:insert(MenuBar, Index, Menu, \"File\"),\n\t Index+1\n end;\ncreate_menu(Name, MenuItems, Index, MenuBar, _Type) ->\n Menu = wxMenu:new(),\n lists:foldl(fun(Record, N) ->\n\t\t\tcreate_menu_item(Record, Menu, N)\n\t\tend, 0, MenuItems),\n wxMenuBar:insert(MenuBar, Index, Menu, Name),\n Index+1.\n\ncreate_menu_item(#create_menu{id = ?wxID_HELP=Id}, Menu, Index) ->\n wxMenu:insert(Menu, Index, Id),\n Index+1;\ncreate_menu_item(#create_menu{id=Id, text=Text, help=Help, type=Type, check=Check},\n\t\t Menu, Index) ->\n Opts = case Help of\n\t [] -> [];\n\t _ -> [{help, Help}]\n\t end,\n case Type of\n\tappend ->\n\t wxMenu:insert(Menu, Index, Id,\n\t\t\t [{text, Text}|Opts]);\n\tcheck ->\n\t wxMenu:insertCheckItem(Menu, Index, Id, Text, Opts),\n\t wxMenu:check(Menu, Id, Check);\n\tradio ->\n\t wxMenu:insertRadioItem(Menu, Index, Id, Text, Opts),\n\t wxMenu:check(Menu, Id, Check);\n\tseparator ->\n\t wxMenu:insertSeparator(Menu, Index)\n end,\n Index+1;\ncreate_menu_item(separator, Menu, Index) ->\n wxMenu:insertSeparator(Menu, Index),\n Index+1.\n\ncreate_attrs() ->\n Font = wxSystemSettings:getFont(?wxSYS_DEFAULT_GUI_FONT),\n Text = case wxSystemSettings:getColour(?wxSYS_COLOUR_LISTBOXTEXT) of\n\t {255,255,255,_} -> {10,10,10}; %% Is white on Mac for some reason\n\t Color -> Color\n\t end,\n #attrs{even = wxListItemAttr:new(Text, ?BG_EVEN, Font),\n\t odd = wxListItemAttr:new(Text, ?BG_ODD, Font),\n\t deleted = wxListItemAttr:new(?FG_DELETED, ?BG_DELETED, Font),\n\t changed_even = wxListItemAttr:new(Text, mix(?BG_CHANGED,?BG_EVEN), Font),\n\t changed_odd = wxListItemAttr:new(Text, mix(?BG_CHANGED,?BG_ODD), Font),\n\t new_even = wxListItemAttr:new(Text, mix(?BG_NEW,?BG_EVEN), Font),\n\t new_odd = wxListItemAttr:new(Text, mix(?BG_NEW, ?BG_ODD), Font),\n\t searched = wxListItemAttr:new(Text, ?BG_SEARCHED, Font)\n\t }.\n\nmix(RGB,_) -> RGB.\n\n%% mix({R,G,B},{MR,MG,MB}) ->\n%% {trunc(R*MR\/255), trunc(G*MG\/255), trunc(B*MB\/255)}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nget_box_info({Title, List}) when is_list(List) -> {Title, ?wxALIGN_LEFT, List};\nget_box_info({Title, left, List}) -> {Title, ?wxALIGN_LEFT, List};\nget_box_info({Title, right, List}) -> {Title, ?wxALIGN_RIGHT, List}.\n\nadd_box(Panel, OuterBox, Cursor, Title, Proportion, {Format, List}) ->\n Box = wxStaticBoxSizer:new(?wxVERTICAL, Panel, [{label, Title}]),\n Scroll = wxScrolledWindow:new(Panel),\n wxScrolledWindow:enableScrolling(Scroll,true,true),\n wxScrolledWindow:setScrollbars(Scroll,1,1,0,0),\n ScrollSizer = wxBoxSizer:new(?wxVERTICAL),\n wxScrolledWindow:setSizer(Scroll, ScrollSizer),\n BC = wxWindow:getBackgroundColour(Panel),\n wxWindow:setBackgroundColour(Scroll,BC),\n add_entries(Format, List, Scroll, ScrollSizer, BC, Cursor),\n wxSizer:add(Box,Scroll,[{proportion,1},{flag,?wxEXPAND}]),\n wxSizer:add(OuterBox,Box,[{proportion,Proportion},{flag,?wxEXPAND}]),\n {Scroll,ScrollSizer,length(List)}.\n\nadd_entries(click, List, Scroll, ScrollSizer, BC, Cursor) ->\n Add = fun(Link) ->\n\t\t TC = link_entry(Scroll, Link, Cursor),\n\t\t wxWindow:setBackgroundColour(TC,BC),\n\t\t wxSizer:add(ScrollSizer,TC,[{flag,?wxEXPAND}])\n\t end,\n [Add(Link) || Link <- List];\nadd_entries(plain, List, Scroll, ScrollSizer, _, _) ->\n Add = fun(String) ->\n\t\t TC = wxTextCtrl:new(Scroll, ?wxID_ANY,\n\t\t\t\t [{style,?SINGLE_LINE_STYLE},\n\t\t\t\t {value,String}]),\n\t\t wxSizer:add(ScrollSizer,TC,[{flag,?wxEXPAND}])\n\t end,\n [Add(String) || String <- List].\n\n\ncreate_box(_Panel, {scroll_boxes,[]}) ->\n undefined;\ncreate_box(Panel, {scroll_boxes,Data}) ->\n OuterBox = wxBoxSizer:new(?wxHORIZONTAL),\n Cursor = wxCursor:new(?wxCURSOR_HAND),\n AddBox = fun({Title,Proportion,Format = {_,_}}) ->\n\t\t add_box(Panel, OuterBox, Cursor, Title, Proportion, Format);\n\t\t({Title, Format = {_,_}}) ->\n\t\t add_box(Panel, OuterBox, Cursor, Title, 1, Format);\n\t\t(undefined) ->\n\t\t undefined\n\t end,\n Boxes = [AddBox(Entry) || Entry <- Data],\n wxCursor:destroy(Cursor),\n\n MaxL = lists:foldl(fun({_,_,L},Max) when L>Max -> L;\n\t\t\t (_,Max) -> Max\n\t\t end,\n\t\t 0,\n\t\t Boxes),\n\n Dummy = wxTextCtrl:new(Panel, ?wxID_ANY, [{style, ?SINGLE_LINE_STYLE}]),\n {_,H} = wxWindow:getSize(Dummy),\n wxTextCtrl:destroy(Dummy),\n\n MaxH = if MaxL > 8 -> 8*H;\n\t true -> MaxL*H\n\t end,\n [wxWindow:setMinSize(B,{0,MaxH}) || {B,_,_} <- Boxes],\n wxSizer:layout(OuterBox),\n {OuterBox, Boxes};\n\ncreate_box(Panel, Data) ->\n {Title, Align, Info} = get_box_info(Data),\n Box = wxStaticBoxSizer:new(?wxVERTICAL, Panel, [{label, Title}]),\n LeftSize = get_max_size(Panel,Info),\n LeftProportion = [{proportion,0}],\n RightProportion = [{proportion,1}, {flag, Align bor ?wxEXPAND}],\n AddRow = fun({Desc0, Value0}) ->\n\t\t Desc = Desc0++\":\",\n\t\t Line = wxBoxSizer:new(?wxHORIZONTAL),\n\t\t wxSizer:add(Line,\n\t\t\t\t wxTextCtrl:new(Panel, ?wxID_ANY,\n\t\t\t\t\t\t[{style,?SINGLE_LINE_STYLE},\n\t\t\t\t\t\t {size,LeftSize},\n\t\t\t\t\t\t {value,Desc}]),\n\t\t\t\t LeftProportion),\n\t\t Field =\n\t\t\t case Value0 of\n\t\t\t {click,\"unknown\"} ->\n\t\t\t\t wxTextCtrl:new(Panel, ?wxID_ANY,\n\t\t\t\t\t\t[{style,?SINGLE_LINE_STYLE},\n\t\t\t\t\t\t {value,\"unknown\"}]);\n\t\t\t {click,Value} ->\n\t\t\t\t link_entry(Panel,Value);\n\t\t\t _ ->\n\t\t\t\t Value = to_str(Value0),\n\t\t\t\t TCtrl = wxTextCtrl:new(Panel, ?wxID_ANY,\n\t\t\t\t\t\t\t[{style,?SINGLE_LINE_STYLE},\n\t\t\t\t\t\t\t {value,Value}]),\n\t\t\t\t length(Value) > 50 andalso\n\t\t\t\t wxWindow:setToolTip(TCtrl,wxToolTip:new(Value)),\n\t\t\t\t TCtrl\n\t\t\t end,\n\t\t wxSizer:add(Line, 10, 0), % space of size 10 horisontally\n\t\t wxSizer:add(Line, Field, RightProportion),\n\n\t\t {_,H,_,_} = wxTextCtrl:getTextExtent(Field,\"Wj\"),\n\t\t wxTextCtrl:setMinSize(Field,{0,H}),\n\n\t\t wxSizer:add(Box, Line, [{proportion,0},{flag,?wxEXPAND}]),\n\t\t Field;\n\t\t(undefined) ->\n\t\t undefined\n\t end,\n InfoFields = [AddRow(Entry) || Entry <- Info],\n {Box, InfoFields}.\n\nlink_entry(Panel, Link) ->\n Cursor = wxCursor:new(?wxCURSOR_HAND),\n TC = link_entry2(Panel, to_link(Link), Cursor),\n wxCursor:destroy(Cursor),\n TC.\nlink_entry(Panel, Link, Cursor) ->\n link_entry2(Panel, to_link(Link), Cursor).\n\nlink_entry2(Panel,{Target,Str},Cursor) ->\n TC = wxTextCtrl:new(Panel, ?wxID_ANY, [{style, ?SINGLE_LINE_STYLE}]),\n wxTextCtrl:setForegroundColour(TC,?wxBLUE),\n wxTextCtrl:appendText(TC, Str),\n wxWindow:setCursor(TC, Cursor),\n wxTextCtrl:connect(TC, left_down, [{userData,Target}]),\n wxTextCtrl:connect(TC, enter_window),\n wxTextCtrl:connect(TC, leave_window),\n ToolTip = wxToolTip:new(\"Click to see properties for \" ++ Str),\n wxWindow:setToolTip(TC, ToolTip),\n TC.\n\nto_link(RegName={Name, Node}) when is_atom(Name), is_atom(Node) ->\n Str = io_lib:format(\"{~p,~p}\", [Name, Node]),\n {RegName, Str};\nto_link(TI = {_Target, _Identifier}) ->\n TI;\nto_link(Target0) ->\n Target=to_str(Target0),\n {Target, Target}.\n\nhtml_window(Panel) ->\n Win = wxHtmlWindow:new(Panel, [{style, ?wxHW_SCROLLBAR_AUTO}]),\n %% wxHtmlWindow:setFonts(Win, \"\", FixedName),\n wxHtmlWindow:connect(Win,command_html_link_clicked),\n Win.\n\nhtml_window(Panel, Html) ->\n Win = html_window(Panel),\n wxHtmlWindow:setPage(Win, Html),\n Win.\n\nget_max_size(Panel,Info) ->\n Txt = wxTextCtrl:new(Panel, ?wxID_ANY, []),\n Size = get_max_size(Txt,Info,0,0),\n wxTextCtrl:destroy(Txt),\n Size.\n\nget_max_size(Txt,[{Desc,_}|Info],MaxX,MaxY) ->\n {X,Y,_,_} = wxTextCtrl:getTextExtent(Txt,Desc++\":\"),\n if X>MaxX ->\n\t get_max_size(Txt,Info,X,Y);\n true ->\n\t get_max_size(Txt,Info,MaxX,MaxY)\n end;\nget_max_size(Txt,[undefined|Info],MaxX,MaxY) ->\n get_max_size(Txt,Info,MaxX,MaxY);\nget_max_size(_,[],X,_Y) ->\n {X+2,-1}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nset_listctrl_col_size(LCtrl, Total) ->\n wx:batch(fun() -> calc_last(LCtrl, Total) end).\n\ncalc_last(LCtrl, _Total) ->\n Cols = wxListCtrl:getColumnCount(LCtrl),\n {Total, _} = wxWindow:getClientSize(LCtrl),\n SBSize = scroll_size(LCtrl),\n Last = lists:foldl(fun(I, Last) ->\n\t\t\t Last - wxListCtrl:getColumnWidth(LCtrl, I)\n\t\t end, Total-SBSize, lists:seq(0, Cols - 2)),\n Size = max(150, Last),\n wxListCtrl:setColumnWidth(LCtrl, Cols-1, Size).\n\nscroll_size(LCtrl) ->\n case os:type() of\n\t{win32, nt} -> 0;\n\t{unix, darwin} -> 0; %% Always 0 in wxWidgets-3.0\n\t_ ->\n\t case wxWindow:hasScrollbar(LCtrl, ?wxVERTICAL) of\n\t\ttrue -> wxSystemSettings:getMetric(?wxSYS_VSCROLL_X);\n\t\tfalse -> 0\n\t end\n end.\n\n\nuser_term(Parent, Title, Default) ->\n Dialog = wxTextEntryDialog:new(Parent, Title, [{value, Default}]),\n case wxTextEntryDialog:showModal(Dialog) of\n\t?wxID_OK ->\n\t Str = wxTextEntryDialog:getValue(Dialog),\n\t wxTextEntryDialog:destroy(Dialog),\n\t parse_string(ensure_last_is_dot(Str));\n\t?wxID_CANCEL ->\n\t wxTextEntryDialog:destroy(Dialog),\n\t cancel\n end.\n\nuser_term_multiline(Parent, Title, Default) ->\n Dialog = wxDialog:new(Parent, ?wxID_ANY, Title,\n\t\t\t [{style, ?wxDEFAULT_DIALOG_STYLE bor\n\t\t\t ?wxRESIZE_BORDER}]),\n Panel = wxPanel:new(Dialog),\n\n TextCtrl = wxTextCtrl:new(Panel, ?wxID_ANY,\n\t\t\t [{value, Default},\n\t\t\t {style, ?wxDEFAULT bor ?wxTE_MULTILINE}]),\n Line = wxStaticLine:new(Panel, [{style, ?wxLI_HORIZONTAL}]),\n\n Buttons = wxDialog:createButtonSizer(Dialog, ?wxOK bor ?wxCANCEL),\n\n InnerSizer = wxBoxSizer:new(?wxVERTICAL),\n wxSizer:add(InnerSizer, TextCtrl,\n\t\t[{flag, ?wxEXPAND bor ?wxALL},{proportion, 1},{border, 5}]),\n wxSizer:add(InnerSizer, Line,\n\t\t[{flag, ?wxEXPAND},{proportion, 0},{border, 5}]),\n wxPanel:setSizer(Panel, InnerSizer),\n\n TopSizer = wxBoxSizer:new(?wxVERTICAL),\n wxSizer:add(TopSizer, Panel,\n\t\t[{flag, ?wxEXPAND bor ?wxALL},{proportion, 1},{border, 5}]),\n wxSizer:add(TopSizer, Buttons,\n\t\t[{flag, ?wxEXPAND bor ?wxBOTTOM bor ?wxRIGHT},{border, 10}]),\n\n % calculate the size of TopSizer when the whole user_term\n % fits in the TextCtrl\n DC = wxClientDC:new(Panel),\n W = wxDC:getCharWidth(DC),\n H = wxDC:getCharHeight(DC),\n {EW, EH} = wxDC:getMultiLineTextExtent(DC, Default),\n wxSizer:setItemMinSize(InnerSizer, 0, EW+2*W, EH+H),\n TopSize = wxSizer:getMinSize(TopSizer),\n % reset min size of TextCtrl to 40 chararacters * 4 lines\n wxSizer:setItemMinSize(InnerSizer, 0, 40*W, 4*H),\n\n wxWindow:setSizerAndFit(Dialog, TopSizer),\n wxSizer:setSizeHints(TopSizer, Dialog),\n\n wxWindow:setClientSize(Dialog, TopSize),\n\n case wxDialog:showModal(Dialog) of\n\t?wxID_OK ->\n\t Str = wxTextCtrl:getValue(TextCtrl),\n\t wxDialog:destroy(Dialog),\n\t parse_string(ensure_last_is_dot(Str));\n\t?wxID_CANCEL ->\n\t wxDialog:destroy(Dialog),\n\t cancel\n end.\n\nparse_string(Str) ->\n try\n\tTokens = case erl_scan:string(Str) of\n\t\t {ok, Ts, _} -> Ts;\n\t\t {error, {_SLine, SMod, SError}, _} ->\n\t\t\t throw(io_lib:format(\"~s\", [SMod:format_error(SError)]))\n\t\t end,\n\tcase erl_parse:parse_term(Tokens) of\n\t {error, {_PLine, PMod, PError}} ->\n\t\tthrow(io_lib:format(\"~s\", [PMod:format_error(PError)]));\n\t Res -> Res\n\tend\n catch\n\tthrow:ErrStr ->\n\t {error, ErrStr};\n\t_:_Err ->\n\t {error, [\"Syntax error in: \", Str]}\n end.\n\nensure_last_is_dot([]) ->\n \".\";\nensure_last_is_dot(String) ->\n case lists:last(String) =:= $. of\n\ttrue ->\n\t String;\n\tfalse ->\n\t String ++ \".\"\n end.\n\n%%%-----------------------------------------------------------------\n%%% Status bar for warnings\ncreate_status_bar(Panel) ->\n StatusStyle = ?wxTE_MULTILINE bor ?wxTE_READONLY bor ?wxTE_RICH2,\n Red = wxTextAttr:new(?wxRED),\n\n %% wxTextCtrl:setSize\/3 does not work, so we must create a dummy\n %% text ctrl first to get the size of the text, then set it when\n %% creating the real text ctrl.\n Dummy = wxTextCtrl:new(Panel, ?wxID_ANY,[{style,StatusStyle}]),\n {X,Y,_,_} = wxTextCtrl:getTextExtent(Dummy,\"WARNING\"),\n wxTextCtrl:destroy(Dummy),\n StatusBar = wxTextCtrl:new(Panel, ?wxID_ANY,\n\t\t\t [{style,StatusStyle},\n\t\t\t {size,{X,Y+2}}]), % Y+2 to avoid scrollbar\n wxTextCtrl:setDefaultStyle(StatusBar,Red),\n wxTextAttr:destroy(Red),\n StatusBar.\n\n%%%-----------------------------------------------------------------\n%%% Progress dialog\n-define(progress_handler,cdv_progress_handler).\ndisplay_progress_dialog(Title,Str) ->\n Caller = self(),\n Env = wx:get_env(),\n spawn_link(fun() ->\n\t\t progress_handler(Caller,Env,Title,Str)\n\t end),\n ok.\n\nwait_for_progress() ->\n receive\n\tcontinue ->\n\t ok;\n\tError ->\n\t Error\n end.\n\ndestroy_progress_dialog() ->\n report_progress(finish).\n\nreport_progress(Progress) ->\n case whereis(?progress_handler) of\n\tPid when is_pid(Pid) ->\n\t Pid ! {progress,Progress},\n\t ok;\n\t_ ->\n\t ok\n end.\n\nprogress_handler(Caller,Env,Title,Str) ->\n register(?progress_handler,self()),\n wx:set_env(Env),\n PD = progress_dialog(Env,Title,Str),\n try progress_loop(Title,PD,Caller)\n catch closed -> normal end.\n\nprogress_loop(Title,PD,Caller) ->\n receive\n\t{progress,{ok,done}} -> % to make wait_for_progress\/0 return\n\t Caller ! continue,\n\t progress_loop(Title,PD,Caller);\n\t{progress,{ok,Percent}} when is_integer(Percent) ->\n\t update_progress(PD,Percent),\n\t progress_loop(Title,PD,Caller);\n\t{progress,{ok,Msg}} ->\n\t update_progress_text(PD,Msg),\n\t progress_loop(Title,PD,Caller);\n\t{progress,{error, Reason}} ->\n\t finish_progress(PD),\n\t FailMsg =\n\t\tif is_list(Reason) -> Reason;\n\t\t true -> file:format_error(Reason)\n\t\tend,\n\t display_info_dialog(\"Crashdump Viewer Error\",FailMsg),\n\t Caller ! error,\n\t unregister(?progress_handler),\n\t unlink(Caller);\n\t{progress,finish} ->\n\t finish_progress(PD),\n\t unregister(?progress_handler),\n\t unlink(Caller)\n end.\n\nprogress_dialog(_Env,Title,Str) ->\n PD = wxProgressDialog:new(Title,Str,\n\t\t\t [{maximum,101},\n\t\t\t {style,\n\t\t\t\t?wxPD_APP_MODAL bor\n\t\t\t\t ?wxPD_SMOOTH bor\n\t\t\t\t ?wxPD_AUTO_HIDE}]),\n wxProgressDialog:setMinSize(PD,{200,-1}),\n PD.\n\nupdate_progress(PD,Value) ->\n try wxProgressDialog:update(PD,Value)\n catch _:_ -> throw(closed) %% Port or window have died\n end.\nupdate_progress_text(PD,Text) ->\n try wxProgressDialog:update(PD,0,[{newmsg,Text}])\n catch _:_ -> throw(closed) %% Port or window have died\n end.\nfinish_progress(PD) ->\n wxProgressDialog:destroy(PD).\n","avg_line_length":32.7411764706,"max_line_length":89,"alphanum_fraction":0.6409550046} +{"size":281,"ext":"erl","lang":"Erlang","max_stars_count":5.0,"content":"-module(shortener_mock_service).\n\n-behaviour(woody_server_thrift_handler).\n\n-export([handle_function\/4]).\n\n-spec handle_function(woody:func(), woody:args(), woody_context:ctx(), #{}) -> {ok, term()}.\nhandle_function(FunName, Args, _, #{function := Fun}) ->\n Fun(FunName, Args).\n","avg_line_length":28.1,"max_line_length":92,"alphanum_fraction":0.7010676157} +{"size":13902,"ext":"erl","lang":"Erlang","max_stars_count":7.0,"content":"%%%-------------------------------------------------------------------\n%%% @doc\n%%% Based on SumoDB Changeset and `Ecto.Changeset'.\n%%%\n%%% Changesets allow filtering, casting, validation and definition of\n%%% constraints when manipulating schemas.\n%%%\n%%% @reference See\n%%% SumoDB<\/a>\n%%% Ecto.Changeset<\/a>\n%%% @end\n%%% @end\n%%%-------------------------------------------------------------------\n-module(xdb_changeset).\n\n%% Properties\n-export([\n schema\/1,\n data\/1,\n params\/1,\n errors\/1,\n changes\/1,\n is_valid\/1,\n types\/1,\n required\/1,\n repo\/1,\n action\/1,\n filters\/1\n]).\n\n%% API\n-export([\n add_error\/3,\n add_error\/4,\n apply_changes\/1,\n cast\/3,\n change\/2,\n get_field\/2,\n get_field\/3,\n put_change\/3,\n get_change\/2,\n get_change\/3,\n delete_change\/2,\n validate_change\/3,\n validate_required\/2,\n validate_inclusion\/3,\n validate_number\/3,\n validate_integer\/2,\n validate_length\/3,\n validate_format\/3\n]).\n\n-import(xdb_schema_type, [cast_field_name\/1]).\n\n%%%=============================================================================\n%%% Types\n%%%=============================================================================\n\n%% General types\n-type error() :: {binary(), xdb_lib:keyword()}.\n-type errors() :: [{atom(), error()}].\n-type action() :: undefined | insert | update | delete | replace | ignore.\n\n%% Changeset definition\n-type t() :: #{\n schema => module() | undefined,\n data => xdb_schema:t() | undefined,\n params => xdb_schema:fields() | undefined,\n errors => errors(),\n changes => xdb_lib:kw_map(),\n is_valid => boolean(),\n types => xdb_lib:kw_map() | undefined,\n required => [atom()],\n repo => atom() | undefined,\n action => action(),\n filters => xdb_lib:kw_map()\n}.\n\n%% Exported types\n-export_type([\n t\/0\n]).\n\n%%%=============================================================================\n%%% Properties\n%%%=============================================================================\n\n-spec schema(t()) -> module() | undefined.\nschema(#{schema := Value}) ->\n Value.\n\n-spec data(t()) -> xdb_schema:t() | undefined.\ndata(#{data := Value}) ->\n Value.\n\n-spec params(t()) -> xdb_schema:fields() | undefined.\nparams(#{params := Value}) ->\n Value.\n\n-spec errors(t()) -> errors().\nerrors(#{errors := Value}) ->\n Value.\n\n-spec changes(t()) -> xdb_lib:kw_map().\nchanges(#{changes := Value}) ->\n Value.\n\n-spec is_valid(t()) -> boolean().\nis_valid(#{is_valid := Value}) ->\n Value.\n\n-spec types(t()) -> xdb_lib:kw_map() | undefined.\ntypes(#{types := Value}) ->\n Value.\n\n-spec required(t()) -> [atom()].\nrequired(#{required := Value}) ->\n Value.\n\n-spec repo(t()) -> atom() | undefined.\nrepo(#{repo := Value}) ->\n Value.\n\n-spec action(t()) -> atom() | undefined.\naction(#{action := Value}) ->\n Value.\n\n-spec filters(t()) -> xdb_lib:kw_map().\nfilters(#{filters := Value}) ->\n Value.\n\n%%%=============================================================================\n%%% API\n%%%=============================================================================\n\n-spec add_error(t(), atom(), binary()) -> t().\nadd_error(Changeset, Key, Message) ->\n add_error(Changeset, Key, Message, []).\n\n-spec add_error(t(), atom(), binary(), xdb_lib:keyword()) -> t().\nadd_error(#{errors := Errors} = Changeset, Key, Message, Keys) ->\n Changeset#{errors := [{Key, {Message, Keys}} | Errors], is_valid := false}.\n\n-spec apply_changes(t()) -> xdb_schema:t().\napply_changes(#{changes := Changes, data := Data}) when map_size(Changes) == 0 ->\n Data;\napply_changes(#{changes := Changes, data := Data}) ->\n xdb_schema:set_fields(Data, Changes).\n\n-spec cast(Data, Params, Permitted) -> Res when\n Data :: xdb_schema:t() | t(),\n Params :: xdb_schema:fields(),\n Permitted :: [atom()],\n Res :: t().\ncast(#{schema := Schema, data := Data, types := Types} = CS, Params, Permitted) ->\n NewChangeset = do_cast({Schema, Data, Types}, Params, Permitted),\n cast_merge(CS, NewChangeset);\ncast(Data, Params, Permitted) ->\n Metadata = get_metadata(Data),\n do_cast(Metadata, Params, Permitted).\n\n%% @private\ndo_cast({SchemaName, Data, Types}, Params, Permitted) ->\n NewParams = xdb_schema:normalize_keys(Params),\n FilteredParams = maps:with(Permitted, NewParams),\n\n {Changes, Errors, IsValid} =\n maps:fold(fun(ParamKey, ParamVal, Acc) ->\n process_param(ParamKey, ParamVal, Types, Acc)\n end, {#{}, [], true}, FilteredParams),\n\n (changeset())#{\n schema := SchemaName,\n data := Data,\n params := FilteredParams,\n changes := Changes,\n errors := Errors,\n is_valid := IsValid,\n types := Types\n }.\n\n-spec change(Data, Changes) -> Res when\n Data :: xdb_schema:t() | t(),\n Changes :: xdb_lib:kw_map(),\n Res :: t().\nchange(#{changes := _, types := _} = Changeset, Changes) ->\n NewChanges = changes(get_changed(Changeset, Changes)),\n Changeset#{changes := NewChanges};\nchange(Data, Changes) ->\n {SchemaName, Data, Types} = get_metadata(Data),\n Changeset = (changeset())#{\n schema := SchemaName,\n data := Data,\n types := Types\n },\n NewChanges = changes(get_changed(Changeset, Changes)),\n Changeset#{changes := NewChanges}.\n\n%% @private\nget_changed(Changeset, NewChanges) ->\n maps:fold(fun(K, V, Acc) ->\n put_change(Acc, K, V)\n end, Changeset, NewChanges).\n\n-spec get_field(t(), atom()) -> term().\nget_field(Changeset, Key) ->\n get_field(Changeset, Key, undefined).\n\n-spec get_field(t(), atom(), term()) -> term().\nget_field(#{changes := Changes, data := Data}, Key, Default) ->\n case maps:find(Key, Changes) of\n {ok, Value} ->\n Value;\n error ->\n case maps:find(Key, Data) of\n {ok, Value} -> Value;\n error -> Default\n end\n end.\n\n-spec put_change(t(), atom(), term()) -> t().\nput_change(#{changes := Changes, data := Data} = Changeset, Key, Value) ->\n NewChanges =\n case maps:find(Key, Data) of\n {ok, V} when V \/= Value ->\n maps:put(Key, Value, Changes);\n _ ->\n case maps:is_key(Key, Changes) of\n true -> maps:remove(Key, Changes);\n false -> Changes\n end\n end,\n\n Changeset#{changes := NewChanges}.\n\n-spec get_change(t(), atom()) -> term().\nget_change(Changeset, Key) ->\n get_change(Changeset, Key, undefined).\n\n-spec get_change(t(), atom(), term()) -> term().\nget_change(#{changes := Changes}, Key, Default) ->\n maps:get(Key, Changes, Default).\n\n-spec delete_change(t(), atom()) -> t().\ndelete_change(#{changes := Changes} = Changeset, Key) ->\n NewChanges = maps:remove(Key, Changes),\n Changeset#{changes := NewChanges}.\n\n-spec validate_change(t(), atom(), fun((atom(), term()) -> [error()])) -> t().\nvalidate_change(#{changes := Changes, errors := Errors} = Changeset, Field, Validator) ->\n _ = ensure_field_exists(Changeset, Field),\n\n Value = fetch(Field, Changes),\n NewErrors1 =\n case is_nil(Value) of\n true -> [];\n false -> Validator(Field, Value)\n end,\n\n NewErrors2 =\n [begin\n case Error of\n {K, V} when is_atom(K), is_binary(V) ->\n {K, {V, []}};\n {K, {V, Opts}} when is_atom(K), is_binary(V), is_list(Opts) ->\n {K, {V, Opts}}\n end\n end || Error <- NewErrors1],\n\n case NewErrors2 of\n [] -> Changeset;\n [_ | _] -> Changeset#{errors := NewErrors2 ++ Errors, is_valid := false}\n end.\n\n-spec validate_required(t(), [atom()]) -> t().\nvalidate_required(#{required := Required, errors := Errors} = CS, Fields) ->\n NewErrors = [\n {F, {<<\"can't be blank\">>, [{validation, required}]}}\n || F <- Fields, is_missing(CS, F), ensure_field_exists(CS, F), is_nil(fetch(F, Errors))\n ],\n\n case NewErrors of\n [] -> CS#{required := Fields ++ Required};\n _ -> CS#{required := Fields ++ Required, errors := NewErrors ++ Errors, is_valid := false}\n end.\n\n-spec validate_inclusion(t(), atom(), [term()]) -> t().\nvalidate_inclusion(Changeset, Field, Enum) ->\n validate_change(Changeset, Field, fun(_, Value) ->\n case lists:member(Value, Enum) of\n true -> [];\n false -> [{Field, {<<\"is invalid\">>, [{validation, inclusion}]}}]\n end\n end).\n\n-spec validate_number(t(), atom(), xdb_lib:keyword()) -> t().\nvalidate_number(Changeset, Field, Opts) ->\n validate_change(Changeset, Field, fun(TargetField, Value) ->\n hd([begin\n case maps:find(SpecKey, number_validators(TargetValue)) of\n {ok, {SpecFun, Message}} ->\n validate_number(TargetField, Value, Message, SpecFun, TargetValue);\n error ->\n error({badarg, SpecKey})\n end\n end || {SpecKey, TargetValue} <- Opts])\n end).\n\n%% @private\nvalidate_number(Field, Value, Message, SpecFun, TargetValue) ->\n case SpecFun(Value, TargetValue) of\n true -> [];\n false -> [{Field, {Message, [{validation, number}]}}]\n end.\n\n\n-spec validate_integer(t(), atom()) -> t().\nvalidate_integer(Changeset, Key) ->\n case is_integer(get_field(Changeset, Key)) of\n true -> Changeset;\n false -> add_error(Changeset, Key, <<\"must be integer\">>)\n end.\n\n-spec validate_length(t(), atom(), xdb_lib:keyword()) -> t().\nvalidate_length(Changeset, Field, Opts) ->\n validate_change(Changeset, Field, fun(_, Value) ->\n case do_validate_length(length_validators(), Opts, byte_size(Value), undefined) of\n undefined -> [];\n Message -> [{Field, {Message, [{validation, length}]}}]\n end\n end).\n\n%% @private\ndo_validate_length([], _, _, Acc) ->\n Acc;\ndo_validate_length([{Opt, Validator} | T], Opts, Length, Acc) ->\n case fetch(Opt, Opts) of\n undefined ->\n do_validate_length(T, Opts, Length, Acc);\n Value ->\n case Validator(Length, Value) of\n undefined ->\n do_validate_length(T, Opts, Length, Acc);\n Message ->\n Message\n end\n end.\n\n%% @private\nwrong_length(Value, Value) ->\n undefined;\nwrong_length(_Length, Value) ->\n text(\"should be ~p character(s)\", [Value]).\n\n%% @private\ntoo_short(Length, Value) when Length >= Value ->\n undefined;\ntoo_short(_Length, Value) ->\n text(\"should be at least ~p character(s)\", [Value]).\n\n%% @private\ntoo_long(Length, Value) when Length =< Value ->\n undefined;\ntoo_long(_Length, Value) ->\n text(\"should be at most ~p character(s)\", [Value]).\n\n-spec validate_format(t(), atom(), binary()) -> t().\nvalidate_format(Changeset, Field, Format) ->\n validate_change(Changeset, Field, fun(_, Value) ->\n case re:run(Value, Format) of\n nomatch -> [{Field, {<<\"has invalid format\">>, [{validation, format}]}}];\n _ -> []\n end\n end).\n\n%%%=============================================================================\n%%% Internal functions\n%%%=============================================================================\n\n%% @private\nchangeset() ->\n #{\n schema => undefined,\n data => undefined,\n params => undefined,\n errors => [],\n changes => #{},\n is_valid => true,\n types => undefined,\n required => [],\n repo => undefined,\n action => undefined,\n filters => #{}\n }.\n\n%% @private\nget_metadata(Data) ->\n SchemaMod = xdb_schema:module(Data),\n SchemaSpec = SchemaMod:schema_spec(),\n Types = xdb_schema_spec:field_types(SchemaSpec),\n {SchemaMod, Data, Types}.\n\n%% @private\nprocess_param(ParamKey, ParamValue, Types, {Changes, Errors, IsValid}) ->\n Key = cast_field_name(ParamKey),\n case cast_field(Key, ParamValue, Types) of\n {ok, CastValue} ->\n {maps:put(Key, CastValue, Changes), Errors, IsValid};\n {invalid, Type} ->\n {Changes, [{Key, {<<\"is invalid\">>, [{type, Type}, {validation, cast}]}} | Errors], false};\n missing ->\n {Changes, Errors, IsValid}\n end.\n\n%% @private\ncast_field(Key, Value, Types) ->\n case maps:get(Key, Types, error) of\n error ->\n missing;\n Type ->\n case xdb_schema_type:cast(Type, Value) of\n {ok, _} = Ok -> Ok;\n {error, _} -> {invalid, Type}\n end\n end.\n\n%% @private\ncast_merge(CS1, CS2) ->\n NewChanges = maps:merge(changes(CS1), changes(CS2)),\n NewErrors = lists:usort(errors(CS1) ++ errors(CS2)),\n NewIsValid = is_valid(CS1) and is_valid(CS2),\n NewTypes = types(CS1),\n NewRequired = lists:usort(required(CS1) ++ required(CS2)),\n NewParams = maps:merge(cs_params(CS1), cs_params(CS2)),\n\n CS1#{\n params := NewParams,\n changes := NewChanges,\n errors := NewErrors,\n is_valid := NewIsValid,\n types := NewTypes,\n required := NewRequired\n }.\n\n%% @private\ncs_params(#{params := Params}) ->\n case Params of\n undefined -> #{};\n _ -> Params\n end.\n\n%% @private\nis_missing(Changeset, Field) ->\n case get_field(Changeset, Field) of\n undefined -> true;\n _ -> false\n end.\n\n%% @private\nensure_field_exists(#{types := Types}, Field) ->\n case maps:is_key(Field, Types) of\n true -> true;\n false -> error({badarg, Field})\n end.\n\n%% @private\nis_nil(undefined) -> true;\nis_nil(_) -> false.\n\n%% @private\nfetch(Key, Keyword) when is_list(Keyword) ->\n case lists:keyfind(Key, 1, Keyword) of\n {Key, Value} -> Value;\n _ -> undefined\n end;\nfetch(Key, Map) when is_map(Map) ->\n maps:get(Key, Map, undefined).\n\n%% @private\nnumber_validators(N) ->\n Text = fun(T) -> text(\"must be ~s ~p\", [T, N]) end,\n #{\n less_than => {fun(X, Y) -> X < Y end, Text(\"less than\")},\n greater_than => {fun(X, Y) -> X > Y end, Text(\"greater than\")},\n less_than_or_equal_to => {fun(X, Y) -> X =< Y end, Text(\"less than or equal to\")},\n greater_than_or_equal_to => {fun(X, Y) -> X >= Y end, Text(\"greater than or equal to\")},\n equal_to => {fun(X, Y) -> X == Y end, Text(\"equal to\")}\n }.\n\n%% @private\nlength_validators() ->\n [{is, fun wrong_length\/2}, {min, fun too_short\/2}, {max, fun too_long\/2}].\n\n%% @private\ntext(Msg, Args) ->\n iolist_to_binary(io_lib:format(Msg, Args)).\n","avg_line_length":27.9718309859,"max_line_length":98,"alphanum_fraction":0.5730830096} +{"size":20662,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%% -------------------------------------------------------------------\n%%\n%% cuttlefish_datatypes: handles datatypes in cuttlefish schemas\n%%\n%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved.\n%%\n%% This file is provided to you under the Apache License,\n%% Version 2.0 (the \"License\"); you may not use this file\n%% except in compliance with the License. You may obtain\n%% a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing,\n%% software distributed under the License is distributed on an\n%% \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n%% KIND, either express or implied. See the License for the\n%% specific language governing permissions and limitations\n%% under the License.\n%%\n%% -------------------------------------------------------------------\n-module(cuttlefish_datatypes).\n\n-ifdef(TEST).\n-include_lib(\"eunit\/include\/eunit.hrl\").\n-endif.\n\n-type datatype() :: integer |\n string |\n atom |\n file |\n directory |\n flag |\n {flag, atom(), atom()} |\n {flag, {atom(), term()}, {atom(), term()}} |\n {enum, [atom()]} |\n ip |\n {duration, cuttlefish_duration:time_unit() } |\n bytesize |\n {percent, integer} |\n {percent, float} |\n float.\n-type extended() :: { integer, integer() } |\n { string, string() } |\n { file, file:filename() } |\n { directory, file:filename() } |\n { atom, atom() } |\n { ip, { string(), integer() } } |\n { {duration, cuttlefish_duration:time_unit() }, string() } |\n { bytesize, string() } |\n { {percent, integer}, integer() } |\n { {percent, float}, float() } |\n { float, float() }.\n-type datatype_list() :: [ datatype() | extended() ].\n\n-export_type([datatype\/0, extended\/0, datatype_list\/0]).\n\n-export([\n is_supported\/1,\n is_extended\/1,\n is_valid_list\/1,\n from_string\/2,\n to_string\/2,\n extended_from\/1\n]).\n\n-spec is_supported(any()) -> boolean().\nis_supported(integer) -> true;\nis_supported(string) -> true;\nis_supported(file) -> true;\nis_supported(directory) -> true;\nis_supported(flag) -> true;\nis_supported({flag, On, Off}) when is_atom(On), is_atom(Off) -> true;\nis_supported({flag, {On, _}, {Off, _}}) when is_atom(On), is_atom(Off) -> true;\nis_supported(atom) -> true;\nis_supported({enum, E}) when is_list(E) -> true;\nis_supported(ip) -> true;\nis_supported({duration, f}) -> true;\nis_supported({duration, w}) -> true;\nis_supported({duration, d}) -> true;\nis_supported({duration, h}) -> true;\nis_supported({duration, m}) -> true;\nis_supported({duration, s}) -> true;\nis_supported({duration, ms}) -> true;\nis_supported(bytesize) -> true;\nis_supported({percent, integer}) -> true;\nis_supported({percent, float}) -> true;\nis_supported(float) -> true;\nis_supported(_) -> false.\n\n-spec is_extended(any()) -> boolean().\nis_extended({integer, I}) when is_integer(I) -> true;\nis_extended({string, S}) when is_list(S) -> true;\nis_extended({atom, A}) when is_atom(A) -> true;\nis_extended({file, F}) when is_list(F) -> true;\nis_extended({directory, D}) when is_list(D) -> true;\nis_extended({ip, {IP, Port}}) when is_list(IP) andalso is_integer(Port) -> true;\nis_extended({ip, StringIP}) when is_list(StringIP) -> true;\nis_extended({{duration, f}, D}) when is_list(D) -> true;\nis_extended({{duration, w}, D}) when is_list(D) -> true;\nis_extended({{duration, d}, D}) when is_list(D) -> true;\nis_extended({{duration, g}, D}) when is_list(D) -> true;\nis_extended({{duration, m}, D}) when is_list(D) -> true;\nis_extended({{duration, s}, D}) when is_list(D) -> true;\nis_extended({{duration, ms}, D}) when is_list(D) -> true;\nis_extended({bytesize, B}) when is_list(B) -> true;\nis_extended({{percent, integer}, _Int}) -> true;\nis_extended({{percent, float}, _Float}) -> true;\nis_extended({float, F}) when is_float(F) -> true;\nis_extended(_) -> false.\n\n-spec extended_from(extended()) -> datatype().\nextended_from({integer, _}) -> integer;\nextended_from({string, _}) -> string;\nextended_from({atom, _}) -> atom;\nextended_from({file, _}) -> file;\nextended_from({directory, _}) -> directory;\nextended_from({ip, _}) -> ip;\nextended_from({{duration, Unit}, _}) -> {duration, Unit};\nextended_from({bytesize, _}) -> bytesize;\nextended_from({{percent, integer}, _}) -> {percent, integer};\nextended_from({{percent, float}, _}) -> {percent, float};\nextended_from({float, _}) -> float;\nextended_from(Other) ->\n case is_supported(Other) of\n true ->\n Other;\n _ -> error\n end.\n\n-spec is_valid_list(any()) -> boolean().\nis_valid_list(NotList) when not is_list(NotList) ->\n false;\nis_valid_list([]) -> false;\nis_valid_list(List) ->\n lists:all(fun(X) ->\n is_supported(X)\n orelse\n is_extended(X)\n end, List).\n\n-spec to_string(term(), datatype()) -> string() | cuttlefish_error:error().\nto_string(Atom, atom) when is_list(Atom) -> Atom;\nto_string(Atom, atom) when is_atom(Atom) -> atom_to_list(Atom);\n\nto_string(Integer, integer) when is_integer(Integer) -> integer_to_list(Integer);\nto_string(Integer, integer) when is_list(Integer) -> Integer;\n\nto_string({IP, Port}, ip) when is_list(IP), is_integer(Port) -> IP ++ \":\" ++ integer_to_list(Port);\nto_string(IPString, ip) when is_list(IPString) -> IPString;\n\nto_string(Enum, {enum, _}) when is_list(Enum) -> Enum;\nto_string(Enum, {enum, _}) when is_atom(Enum) -> atom_to_list(Enum);\n\nto_string(Duration, {duration, _}) when is_list(Duration) -> Duration;\nto_string(Duration, {duration, Unit}) when is_integer(Duration) -> cuttlefish_duration:to_string(Duration, Unit);\n\nto_string(Bytesize, bytesize) when is_list(Bytesize) -> Bytesize;\nto_string(Bytesize, bytesize) when is_integer(Bytesize) -> cuttlefish_bytesize:to_string(Bytesize);\n\nto_string(String, string) when is_list(String) -> String;\n\nto_string(File, file) when is_list(File) -> File;\n\nto_string(Directory, directory) when is_list(Directory) -> Directory;\n\nto_string(Flag, flag) when is_atom(Flag) -> cuttlefish_flag:to_string(Flag, flag);\nto_string(Flag, flag) when is_list(Flag) -> cuttlefish_flag:to_string(Flag, flag);\nto_string(Flag, {flag, _, _}=Type) when is_atom(Flag) -> cuttlefish_flag:to_string(Flag, Type);\nto_string(Flag, {flag, _, _}=Type) when is_list(Flag) -> cuttlefish_flag:to_string(Flag, Type);\n\nto_string(Percent, {percent, integer}) when is_integer(Percent) ->\n integer_to_list(Percent) ++ \"%\";\nto_string(Percent, {percent, integer}) when is_list(Percent) ->\n Percent;\nto_string(Percent, {percent, float}) when is_float(Percent) ->\n P = list_to_float(float_to_list(Percent * 100, [{decimals, 6}, compact])),\n integer_to_list(cuttlefish_util:ceiling(P)) ++ \"%\";\nto_string(Percent, {percent, float}) when is_list(Percent) ->\n Percent;\n\nto_string(Float, float) when is_float(Float) ->\n float_to_list(Float, [{decimals, 6}, compact]);\nto_string(Float, float) when is_list(Float) -> Float;\n\n%% The Pokemon Clause: Gotta Catch 'em all!\nto_string(Value, MaybeExtendedDatatype) ->\n case is_extended(MaybeExtendedDatatype) of\n true ->\n to_string(Value, extended_from(MaybeExtendedDatatype));\n _ ->\n {error, {type, {Value, MaybeExtendedDatatype}}}\n end.\n\n-spec from_string(term(), datatype()) -> term() | cuttlefish_error:error().\nfrom_string(Atom, atom) when is_atom(Atom) -> Atom;\nfrom_string(String, atom) when is_list(String) -> list_to_atom(String);\n\nfrom_string(Value, {enum, Enum}) ->\n cuttlefish_enum:parse(Value, {enum, Enum});\n\nfrom_string(Integer, integer) when is_integer(Integer) -> Integer;\nfrom_string(String, integer) when is_list(String) ->\n try list_to_integer(String) of\n X -> X\n catch\n _:_ -> {error, {conversion, {String, integer}}}\n end;\n\nfrom_string({IP, Port}, ip) when is_list(IP), is_integer(Port) -> {IP, Port};\nfrom_string(String, ip) when is_list(String) ->\n from_string_to_ip(String, lists:split(string:rchr(String, $:), String));\n\nfrom_string(Duration, {duration, _}) when is_integer(Duration) -> Duration;\nfrom_string(Duration, {duration, Unit}) when is_list(Duration) -> cuttlefish_duration:parse(Duration, Unit);\n\nfrom_string(Bytesize, bytesize) when is_integer(Bytesize) -> Bytesize;\nfrom_string(Bytesize, bytesize) when is_list(Bytesize) -> cuttlefish_bytesize:parse(Bytesize);\n\nfrom_string(String, string) when is_list(String) -> String;\n\nfrom_string(File, file) when is_list(File) -> File;\n\nfrom_string(Directory, directory) when is_list(Directory) -> Directory;\n\nfrom_string(Flag, flag) when is_list(Flag) -> cuttlefish_flag:parse(Flag);\nfrom_string(Flag, flag) when is_atom(Flag) -> cuttlefish_flag:parse(Flag);\n\nfrom_string(Flag, {flag, _, _}=Type) when is_list(Flag) -> cuttlefish_flag:parse(Flag, Type);\nfrom_string(Flag, {flag, _, _}=Type) when is_atom(Flag) -> cuttlefish_flag:parse(Flag, Type);\n\nfrom_string(Percent, {percent, integer}) when is_integer(Percent), Percent >= 0, Percent =< 100 -> Percent;\nfrom_string(Percent, {percent, integer}) when is_integer(Percent) ->\n {error, {range, {{Percent, {percent, integer}}, \"0 - 100%\"}}};\n%% This clause ends with a percent sign!\nfrom_string(Percent, {percent, integer}) when is_list(Percent) ->\n from_string(\n list_to_integer(string:sub_string(Percent, 1, length(Percent) - 1)),\n {percent, integer});\n\nfrom_string(Percent, {percent, float}) when is_float(Percent), Percent >= 0, Percent =< 1 -> Percent;\nfrom_string(Percent, {percent, float}) when is_float(Percent) ->\n {error, {range, {{Percent, {percent, float}}, \"0 - 100%\"}}};\n%% This clause ends with a percent sign!\nfrom_string(Percent, {percent, float}) when is_list(Percent) ->\n from_string(\n list_to_integer(string:sub_string(Percent, 1, length(Percent) - 1)) \/ 100.0,\n {percent, float});\n\nfrom_string(Float, float) when is_float(Float) -> Float;\nfrom_string(String, float) when is_list(String) ->\n try list_to_float(String) of\n X -> X\n catch\n _:_ -> {error, {conversion, {String, float}}}\n end;\n\nfrom_string(Thing, InvalidDatatype) ->\n {error, {type, {Thing, InvalidDatatype}}}.\n\n\n%%% Utility functions for IP conversion\n\nport_to_integer(Str) ->\n try\n list_to_integer(Str)\n of\n X when X >= 0 ->\n X;\n %% Negative ports are nonsensical\n _X ->\n undefined\n catch\n _:_ ->\n undefined\n end.\n\nip_conversions(String, _IPStr, {error, einval}, _Port) ->\n {error, {conversion, {String, 'IP'}}};\nip_conversions(String, _IPStr, _IP, undefined) ->\n {error, {conversion, {String, 'IP'}}};\nip_conversions(_String, IPStr, {ok, _}, Port) ->\n {IPStr, Port}.\n\ndroplast(List) ->\n lists:sublist(List, length(List)-1).\n\nfrom_string_to_ip(String, {[], String}) ->\n {error, {conversion, {String, 'IP'}}}; %% No port\nfrom_string_to_ip(String, {IpPlusColon, PortString}) ->\n %% Still need to drop last character from IP, the trailing\n %% colon. Perfect use case for lists:droplast\/1 but it's a recent\n %% addition\n IP = droplast(IpPlusColon),\n ip_conversions(String, IP, inet:parse_address(IP), port_to_integer(PortString)).\n\n\n-ifdef(TEST).\n\n-define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))).\n\nto_string_atom_test() ->\n ?assertEqual(\"split_the\", to_string(split_the, atom)),\n ?assertEqual(\"split_the\", to_string(\"split_the\", atom)).\n\nto_string_integer_test() ->\n ?assertEqual(\"32\", to_string(32, integer)),\n ?assertEqual(\"32\", to_string(\"32\", integer)).\n\nto_string_ip_test() ->\n ?assertEqual(\"127.0.0.1:8098\", to_string(\"127.0.0.1:8098\", ip)),\n ?assertEqual(\"127.0.0.1:8098\", to_string({\"127.0.0.1\", 8098}, ip)).\n\nto_string_enum_test() ->\n ?assertEqual(\"true\", to_string(\"true\", {enum, [true, false]})),\n ?assertEqual(\"true\", to_string(true, {enum, [true, false]})).\n\nto_string_string_test() ->\n ?assertEqual(\"string\", to_string(\"string\", string)).\n\nto_string_duration_test() ->\n ?assertEqual(\"1w\", to_string(\"1w\", {duration, s})),\n ?assertEqual(\"1w\", to_string(604800000, {duration, ms})).\n\nto_string_bytesize_test() ->\n ?assertEqual(\"1GB\", to_string(1073741824, bytesize)),\n ?assertEqual(\"1GB\", to_string(\"1GB\", bytesize)).\n\nto_string_percent_integer_test() ->\n ?assertEqual(\"10%\", to_string(10, {percent, integer})),\n ?assertEqual(\"10%\", to_string(\"10%\", {percent, integer})),\n ok.\n\nto_string_percent_float_test() ->\n ?assertEqual(\"10%\", to_string(0.1, {percent, float})),\n ?assertEqual(\"10%\", to_string(\"10%\", {percent, float})),\n ok.\n\nto_string_float_test() ->\n ?assertEqual(\"0.1\", to_string(0.1, float)),\n ?assertEqual(\"0.1\", to_string(\"0.1\", float)),\n ok.\n\nto_string_extended_type_test() ->\n ?assertEqual(\"split_the\", to_string(split_the, {atom, split_the})),\n ?assertEqual(\"split_the\", to_string(\"split_the\", {atom, split_the})),\n ?assertEqual(\"32\", to_string(32, {integer, 32})),\n ?assertEqual(\"32\", to_string(\"32\", {integer, 32})),\n ?assertEqual(\"127.0.0.1:8098\", to_string(\"127.0.0.1:8098\", {ip, \"127.0.0.1:8098\"})),\n ?assertEqual(\"127.0.0.1:8098\", to_string({\"127.0.0.1\", 8098}, {ip, {\"127.0.0.1\", 8098}})),\n ?assertEqual(\"string\", to_string(\"string\", {string, \"string\"})),\n ?assertEqual(\"1w\", to_string(\"1w\", {{duration, s}, \"1w\"})),\n ?assertEqual(\"1w\", to_string(604800000, {{duration, ms}, \"1w\"})),\n ?assertEqual(\"1GB\", to_string(1073741824, {bytesize, \"1GB\"})),\n ?assertEqual(\"1GB\", to_string(\"1GB\", {bytesize, \"1GB\"})),\n ?assertEqual(\"10%\", to_string(10, {{percent, integer}, \"10%\"})),\n ?assertEqual(\"10%\", to_string(\"10%\", {{percent, integer}, \"10%\"})),\n ?assertEqual(\"10%\", to_string(0.1, {{percent, float}, \"10%\"})),\n ?assertEqual(\"10%\", to_string(\"10%\", {{percent, float}, \"10%\"})),\n ?assertEqual(\"0.1\", to_string(0.1, {float, 0.1})),\n ?assertEqual(\"0.1\", to_string(\"0.1\", {float, 0.1})),\n ok.\n\nto_string_unsupported_datatype_test() ->\n ?assertEqual(\"Tried to convert \\\"Something\\\" but invalid datatype: unsupported_datatype\", ?XLATE(to_string(\"Something\", unsupported_datatype))).\n\nfrom_string_atom_test() ->\n ?assertEqual(split_the, from_string(split_the, atom)),\n ?assertEqual(split_the, from_string(\"split_the\", atom)).\n\nfrom_string_integer_test() ->\n ?assertEqual(32, from_string(32, integer)),\n ?assertEqual(32, from_string(\"32\", integer)),\n ?assertEqual(\"\\\"thirty_two\\\" cannot be converted to a(n) integer\", ?XLATE(from_string(\"thirty_two\", integer))),\n ok.\n\nfrom_string_ip_test() ->\n ?assertEqual({\"127.0.0.1\", 8098}, from_string(\"127.0.0.1:8098\", ip)),\n ?assertEqual(\n {\"2001:0db8:85a3:0042:1000:8a2e:0370:7334\", 8098},\n from_string(\"2001:0db8:85a3:0042:1000:8a2e:0370:7334:8098\", ip)),\n ?assertEqual(\n {\"2001:0db8:85a3::0370:7334\", 8098},\n from_string(\"2001:0db8:85a3::0370:7334:8098\", ip)),\n ?assertEqual(\n {\"::1\", 1},\n from_string(\"::1:1\", ip)),\n\n BadIPs = [\n \"This is not an IP:80\",\n \"2001:0db8:85a3:0042:1000:8a2e:0370:80\",\n \"127.0.0.1.1:80\",\n \"127.256.0.1:80\",\n \"127.0.0.1\", %% No port\n \"127.0.0.1:-5\",\n \"0:127.0.0.1:80\",\n \"127.0.0.1:80l\",\n \":1:1\"\n ],\n\n lists:foreach(fun(Bad) ->\n ?assertEqual({error, {conversion, {Bad, 'IP'}}},\n from_string(Bad, ip))\n end,\n BadIPs),\n ok.\n\nfrom_string_enum_test() ->\n ?assertEqual(\"\\\"a\\\" is not a valid enum value, acceptable values are: b, c\", ?XLATE(from_string(a, {enum, [b, c]}))),\n ?assertEqual(true, from_string(\"true\", {enum, [true, false]})),\n ?assertEqual(true, from_string(true, {enum, [true, false]})).\n\nfrom_string_duration_test() ->\n %% more examples in the the cuttlefish_duration tests\n ?assertEqual(1100, from_string(\"1s100ms\", {duration, ms})),\n ?assertEqual(1100, from_string(1100, {duration, ms})),\n ok.\n\nfrom_string_duration_secs_test() ->\n %% more examples in the the cuttlefish_duration tests\n %% also rounds up for smaller units\n ?assertEqual(2, from_string(\"1s100ms\", {duration, s})),\n ?assertEqual(2, from_string(2, {duration, s})),\n ok.\n\nfrom_string_percent_integer_test() ->\n ?assertEqual(10, from_string(\"10%\", {percent, integer})),\n ?assertEqual(10, from_string(10, {percent, integer})),\n %% Range!\n ?assertEqual(0, from_string(\"0%\", {percent, integer})),\n ?assertEqual(100, from_string(\"100%\", {percent, integer})),\n ?assertEqual(\"110% can't be outside the range 0 - 100%\", ?XLATE(from_string(\"110%\", {percent, integer}))),\n ?assertEqual(\"-1% can't be outside the range 0 - 100%\", ?XLATE(from_string(\"-1%\", {percent, integer}))),\n ok.\n\nfrom_string_percent_float_test() ->\n ?assertEqual(0.10, from_string(\"10%\", {percent, float})),\n ?assertEqual(0.10, from_string(0.1, {percent, float})),\n %% Range!\n ?assertEqual(0.0, from_string(\"0%\", {percent, float})),\n ?assertEqual(1.0, from_string(\"100%\", {percent, float})),\n ?assertEqual(\"110% can't be outside the range 0 - 100%\", ?XLATE(from_string(\"110%\", {percent, float}))),\n ?assertEqual(\"-1% can't be outside the range 0 - 100%\", ?XLATE(from_string(\"-1%\", {percent, float}))),\n ok.\n\nfrom_string_float_test() ->\n ?assertEqual(0.1, from_string(\"0.100\", float)),\n ?assertEqual(0.1, from_string(0.1, float)),\n ok.\n\nfrom_string_string_test() ->\n ?assertEqual(\"string\", from_string(\"string\", string)).\n\nfrom_string_unsupported_datatype_test() ->\n ?assertEqual(\"Tried to convert \\\"string\\\" but invalid datatype: unsupported_datatype\", ?XLATE(from_string(\"string\", unsupported_datatype))).\n\nis_supported_test() ->\n ?assert(is_supported(integer)),\n ?assert(is_supported(string)),\n ?assert(is_supported(atom)),\n ?assert(is_supported(file)),\n ?assert(is_supported(directory)),\n ?assert(is_supported({enum, [one, two, three]})),\n ?assert(not(is_supported({enum, not_a_list}))),\n ?assert(is_supported(ip)),\n ?assert(is_supported({duration, f})),\n ?assert(is_supported({duration, w})),\n ?assert(is_supported({duration, d})),\n ?assert(is_supported({duration, h})),\n ?assert(is_supported({duration, m})),\n ?assert(is_supported({duration, s})),\n ?assert(is_supported({duration, ms})),\n ?assert(is_supported(bytesize)),\n ?assert(not(is_supported(some_unsupported_type))),\n ok.\n\nis_extended_test() ->\n ?assertEqual(true, is_extended({integer, 10})),\n ?assertEqual(true, is_extended({integer, -10})),\n ?assertEqual(false, is_extended({integer, \"ten\"})),\n\n ?assertEqual(true, is_extended({string, \"string\"})),\n ?assertEqual(false, is_extended({string, string})),\n ?assertEqual(false, is_extended({string, 10})),\n\n ?assertEqual(true, is_extended({atom, atom})),\n ?assertEqual(false, is_extended({atom, \"atom\"})),\n ?assertEqual(false, is_extended({atom, 10})),\n\n ?assertEqual(true, is_extended({file, \"\/tmp\/foo.txt\"})),\n ?assertEqual(true, is_extended({file, \"\"})),\n ?assertEqual(false, is_extended({file, this})),\n\n ?assertEqual(true, is_extended({directory, \"\/tmp\/foo.txt\"})),\n ?assertEqual(true, is_extended({directory, \"\"})),\n ?assertEqual(false, is_extended({directory, this})),\n\n ?assertEqual(true, is_extended({ip, {\"1.2.3.4\", 1234}})),\n ?assertEqual(false, is_extended({ip, {1234, 1234}})),\n ?assertEqual(false, is_extended({ip, {\"1.2.3.4\", \"1234\"}})),\n\n ?assertEqual(true, is_extended({{duration, f}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, w}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, d}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, g}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, m}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, s}, \"10f\"})),\n ?assertEqual(true, is_extended({{duration, ms}, \"10ms\"})),\n ?assertEqual(true, is_extended({bytesize, \"10GB\"})),\n\n ?assertEqual(true, is_extended({{percent, integer}, \"10%\"})),\n ?assertEqual(true, is_extended({{percent, integer}, 10})),\n ?assertEqual(true, is_extended({{percent, float}, \"10%\"})),\n ?assertEqual(true, is_extended({{percent, float}, 0.1})),\n ?assertEqual(true, is_extended({float, 0.1})),\n ok.\n\n-endif.\n","avg_line_length":39.8111753372,"max_line_length":148,"alphanum_fraction":0.6365308295} +{"size":4886,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(urlfetch_handler).\n\n-behaviour(gen_fsm).\n\n-include(\"urlfetch.hrl\").\n\n-export([start_link\/0, set_socket\/2]).\n\n%% Finite state machine API\n-export([init\/1, handle_event\/3, handle_sync_event\/4, handle_info\/3,\n terminate\/3, code_change\/4]).\n\n-export(['AWAIT_SOCKET'\/2, 'AWAIT_DATA'\/2]).\n\n-record(state, {socket, addr, id}).\n\n\nstart_link() ->\n gen_fsm:start_link(?MODULE, [], []).\n\n\nset_socket(Pid, Socket) when is_pid(Pid), is_port(Socket) ->\n gen_fsm:send_event(Pid, {socket_ready, Socket}).\n\n\ninit([]) ->\n process_flag(trap_exit, true),\n {ok, 'AWAIT_SOCKET', #state{}}.\n\n\n%% Client connects\n'AWAIT_SOCKET'({socket_ready, Socket}, State) when is_port(Socket) ->\n inet:setopts(Socket, [binary, {active, once}]),\n {ok, {IP, _Port}} = inet:peername(Socket),\n error_logger:info_msg(\"~p Client ~p connected.\\n\", [self(), IP]),\n {next_state, 'AWAIT_DATA', State#state{socket=Socket, addr=IP}, ?TIMEOUT};\n'AWAIT_SOCKET'(Other, State) ->\n error_logger:error_msg(\"Unexpected message: ~p\\n\", [Other]),\n {next_state, 'AWAIT_SOCKET', State}.\n\n\n%% Notification event coming from client\n'AWAIT_DATA'({data, Data}, #state{socket=S} = State) ->\n case urlfetch_rpc_parser:parse(Data) of\n {request, <<\"FETCH_ASYNC\">>, MethodString, Url, Payload, Headers} ->\n Id = urlfetch_uuid:new(),\n error_logger:info_msg(\"~p Fetching ~p.~n\", [self(), Url]),\n Method = get_method(MethodString),\n Result = urlfetch_async:fetch({\n Id, Method, binary_to_list(Url), binary_to_list(Payload),\n urlfetch_http:decode_headers(Headers)}),\n case Result of\n ok ->\n gen_tcp:send(S, Id);\n error ->\n gen_tcp:send(S, <<\"ERROR\">>)\n end,\n NewState = State#state{id=Id},\n {next_state, 'AWAIT_DATA', NewState, ?TIMEOUT};\n {request, <<\"GET_RESULT\">>, Id} ->\n case get_result(Id) of\n {result, Result} ->\n gen_tcp:send(S, [pack_result(Result), \"\\tEOF\\n\"]),\n spawn(urlfetch_async, purge, [Id]);\n {error, not_found} ->\n gen_tcp:send(S, pack_result({404, \"NOT_FOUND\"}))\n end,\n {next_state, 'AWAIT_DATA', State, ?TIMEOUT};\n {request, <<\"GET_RESULT_NOWAIT\">>, Id} ->\n case get_result({nowait, Id}) of\n {result, Result} ->\n gen_tcp:send(S, [pack_result(Result), \"\\tEOF\\n\"]),\n spawn(urlfetch_async, purge, [Id]);\n {error, not_found} ->\n gen_tcp:send(S, pack_result({404, \"NOT_FOUND\"}))\n end,\n {next_state, 'AWAIT_DATA', State, ?TIMEOUT};\n {request, _, _} ->\n gen_tcp:send(S, <<\"ERROR\">>),\n {next_state, 'AWAIT_DATA', State, ?TIMEOUT};\n {noreply, _} ->\n gen_tcp:send(S, <<\"ERROR\">>),\n {stop, normal, State}\n end;\n'AWAIT_DATA'(timeout, State) ->\n error_logger:error_msg(\"~p Closing connection (timeout).\\n\", [self()]),\n {stop, normal, State};\n'AWAIT_DATA'(Data, State) ->\n io:format(\"~p Ignoring data: ~p\\n\", [self(), Data]),\n {next_state, 'AWAIT_DATA', State, ?TIMEOUT}.\n\n\nhandle_event(Event, StateName, StateData) ->\n {stop, {StateName, undefined_event, Event}, StateData}.\n\n\nhandle_sync_event(Event, _From, StateName, StateData) ->\n {stop, {StateName, undefined_event, Event}, StateData}.\n\n\nhandle_info({tcp, Socket, Bin}, StateName, #state{socket=Socket} = StateData) ->\n inet:setopts(Socket, [{active, once}]),\n ?MODULE:StateName({data, Bin}, StateData);\nhandle_info({tcp_closed, Socket}, _StateName,\n #state{socket=Socket} = StateData) ->\n {stop, normal, StateData}.\n\n\nterminate(_Reason, _StateName, #state{socket=Socket, addr=Addr}) ->\n (catch gen_tcp:close(Socket)),\n error_logger:info_msg(\"~p Client ~p disconnected.\\n\", [self(), Addr]),\n ok.\n\n\ncode_change(_OldVsn, StateName, StateData, _Extra) ->\n {ok, StateName, StateData}.\n\n\n%% Internal API\n\nget_method(String) ->\n {ok, [{atom, 1, Method}], 1} = erl_scan:string(binary_to_list(String)),\n Method.\n\n\nget_result({nowait, Id}) ->\n case urlfetch_async:get_result(Id) of\n {result, Result} ->\n {result, Result};\n {error, _} ->\n {error, not_found}\n end;\nget_result(Id) ->\n case urlfetch_async:get_result(Id) of\n {result, Result} ->\n {result, Result};\n {error, retry} ->\n timer:sleep(50),\n get_result(Id);\n {error, not_found} ->\n {error, not_found}\n end.\n\n\npack_result(Result) ->\n {Code, Body} = Result,\n case is_binary(Body) of\n true ->\n Data = Body;\n false ->\n Data = list_to_binary(Body)\n end,\n <>.\n","avg_line_length":31.7272727273,"max_line_length":80,"alphanum_fraction":0.5736799018} +{"size":6618,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"-module(riak_core_schema_tests).\n\n-include_lib(\"eunit\/include\/eunit.hrl\").\n-compile(export_all).\n\n%% basic schema test will check to make sure that all defaults from\n%% the schema make it into the generated app.config\nbasic_schema_test() ->\n %% The defaults are defined in ..\/priv\/riak_core.schema. it is the\n %% file under test.\n Config = cuttlefish_unit:generate_templated_config(\n \"..\/priv\/riak_core.schema\", [], context()),\n\n cuttlefish_unit:assert_config(Config, \"riak_core.default_bucket_props.n_val\", 3),\n cuttlefish_unit:assert_config(Config, \"riak_core.ring_creation_size\", 64),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_concurrency\", 2),\n cuttlefish_unit:assert_config(Config, \"riak_core.ring_state_dir\", \".\/data\/ring\"),\n cuttlefish_unit:assert_not_configured(Config, \"riak_core.ssl.certfile\"),\n cuttlefish_unit:assert_not_configured(Config, \"riak_core.ssl.keyfile\"),\n cuttlefish_unit:assert_not_configured(Config, \"riak_core.ssl.cacertfile\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_ip\", \"0.0.0.0\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_port\", 8099 ),\n cuttlefish_unit:assert_not_configured(Config, \"riak_core.handoff_ssl_options\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.dtrace_support\", false),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_bin_dir\", \".\/bin\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_data_dir\", \".\/data\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_etc_dir\", \".\/etc\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_lib_dir\", \".\/lib\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_log_dir\", \".\/log\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.enable_consensus\", false),\n cuttlefish_unit:assert_config(Config, \"riak_core.use_background_manager\", false),\n cuttlefish_unit:assert_config(Config, \"riak_core.vnode_management_timer\", 10000),\n ok.\n\n%% Tests that configurations which should be prohibited by validators defined\n%% in the schema are, in fact, reported as invalid.\ninvalid_states_test() ->\n Conf = [\n {[\"handoff\", \"ip\"], \"0.0.0.0.0\"}\n ],\n\n Config = cuttlefish_unit:generate_templated_config(\"..\/priv\/riak_core.schema\", Conf, context()),\n\n %% Confirm that we made it to validation and test that each expected failure\n %% message is present.\n cuttlefish_unit:assert_error_in_phase(Config, validation),\n cuttlefish_unit:assert_error_message(Config, \"handoff.ip invalid, must be a valid IP address\"),\n ok.\n\n\ndefault_bucket_properties_test() ->\n Conf = [\n {[\"buckets\", \"default\", \"n_val\"], 5}\n ],\n\n Config = cuttlefish_unit:generate_templated_config(\n \"..\/priv\/riak_core.schema\", Conf, context()),\n\n cuttlefish_unit:assert_config(Config, \"riak_core.default_bucket_props.n_val\", 5),\n ok.\n\noverride_schema_test() ->\n %% Conf represents the riak.conf file that would be read in by cuttlefish.\n %% this proplists is what would be output by the conf_parse module\n Conf = [\n {[\"buckets\", \"default\", \"n_val\"], 4},\n {[\"ring_size\"], 8},\n {[\"transfer_limit\"], 4},\n {[\"ring\", \"state_dir\"], \"\/absolute\/ring\"},\n {[\"ssl\", \"certfile\"], \"\/absolute\/etc\/cert.pem\"},\n {[\"ssl\", \"keyfile\"], \"\/absolute\/etc\/key.pem\"},\n {[\"ssl\", \"cacertfile\"], \"\/absolute\/etc\/cacertfile.pem\"},\n {[\"handoff\", \"ip\"], \"1.2.3.4\"},\n {[\"handoff\", \"port\"], 8888},\n {[\"handoff\", \"ssl\", \"certfile\"], \"\/tmp\/erlserver.pem\"},\n {[\"handoff\", \"ssl\", \"keyfile\"], \"\/tmp\/erlkey\/pem\"},\n {[\"dtrace\"], on},\n %% Platform-specific installation paths (substituted by rebar)\n {[\"platform_bin_dir\"], \"\/absolute\/bin\"},\n {[\"platform_data_dir\"],\"\/absolute\/data\" },\n {[\"platform_etc_dir\"], \"\/absolute\/etc\"},\n {[\"platform_lib_dir\"], \"\/absolute\/lib\"},\n {[\"platform_log_dir\"], \"\/absolute\/log\"},\n {[\"strong_consistency\"], on},\n {[\"background_manager\"], on},\n {[\"vnode_management_timer\"], \"20s\"}\n ],\n\n Config = cuttlefish_unit:generate_templated_config(\"..\/priv\/riak_core.schema\", Conf, context()),\n\n cuttlefish_unit:assert_config(Config, \"riak_core.default_bucket_props.n_val\", 4),\n cuttlefish_unit:assert_config(Config, \"riak_core.ring_creation_size\", 8),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_concurrency\", 4),\n cuttlefish_unit:assert_config(Config, \"riak_core.ring_state_dir\", \"\/absolute\/ring\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.ssl.certfile\", \"\/absolute\/etc\/cert.pem\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.ssl.keyfile\", \"\/absolute\/etc\/key.pem\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.ssl.cacertfile\", \"\/absolute\/etc\/cacertfile.pem\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_ip\", \"1.2.3.4\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_port\", 8888),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_ssl_options.certfile\", \"\/tmp\/erlserver.pem\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.handoff_ssl_options.keyfile\", \"\/tmp\/erlkey\/pem\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.dtrace_support\", true),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_bin_dir\", \"\/absolute\/bin\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_data_dir\", \"\/absolute\/data\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_etc_dir\", \"\/absolute\/etc\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_lib_dir\", \"\/absolute\/lib\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.platform_log_dir\", \"\/absolute\/log\"),\n cuttlefish_unit:assert_config(Config, \"riak_core.enable_consensus\", true),\n cuttlefish_unit:assert_config(Config, \"riak_core.use_background_manager\", true),\n cuttlefish_unit:assert_config(Config, \"riak_core.vnode_management_timer\", 20000),\n ok.\n\n%% this context() represents the substitution variables that rebar\n%% will use during the build process. riak_core's schema file is\n%% written with some {{mustache_vars}} for substitution during\n%% packaging cuttlefish doesn't have a great time parsing those, so we\n%% perform the substitutions first, because that's how it would work\n%% in real life.\ncontext() ->\n [\n {handoff_ip, \"0.0.0.0\"},\n {handoff_port, \"8099\"},\n {platform_bin_dir , \".\/bin\"},\n {platform_data_dir, \".\/data\"},\n {platform_etc_dir , \".\/etc\"},\n {platform_lib_dir , \".\/lib\"},\n {platform_log_dir , \".\/log\"}\n ].\n","avg_line_length":51.3023255814,"max_line_length":106,"alphanum_fraction":0.7061045633} +{"size":2435,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%-------------------------------------------------------------------\n%% @doc genesearcher top level supervisor.\n%% @end\n%%%-------------------------------------------------------------------\n\n-module(genesearcher_sup).\n\n-behaviour(supervisor).\n\n-include(\"genesearcher.hrl\").\n\n%% API\n-export([start_link\/0]).\n\n%% Supervisor callbacks\n-export([init\/1]).\n\n-define(SERVER, ?MODULE).\n\n-define(DEFAULT_POOL_SIZE, 5).\n-define(DEFAULT_POOL_MAX_OVERFLOW, 10).\n\n-define(DEFAULT_PORT, 8080).\n-define(DEFAULT_KEEP_ALIVE, true).\n\n%%====================================================================\n%% API functions\n%%====================================================================\n\nstart_link() ->\n supervisor:start_link({local, ?SERVER}, ?MODULE, []).\n\n%%====================================================================\n%% Supervisor callbacks\n%%====================================================================\n\n%% Child :: #{id => Id, start => {M, F, A}}\n%% Optional keys are restart, shutdown, type, modules.\n%% Before OTP 18 tuples must be used to specify a child. e.g.\n%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}\ninit([]) ->\n {PoolOptions, MysqlOptions} = mysql_poolboy_options(),\n MySQLPoolSrv = mysql_poolboy:child_spec(pool1, PoolOptions, MysqlOptions),\n Procs = [MySQLPoolSrv],\n {ok, { {one_for_all, 0, 1}, Procs} }.\n\n%%====================================================================\n%% Internal functions\n%%====================================================================\n\nmysql_poolboy_options() ->\n PoolOptions = [\n {size, genesearcher:get_env(ensembldb_pool_size), ?DEFAULT_POOL_SIZE},\n {max_overflow, genesearcher:get_env(ensembldb_pool_max_overflow, ?DEFAULT_POOL_MAX_OVERFLOW)}\n ],\n MysqlOptions = [\n {host, genesearcher:get_env(ensembldb_host)},\n {port, genesearcher:get_env(ensembldb_port, ?DEFAULT_PORT)},\n {user, genesearcher:get_env(ensembldb_user)},\n {database, genesearcher:get_env(ensembldb_database)},\n {keep_alive, genesearcher:get_env(ensembldb_keep_alive, ?DEFAULT_KEEP_ALIVE)}\n ],\n Password = case genesearcher:get_env(ensembldb_password) of\n undefined -> [];\n Pswd -> [{password, Pswd}]\n end,\n {PoolOptions, MysqlOptions ++ Password}.\n","avg_line_length":35.8088235294,"max_line_length":112,"alphanum_fraction":0.4895277207} +{"size":23078,"ext":"erl","lang":"Erlang","max_stars_count":4.0,"content":"-module(wm_mst).\n\n-behaviour(gen_fsm).\n\n-export([start_link\/1]).\n-export([init\/1, handle_event\/3, handle_sync_event\/4, handle_info\/3, code_change\/4, terminate\/3]).\n-export([activate\/1, find\/2, found\/2, sleeping\/2]).\n\n-include(\"wm_log.hrl\").\n\n-record(mstate,\n {fragm_id :: atom(),\n level :: integer(),\n edge_states = maps:new() :: map(),\n best_edge :: atom(),\n best_wt :: atom() | integer(),\n test_edge :: atom(),\n in_branch :: atom(),\n find_count :: integer(),\n state :: atom(),\n requests_queue = [] :: list(),\n nodes :: list(),\n mst_id :: string()}).\n\n%% ============================================================================\n%% Module API\n%% ============================================================================\n\n-spec start_link([term()]) -> {ok, pid()}.\nstart_link(Args) ->\n gen_fsm:start_link(?MODULE, Args, []).\n\n%% @doc Activate a new MST construction\n-spec activate(pid()) -> ok.\nactivate(Pid) ->\n ?LOG_DEBUG(\"Activate ~p\", [Pid]),\n gen_fsm:send_event(Pid, wakeup).\n\n%% ============================================================================\n%% Server callbacks\n%% ============================================================================\n\n-spec init(term()) ->\n {ok, atom(), term()} |\n {ok, atom(), term(), hibernate | infinity | non_neg_integer()} |\n {stop, term()} |\n ignore.\n-spec handle_event(term(), atom(), term()) ->\n {next_state, atom(), term()} |\n {next_state, atom(), term(), hibernate | infinity | non_neg_integer()} |\n {stop, term(), term()} |\n {stop, term(), term(), term()}.\n-spec handle_sync_event(term(), atom(), atom(), term()) ->\n {next_state, atom(), term()} |\n {next_state, atom(), term(), hibernate | infinity | non_neg_integer()} |\n {reply, term(), atom(), term()} |\n {reply, term(), atom(), term(), hibernate | infinity | non_neg_integer()} |\n {stop, term(), term()} |\n {stop, term(), term(), term()}.\n-spec handle_info(term(), atom(), term()) ->\n {next_state, atom(), term()} |\n {next_state, atom(), term(), hibernate | infinity | non_neg_integer()} |\n {stop, term(), term()}.\n-spec code_change(term(), atom(), term(), term()) -> {ok, term()}.\n-spec terminate(term(), atom(), term()) -> ok.\ninit(Args) ->\n process_flag(trap_exit, true),\n MState = parse_args(Args, #mstate{}),\n ?LOG_INFO(\"MST module has been started (~p)\", [MState#mstate.mst_id]),\n wm_factory:notify_initiated(mst, MState#mstate.mst_id),\n {ok, sleeping, MState}.\n\nhandle_sync_event(_Event, _From, State, MState) ->\n {reply, State, State, MState}.\n\nhandle_event(_Event, State, MState) ->\n {next_state, State, MState}.\n\nhandle_info(_Info, StateName, MState) ->\n {next_state, StateName, MState}.\n\ncode_change(_OldVsn, StateName, MState, _Extra) ->\n {ok, StateName, MState}.\n\nterminate(Status, StateName, MState) ->\n Msg = io_lib:format(\"MST ~p has been terminated (status=~p, state=~p)\", [MState#mstate.mst_id, Status, StateName]),\n wm_utils:terminate_msg(?MODULE, Msg).\n\n%% ============================================================================\n%% FSM state transitions\n%% ============================================================================\n\n-spec sleeping(term(), #mstate{}) -> {atom(), atom(), #mstate{}}.\nsleeping({connect, From, Level}, MState) ->\n ?LOG_DEBUG(\"Received connect from ~p => wake up [sleeping]\", [From]),\n MState2 = wakeup(set_state(found, MState)),\n MState3 = do_connect_resp(From, Level, get_state(MState2), MState2),\n {next_state, get_state(MState3), MState3};\nsleeping(Cmd, MState) ->\n ?LOG_DEBUG(\"Received '~p' => wake up [sleeping]\", [Cmd]),\n MState2 = wakeup(set_state(found, MState)),\n {next_state, get_state(MState2), MState2}.\n\n-spec find(term(), #mstate{}) -> {atom(), atom(), #mstate{}}.\nfind({connect, From, Level}, MState) ->\n ?LOG_DEBUG(\"Received 'connect' (E=~p, L=~p) [find]\", [From, Level]),\n MState2 = do_connect_resp(From, Level, find, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind({initiate, From, Level, FID, NodeState}, MState) ->\n ?LOG_DEBUG(\"Received 'initiate' (E=~p, L=~p) [find]\", [From, Level]),\n MState2 = set_state(find, MState),\n MState3 = do_initiate_resp(From, Level, FID, NodeState, MState2),\n {next_state, get_state(MState3), MState3};\nfind({test, From, Level, FID}, MState) ->\n ?LOG_DEBUG(\"Received 'test' from ~p (L=~p, F=~p) [find]\", [From, Level, FID]),\n MState2 = do_test_resp(From, Level, FID, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind({accept, From}, MState) ->\n ?LOG_DEBUG(\"Received 'accept' from ~p [find]\", [From]),\n MState2 = do_accept_resp(From, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind({reject, From}, MState) ->\n ?LOG_DEBUG(\"Received 'accept' from ~p [find]\", [From]),\n MState2 = do_reject_resp(From, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind({report, From, BestWeight}, MState) ->\n ?LOG_DEBUG(\"Received 'report' from ~p, W=~p [find]\", [From, BestWeight]),\n MState2 = do_report_resp(From, BestWeight, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind({change_root, From}, MState) ->\n ?LOG_DEBUG(\"Received 'change_root' from ~p [find]\", [From]),\n MState2 = do_change_root_resp(From, set_state(find, MState)),\n {next_state, get_state(MState2), MState2};\nfind(wakeup, MState) ->\n {next_state, get_state(MState), MState}.\n\n-spec found(term(), #mstate{}) -> {atom(), atom(), #mstate{}}.\nfound({connect, From, Level}, MState) ->\n ?LOG_DEBUG(\"Received 'connect' (E=~p, L=~p) [found]\", [From, Level]),\n MState2 = do_connect_resp(From, Level, found, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound({initiate, From, Level, Weight, NodeState}, MState) ->\n ?LOG_DEBUG(\"Received 'initiate' (E=~p, L=~p) [found]\", [From, Level]),\n MState2 = set_state(found, MState),\n MState3 = do_initiate_resp(From, Level, Weight, NodeState, MState2),\n {next_state, get_state(MState3), MState3};\nfound({test, From, Level, FID}, MState) ->\n ?LOG_DEBUG(\"Received 'test' (E=~p, L=~p, F=~p) [found]\", [From, Level, FID]),\n MState2 = do_test_resp(From, Level, FID, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound({accept, From}, MState) ->\n ?LOG_DEBUG(\"Received 'accept' from ~p [found]\", [From]),\n MState2 = do_accept_resp(From, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound({reject, From}, MState) ->\n ?LOG_DEBUG(\"Received 'accept' from ~p [found]\", [From]),\n MState2 = do_reject_resp(From, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound({report, From, BestWeight}, MState) ->\n ?LOG_DEBUG(\"Received 'report' from ~p, W=~p [found]\", [From, BestWeight]),\n MState2 = do_report_resp(From, BestWeight, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound({change_root, From}, MState) ->\n ?LOG_DEBUG(\"Received 'change_root' from ~p [found]\", [From]),\n MState2 = do_change_root_resp(From, set_state(found, MState)),\n {next_state, get_state(MState2), MState2};\nfound(wakeup, MState) ->\n {next_state, get_state(MState), MState}.\n\n%% ============================================================================\n%% FSM implementation functions\n%% ============================================================================\n\n-spec parse_args(list(), #mstate{}) -> #mstate{}.\nparse_args([], MState) ->\n MState;\nparse_args([{nodes, Nodes} | T], MState) ->\n parse_args(T, MState#mstate{nodes = Nodes});\nparse_args([{task_id, ID} | T], MState) ->\n parse_args(T, MState#mstate{mst_id = ID});\nparse_args([{_, _} | T], MState) ->\n parse_args(T, MState).\n\n%% ============================================================================\n%% GHS implementation functions\n%% ============================================================================\n\n-spec wakeup(#mstate{}) -> #mstate{}.\nwakeup(MState) ->\n ?LOG_INFO(\"Wake up and explore nodes constructing new MST\"),\n case MState#mstate.nodes of\n [] ->\n do_halt(MState);\n Edges ->\n MState2 = init_edge_states(Edges, MState),\n MState3 =\n MState2#mstate{level = 0,\n find_count = 0,\n fragm_id = node()},\n case try_connect(Edges, unknown, MState3) of\n {connected, MState4} ->\n ?LOG_DEBUG(\"Connected, MState=~s\", [format_mstate(MState4)]),\n MState4;\n {not_connected, MState4} ->\n ?LOG_DEBUG(\"Cannot send 'connect' to any of ~p\", [Edges]),\n do_halt(MState4)\n end\n end.\n\n%------------------------------- CONNECT\n\n-spec try_connect([atom()], term(), #mstate{}) -> {connected, #mstate{}} | {not_connected, #mstate{}}.\ntry_connect(_, {true, Edge}, MState) ->\n {connected, set_edge_state(Edge, branch, MState)};\ntry_connect([], _, MState) ->\n {not_connected, MState};\ntry_connect([Edge | T], _, MState) ->\n Result = send({connect, node(), MState#mstate.level}, Edge, MState),\n ?LOG_DEBUG(\"Sending 'connect' to ~p result: ~p\", [Edge, Result]),\n try_connect(T, Result, MState).\n\n-spec do_connect_resp(atom(), integer(), atom(), #mstate{}) -> #mstate{}.\ndo_connect_resp(Edge, Level, NodeState, MState) when Level < MState#mstate.level ->\n ?LOG_DEBUG(\"Connect respond: E=~p, L=~p<~p\", [Edge, Level, MState#mstate.level]),\n MState2 = set_edge_state(Edge, branch, MState),\n try_initiate(Edge, NodeState, MState2),\n case NodeState of\n find ->\n MState2#mstate{find_count = MState2#mstate.find_count + 1};\n _ ->\n MState2\n end;\ndo_connect_resp(Edge,\n Level,\n _,\n MState) -> %% Level >= MState#mstate.level\n ?LOG_DEBUG(\"Connect respond: E=~p, L=~p\", [Edge, Level]),\n case get_edge_state(Edge, MState) of\n basic ->\n queue_request({connect, Edge, Level}, MState);\n _ ->\n try_initiate(Edge, find, MState#mstate{level = MState#mstate.level + 1}),\n MState\n end.\n\n%------------------------------- INITIATE\n\n-spec try_initiate(atom(), atom(), #mstate{}) -> #mstate{}.\ntry_initiate(Edge, NodeState, MState) ->\n ?LOG_DEBUG(\"Initiate ~p (S=~p)\", [Edge, NodeState]),\n FID = MState#mstate.fragm_id,\n send({initiate, node(), MState#mstate.level, FID, NodeState}, Edge, MState).\n\n-spec do_initiate_resp(atom(), integer(), atom(), atom(), #mstate{}) -> #mstate{}.\ndo_initiate_resp(From, Level, FID, NodeState, MState) ->\n ?LOG_DEBUG(\"Respond to 'initiate' from ~p\", [From]),\n {ok, RemoteNode} = wm_conf:select_node(atom_to_list(FID)),\n {ok, MyNodeId} = wm_self:get_node_id(),\n RemoteLeaderID = wm_entity:get_attr(id, RemoteNode),\n {InBranch, NewFID, FC} =\n case RemoteLeaderID < MyNodeId of\n true ->\n {From, FID, MState#mstate.find_count};\n false ->\n {none, node(), MState#mstate.find_count + 1}\n end,\n ?LOG_DEBUG(\"New FID=~p (id2=~p, id1=~p)\", [NewFID, RemoteLeaderID, MyNodeId]),\n ?LOG_DEBUG(\"Old\/new levels: ~p\/~p\", [MState#mstate.level, Level]),\n MState2 =\n MState#mstate{fragm_id = NewFID,\n level = Level,\n in_branch = InBranch,\n best_edge = none,\n state = NodeState,\n best_wt = infinity,\n find_count = FC},\n MState3 =\n case MState#mstate.level =\/= Level of\n true ->\n handle_queued_requests(MState2);\n _ ->\n MState2\n end,\n F = fun (Edge, branch, FindCount) when From =\/= Edge ->\n try_initiate(Edge, NodeState, MState3),\n case NodeState of\n find ->\n FindCount + 1;\n _ ->\n FindCount\n end;\n (_, _, FindCount) ->\n FindCount\n end,\n FindCount = maps:fold(F, MState3#mstate.find_count, MState3#mstate.edge_states),\n MState4 = MState3#mstate{find_count = FindCount},\n case NodeState of\n find ->\n try_test(Level, NewFID, MState4);\n _ ->\n MState4\n end.\n\n%------------------------------- TEST\n\n-spec try_test(integer(), atom(), #mstate{}) -> #mstate{}.\ntry_test(Level, FID, MState) ->\n ?LOG_DEBUG(\"Run procedure 'test': L=~p, ID=~p\", [Level, FID]),\n F = fun ({_, basic}) ->\n true;\n (_) ->\n false\n end,\n Pairs = lists:filter(F, maps:to_list(MState#mstate.edge_states)),\n EdgesBasic = [X || {X, _} <- Pairs],\n Msg = {test, node(), MState#mstate.level, MState#mstate.fragm_id},\n MState3 =\n case send_to_min_weight_edge(Msg, EdgesBasic, MState) of\n {false, NewMState} ->\n try_report(NewMState#mstate{test_edge = none});\n {true, NewMState} ->\n NewMState\n end,\n ?LOG_DEBUG(\"Test procedure finished, MState=~s\", [format_mstate(MState3)]),\n MState3.\n\n-spec do_test_resp(atom(), integer(), atom(), #mstate{}) -> #mstate{}.\ndo_test_resp(From, Level, FID, MState) when Level > MState#mstate.level ->\n ?LOG_DEBUG(\"Respond to 'test' from ~p (L=~p, FID=~p)\", [From, Level, FID]),\n queue_request({test, From, Level, FID}, MState);\ndo_test_resp(From, Level, FID, MState) when FID =\/= MState#mstate.fragm_id ->\n ?LOG_DEBUG(\"Respond to 'test' from ~p (L=~p, FID=~p)\", [From, Level, FID]),\n try_accept(From, MState);\ndo_test_resp(From, Level, FID, MState) ->\n ?LOG_DEBUG(\"Respond to 'test' from ~p (L=~p, FID=~p)\", [From, Level, FID]),\n MState2 = set_edge_rejected_if_basic(From, MState),\n case MState2#mstate.test_edge of\n From ->\n try_test(MState2#mstate.level, MState2#mstate.fragm_id, MState2);\n _ ->\n try_reject(From, MState2)\n end.\n\n%------------------------------- ACCEPT\n\n-spec try_accept(atom(), #mstate{}) -> #mstate{}.\ntry_accept(Edge, MState) ->\n ?LOG_DEBUG(\"Run procedure 'accept' on edge ~p\", [Edge]),\n send({accept, node()}, Edge, MState),\n MState.\n\n-spec do_accept_resp(atom(), #mstate{}) -> #mstate{}.\ndo_accept_resp(From, MState) ->\n ?LOG_DEBUG(\"Respond to 'accept' from ~p\", [From]),\n MState2 = MState#mstate{test_edge = none},\n Weight = wm_topology:get_latency(node(), From),\n MState3 =\n if Weight < MState2#mstate.best_wt ->\n MState2#mstate{best_edge = From, best_wt = Weight};\n true ->\n MState2\n end,\n try_report(MState3).\n\n%------------------------------- REJECT\n\n-spec try_reject(atom(), #mstate{}) -> #mstate{}.\ntry_reject(Edge, MState) ->\n ?LOG_DEBUG(\"Run procedure 'reject' on edge ~p\", [Edge]),\n send({reject, node()}, Edge, MState),\n MState.\n\n-spec do_reject_resp(atom(), #mstate{}) -> #mstate{}.\ndo_reject_resp(From, MState) ->\n ?LOG_DEBUG(\"Respond to 'reject' from ~p\", [From]),\n MState2 = set_edge_rejected_if_basic(From, MState),\n try_test(MState2#mstate.level, MState2#mstate.fragm_id, MState2).\n\n%------------------------------- REPORT\n\n-spec try_report(#mstate{}) -> #mstate{}.\ntry_report(MState) ->\n ?LOG_DEBUG(\"Run procedure 'report', mstate=~s\", [format_mstate(MState)]),\n if MState#mstate.find_count == 0, MState#mstate.test_edge == none ->\n case MState#mstate.in_branch of\n none ->\n ?LOG_DEBUG(\"My in-branch is looped and all find-branches\"\n ++ \" were reported to me, so lets halt the algorithm\"),\n set_state(found, MState),\n do_halt(MState);\n _ ->\n ?LOG_DEBUG(\"Report ~p: links are tested\", [MState#mstate.in_branch]),\n Msg = {report, node(), MState#mstate.best_wt},\n send(Msg, MState#mstate.in_branch, MState),\n set_state(found, MState)\n end;\n true ->\n MState\n end.\n\n-spec do_report_resp(atom(), atom() | integer(), #mstate{}) -> #mstate{}.\ndo_report_resp(From, RBestWeight, MState) when From =\/= MState#mstate.in_branch ->\n ?LOG_DEBUG(\"Respond to 'report' from ~p (W=~p)\", [From, RBestWeight]),\n MState2 = MState#mstate{find_count = MState#mstate.find_count - 1},\n MState3 =\n case RBestWeight < MState2#mstate.best_wt of\n true ->\n MState2#mstate{best_wt = RBestWeight, best_edge = From};\n _ ->\n MState2\n end,\n try_report(MState3);\ndo_report_resp(From, RBestWeight, MState) when MState#mstate.state == find ->\n ?LOG_DEBUG(\"Respond to 'report' from ~p (W=~p)\", [From, RBestWeight]),\n queue_request({report, From, RBestWeight}, MState);\ndo_report_resp(From, RBestWeight, MState) ->\n ?LOG_DEBUG(\"Respond to 'report' from ~p (W=~p)\", [From, RBestWeight]),\n case RBestWeight > MState#mstate.best_wt of\n true ->\n do_change_root(From, MState);\n _ ->\n case RBestWeight of\n infinity when MState#mstate.best_wt == infinity ->\n do_halt(MState);\n _ ->\n MState\n end\n end.\n\n%------------------------------- CHANGE_ROOT\n\n-spec do_change_root(atom(), #mstate{}) -> #mstate{}.\ndo_change_root(Edge, MState) ->\n ?LOG_DEBUG(\"Change root: ~p\", [Edge]),\n case get_edge_state(Edge, MState) of\n branch ->\n send({change_root, Edge}, MState#mstate.best_edge, MState),\n MState;\n _ ->\n Me = node(),\n send({connect, Me, MState#mstate.level}, MState#mstate.best_edge, MState),\n set_edge_state(MState#mstate.best_edge, branch, MState)\n end.\n\n-spec do_change_root_resp(atom(), #mstate{}) -> #mstate{}.\ndo_change_root_resp(From, MState) ->\n ?LOG_DEBUG(\"Respond to 'change_root' from ~p\", [From]),\n do_change_root(From, MState).\n\n-spec do_halt(#mstate{}) -> #mstate{}.\ndo_halt(MState) ->\n ?LOG_DEBUG(\"Do halt the algorithm, MST has been found with a single leader\"),\n MyAddr = wm_conf:get_my_address(),\n wm_event:announce(wm_mst_done, {MState#mstate.mst_id, {node, MyAddr}}),\n MState.\n\n%% ============================================================================\n%% Helper functions\n%% ============================================================================\n\n-spec queue_request(term(), #mstate{}) -> #mstate{}.\nqueue_request(Msg, MState) ->\n ?LOG_DEBUG(\"Put the request back to events queue: ~p\", [Msg]),\n NewQueue = [Msg | MState#mstate.requests_queue],\n MState#mstate{requests_queue = NewQueue}.\n\n-spec handle_queued_requests(#mstate{}) -> #mstate{}.\nhandle_queued_requests(MState) ->\n ?LOG_DEBUG(\"Requests queue: ~p\", [MState#mstate.requests_queue]),\n QueueSize = length(MState#mstate.requests_queue),\n ?LOG_DEBUG(\"Handle ~p queued requests\", [QueueSize]),\n F = fun(QueuedRequest) -> ok = gen_fsm:send_event(self(), QueuedRequest) end,\n [F(X) || X <- lists:reverse(MState#mstate.requests_queue)],\n MState#mstate{requests_queue = []}.\n\n-spec init_edge_states([atom()], #mstate{}) -> #mstate{}.\ninit_edge_states(Edges, MState) ->\n F = fun(E, MStateAcc) -> set_edge_state(E, basic, MStateAcc) end,\n lists:foldl(F, MState#mstate{edge_states = maps:new()}, Edges).\n\n-spec send(term(), atom(), #mstate{}) -> {term(), atom()}.\nsend(Msg, Edge, MState) ->\n Result = wm_factory:send_confirm(mst, one_state, MState#mstate.mst_id, Msg, [Edge]),\n {Result, Edge}.\n\n-spec send_to_min_weight_edge(term(), [atom()], #mstate{}) -> {boolean(), #mstate{}}.\nsend_to_min_weight_edge(Msg, [], MState2) ->\n ?LOG_DEBUG(\"No more min-weight edges are available to send ~p\", Msg),\n {false, MState2};\nsend_to_min_weight_edge(Msg, Edges, MState) ->\n ?LOG_DEBUG(\"Send ~p to min-weight edge (edges set: ~p)\", [Msg, Edges]),\n case wm_topology:get_min_latency_to(Edges) of\n {} ->\n ?LOG_DEBUG(\"No edges were found\"),\n {false, MState};\n {Edge, Weight} ->\n ?LOG_DEBUG(\"Minimum weight edge is ~p (W=~p)\", [Edge, Weight]),\n case send(Msg, Edge, MState) of\n {true, Edge} ->\n {true, MState#mstate{test_edge = Edge}};\n Error ->\n RemainingEdges = Edges -- [Edge],\n ?LOG_DEBUG(\"Failed to send ~p to ~p: ~p (remaining edges: ~p)\", [Msg, Edge, Error, RemainingEdges]),\n MState2 = set_edge_state(Edge, rejected, MState),\n send_to_min_weight_edge(Msg, RemainingEdges, MState2)\n end\n end.\n\n-spec get_edge_state(atom(), #mstate{}) -> map().\nget_edge_state(Edge, MState) ->\n maps:get(Edge, MState#mstate.edge_states).\n\n-spec set_edge_rejected_if_basic(atom(), #mstate{}) -> #mstate{}.\nset_edge_rejected_if_basic(Edge, MState) ->\n case get_edge_state(Edge, MState) of\n basic ->\n set_edge_state(Edge, rejected, MState);\n _ ->\n MState\n end.\n\n-spec set_edge_state(atom(), atom(), #mstate{}) -> #mstate{}.\nset_edge_state(Edge, basic, MState) ->\n NewMap = maps:put(Edge, basic, MState#mstate.edge_states),\n MState#mstate{edge_states = NewMap};\nset_edge_state(Edge, EdgeState, MState) ->\n MState2 = handle_queued_requests(MState),\n NewMap = maps:put(Edge, EdgeState, MState2#mstate.edge_states),\n MState#mstate{edge_states = NewMap}.\n\n-spec get_state(#mstate{}) -> atom().\nget_state(MState) ->\n MState#mstate.state.\n\n-spec set_state(atom(), #mstate{}) -> #mstate{}.\nset_state(State, MState) ->\n MState2 = MState#mstate{state = State},\n case MState#mstate.state =\/= MState2#mstate.state of\n true ->\n handle_queued_requests(MState2);\n false ->\n MState2\n end.\n\n-spec format_mstate(#mstate{}) -> string().\nformat_mstate(MState) ->\n io_lib:format(\"fragm_id=~p level=~p edge_states=~p best_edge=~p best_wt=~p test_edge=~p \"\n \"in_branch=~p find_count=~p state=~p queuesize=~p id=~p\",\n [MState#mstate.fragm_id,\n MState#mstate.level,\n maps:to_list(MState#mstate.edge_states),\n MState#mstate.best_edge,\n MState#mstate.best_wt,\n MState#mstate.test_edge,\n MState#mstate.in_branch,\n MState#mstate.find_count,\n MState#mstate.state,\n length(MState#mstate.requests_queue),\n MState#mstate.mst_id]).\n","avg_line_length":41.2107142857,"max_line_length":120,"alphanum_fraction":0.5611838114} +{"size":6404,"ext":"erl","lang":"Erlang","max_stars_count":32.0,"content":"%%-----------------------------------------------------------------------------\n%% @copyright (C) 2019, Matthew Pope\n%% @author Matthew Pope\n%% @doc Interface for the xor16 filter.\n%%\n%% Shorthand for the `exor_filter' module. For indepth documentation, see\n%% that module.\n%%\n%% Example usage:\n%% ```\n%% Filter = xor16:new([\"cat\", \"dog\", \"mouse\"]),\n%% true = xor16:contain(Filter, \"cat\"),\n%% false = xor16:contain(Filter, \"goose\"),\n%% '''\n%% @end\n%%-----------------------------------------------------------------------------\n-module(xor16).\n\n-export([\n new\/1,\n new\/2,\n new_buffered\/1,\n new_buffered\/2,\n new_empty\/0,\n add\/2,\n finalize\/1,\n contain\/2,\n contain\/3,\n to_bin\/1,\n from_bin\/1\n]).\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes the xor filter, and runs the default hash function on\n%% each of the elements in the list. This should be fine for the general case.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec new(list()) -> {reference(), atom()} | {error, atom()}.\n\nnew(List) ->\n exor_filter:xor16(List).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes the xor filter, and runs the specified hash on each of \n%% the elements in the list. \n%%\n%% The option `default_hash' uses the `erlang:phash2\/1' function.\n%% The option `none' is for prehashed data.\n%% A fun can be passed that will be applied to each element.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec new(list(), exor_filter:hash_function()) -> \n {reference(), exor_filter:hash_function()} | {error, atom()}.\n\nnew(List, HashFunction) ->\n exor_filter:xor16(List, HashFunction).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes the xor filter, and runs the default hash function on\n%% each of the elements in the list. This is the buffered version, meant for\n%% large filters.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec new_buffered(list()) -> {reference(), atom()} | {error, atom()}.\n\nnew_buffered(List) ->\n exor_filter:xor16_buffered(List).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes an empty filter. Can be filled incrementally, and is\n%% more memory efficient than storing entire data set in the Erlang VM.\n%% Initializes the filter to 64 elements, but will be dynamically expanded\n%% if more elements are added.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec new_empty() -> {builder, reference()}.\n\nnew_empty() ->\n exor_filter:exor_empty().\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Adds elements to filter, and applys the default hashing mechanism.\n%% Dynamically re-sizes filter if needed.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec add({builder, reference()}, list()) -> {builder, reference()}.\n\nadd(Filter, Elements) ->\n\n SortedElements = lists:sort(Elements),\n exor_filter:exor_add(Filter, SortedElements).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes filter internally, and frees data buffer. Equivalent to\n%% calling `xor16:new'.\n%% Deduplication is not done, `finalize' will fail if duplicates are inserted.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec finalize({builder, reference()}) -> reference().\n\nfinalize(Filter) ->\n exor_filter:xor16_finalize(Filter).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Initializes the xor filter, and runs the default hash function on\n%% each of the elements in the list. This is the buffered version, meant for\n%% large filters. See the `xor16:new\/2' or `exor_filter:xor16_new\/2' funtions\n%% for more indepth documentaiton.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec new_buffered(list(), exor_filter:hash_function()) \n -> {reference(), exor_filter:hash_function()} | {error, atom()}.\n\nnew_buffered(List, HashFunction) ->\n exor_filter:xor16_buffered(List, HashFunction).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Tests to see if the passed argument is in the filter. The first\n%% argument must be the pre-initialized filter.\n%%\n%% A filter previously serialized by `to_bin' is allowed\n%% @end\n%%-----------------------------------------------------------------------------\n-spec contain({reference() | binary(), exor_filter:hash_function()}, term()) -> true | false.\n\ncontain(Filter, Key) ->\n exor_filter:xor16_contain(Filter, Key).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Tests to see if the passed argument is in the filter. The first\n%% argument must be the pre-initialized filter.\n%%\n%% A filter previously serialized by `to_bin' is allowed\n%%\n%% Will return the third argument if the element doesn't exist in the filter.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec contain({reference() | binary(), exor_filter:hash_function()}, term(), any()) -> true | any().\n\ncontain(Filter, Key, ReturnValue) ->\n exor_filter:xor16_contain(Filter, Key, ReturnValue).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Serializes the filter to a binary that can be later be deserialized with\n%% `from_bin\/1'.\n%%\n%% Returns `{binary(), hash_function()}'.\n%% @end\n%%-----------------------------------------------------------------------------\n-spec to_bin({reference(), exor_filter:hash_function()}) -> {binary(), exor_filter:hash_function()}.\n\nto_bin(Filter) ->\n exor_filter:xor16_to_bin(Filter).\n\n\n%%-----------------------------------------------------------------------------\n%% @doc Deserializes a filter previously serialized with `to_bin'.\n%%\n%% @end\n%%-----------------------------------------------------------------------------\n-spec from_bin({binary(), exor_filter:hash_function()})\n -> {reference(), exor_filter:hash_function()}.\n\nfrom_bin({Filter, Hash}) ->\n exor_filter:xor16_from_bin({Filter, Hash}).\n","avg_line_length":36.5942857143,"max_line_length":100,"alphanum_fraction":0.4846970643} +{"size":1601,"ext":"erl","lang":"Erlang","max_stars_count":10.0,"content":"-module(webutil).\n\n-export([ template\/2\n , html_escape\/1\n , logged_in\/1\n , create_hash\/1\n ]).\n\n-spec template(FileName :: file:filename(), ArgList :: [string()]) -> Html :: binary().\n%% @doc Reads an html file from its complete path name, and inserts strings without escaping `<' or `>'.\ntemplate(FileName, ArgList) ->\n {ok, Binary} = file:read_file(FileName),\n io_lib:format(Binary, ArgList).\n\n-spec html_escape(ArgList :: [string()]) -> EscapedList :: [string()].\n%% @doc Makes input text \"safe\" by replacing `<' with `<' and `>' with `>'.\nhtml_escape(ArgList) ->\n lists:map(fun(Html) -> \n string:replace(string:replace(Html, \"<\", \"<\", all), \">\", \">\", all)\n end, \n ArgList\n).\n\n-spec create_hash(Input::binary()) -> Hexdigest :: string().\n%% @doc Rehash the hexdigest read from browser cookie and return as a new hexdigest.\ncreate_hash(Binary) ->\n Salt = \"Some very long randomly generated string\",\n <> = crypto:mac(hmac, sha256, Salt, Binary),\n string:lowercase(integer_to_binary(I, 16)).\n\n-spec logged_in(Req :: cowboy_req:req()) -> Name::binary() | false.\n%% @doc if the user is logged in, return their name, else return false.\nlogged_in(Req) ->\n #{user_id := Hash} = cowboy_req:match_cookies([{user_id, [], false}], Req),\n if\n Hash =:= false -> false;\n true ->\n #{num_rows := NumRows, rows := Rows} = \n pgo:query(\"SELECT name FROM users WHERE id=$1::text\", [create_hash(Hash)]),\n case NumRows of\n 0 -> false;\n 1 -> [{Name}] = Rows,\n Name\n end\n end.\n\n\n","avg_line_length":33.3541666667,"max_line_length":104,"alphanum_fraction":0.6039975016} +{"size":1547,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(ataxia_time).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% TYPES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n-type type() :: (never | calendar:datetime()).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% EXPORTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n-export_type([type\/0]).\n\n-export\n(\n [\n never\/0,\n now\/0,\n in\/1\n ]\n).\n\n-export\n(\n [\n is_past\/1,\n to_string\/1\n ]\n).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% LOCAL FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% EXPORTED FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n-spec is_past (type()) -> boolean().\nis_past (never) -> false;\nis_past (_Time) -> true.\n\n-spec never () -> type().\nnever () -> never.\n\n-spec now () -> type().\nnow () -> never.\n\n-spec in (non_neg_integer()) -> type().\nin (_Seconds) -> never.\n\n-spec to_string (type()) -> binary().\nto_string (never) -> <<\"Never\">>;\nto_string (_Date) -> <<\"At some point\">>.\n","avg_line_length":29.1886792453,"max_line_length":80,"alphanum_fraction":0.2275371687} +{"size":1550,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"-module (web_continuations).\n-include (\"wf.inc\").\n-export ([main\/0, event\/1, continue\/2]).\n\nmain() ->\n\tTitle = \"Continuations\",\n\tBody = #template { file=onecolumn, title=Title, headline=Title, section1=[\n\n\t\t\"\n\t\t\tA Nitrogen continuation lets you kick off a long running-function\n\t\t\ton the server and have the browser periodically check in\n\t\t\tto see if it is finished.\n\t\t\t

\n\t\t\tYou can also set a timeout, where the server basically just throws\n\t\t\tup it's hands after X seconds.\n\t\t\",\n\t\t#p{},\n\t\t\n\t\t#button { text=\"Start a 1 second task.\", postback={continue, \"1 Second Task\", 1, 20} },\n\t\t#p{},\n\t\t\n\t\t#button { text=\"Start a 3 second task.\", postback={continue, \"3 Second Task\", 3, 20} }, \n\t\t#p{},\n\t\t\n\t\t#button { text=\"Start a 5 second task.\", postback={continue, \"5 Second Task\", 5, 20} }, \n\t\t#p{},\n\n\t\t#button { text=\"Start a 60 second task that times out after 3 seconds.\", postback={continue, \"60 Second Task\", 100, 3} }\n\n\t]},\n\t\n\twf:render(Body).\n\nevent({continue, Description, DelaySeconds, TimeoutSeconds}) ->\n\twf:flash(\"Started the task...\"),\n\tF = fun() -> long_running_function(DelaySeconds) end,\n\twf:continue({continue, Description}, F, 100, TimeoutSeconds * 1000);\n\nevent(_) -> ok.\n\ncontinue({continue, Description}, timeout) ->\n\tMessage = wf:f(\"Task '~s' timed out.\", [Description]),\n\twf:flash(Message);\n\ncontinue({continue, Description}, _Result) ->\n\tMessage = wf:f(\"Finished the task: '~s'\", [Description]),\n\twf:flash(Message).\n\t\nlong_running_function(Duration) ->\n\t% Do a lot of hard work here.\n\treceive \n\tafter Duration * 1000 -> ok\n\tend.\n\t","avg_line_length":28.7037037037,"max_line_length":122,"alphanum_fraction":0.6612903226} +{"size":182068,"ext":"erl","lang":"Erlang","max_stars_count":13.0,"content":"%% \n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2003-2016. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%% \n\n%%----------------------------------------------------------------------\n%% Purpose:\n%%\n%% Test: ts:run(snmp, snmp_manager_test, [batch]).\n%% Test: ts:run(snmp, snmp_manager_test, event_tests, [batch]).\n%% Test: ts:run(snmp, snmp_manager_test, inform_swarm, [batch]).\n%% \n%%----------------------------------------------------------------------\n-module(snmp_manager_test).\n\n%%----------------------------------------------------------------------\n%% Include files\n%%----------------------------------------------------------------------\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n-include(\"snmp_test_lib.hrl\").\n-include(\"snmp_test_data\/Test2.hrl\").\n\n-include_lib(\"snmp\/include\/snmp_types.hrl\").\n-include_lib(\"snmp\/include\/STANDARD-MIB.hrl\").\n-include_lib(\"snmp\/src\/manager\/snmpm_internal.hrl\").\n\n\n%%----------------------------------------------------------------------\n%% External exports\n%%----------------------------------------------------------------------\n-export([\n\t all\/0, \n\t groups\/0, \n\t init_per_group\/2, end_per_group\/2, \n init_per_testcase\/2, end_per_testcase\/2,\n\n\t init_per_suite\/1, end_per_suite\/1, \n\n\t\n\t simple_start_and_stop1\/1,\n\t simple_start_and_stop2\/1,\n\t simple_start_and_monitor_crash1\/1,\n\t simple_start_and_monitor_crash2\/1,\n\t notify_started01\/1,\n\t notify_started02\/1,\n\n\t register_user1\/1,\n\t\n\t register_agent1\/1,\n\t register_agent2\/1,\n\t register_agent3\/1,\n\n\t info\/1,\n\t \n\t simple_sync_get1\/1, \n\t simple_sync_get2\/1, \n\t simple_sync_get3\/1, \n\t simple_async_get1\/1, \n\t simple_async_get2\/1, \n\t simple_async_get3\/1, \n\t\n \t simple_sync_get_next1\/1, \n \t simple_sync_get_next2\/1, \n \t simple_sync_get_next3\/1, \n \t simple_async_get_next1\/1, \n \t simple_async_get_next2\/1, \n \t simple_async_get_next3\/1, \n\t \n\t simple_sync_set1\/1, \n\t simple_sync_set2\/1, \n\t simple_sync_set3\/1, \n\t simple_async_set1\/1, \n\t simple_async_set2\/1, \n\t simple_async_set3\/1, \n\t \n \t simple_sync_get_bulk1\/1, \n \t simple_sync_get_bulk2\/1, \n \t simple_sync_get_bulk3\/1, \n \t simple_async_get_bulk1\/1, \n \t simple_async_get_bulk2\/1, \n \t simple_async_get_bulk3\/1, \n\t \n \t misc_async1\/1, \n \t misc_async2\/1, \n\n\t discovery\/1,\n\t \n\t trap1\/1,\n\t trap2\/1,\n\n\t inform1\/1,\n\t inform2\/1,\n\t inform3\/1,\n\t inform4\/1,\n\t inform_swarm\/1,\n\n\t report\/1,\n\n\t otp8015_1\/1, \n\t\n\t otp8395_1\/1\n\n\t]).\n\n\n%%----------------------------------------------------------------------\n%% Internal exports\n%%----------------------------------------------------------------------\n\n%% -export([async_exec\/2]).\n\n\n%%----------------------------------------------------------------------\n%% Macros and constants\n%%----------------------------------------------------------------------\n\n-define(AGENT_PORT, 4000).\n-define(AGENT_MMS, 1024).\n-define(AGENT_ENGINE_ID, \"agentEngine\").\n\n-define(MGR_PORT, 5000).\n-define(MGR_MMS, 1024).\n-define(MGR_ENGINE_ID, \"mgrEngine\").\n\n-define(NS_TIMEOUT, 10000).\n\n-define(DEFAULT_MNESIA_DEBUG, none).\n\n\n%%----------------------------------------------------------------------\n%% Records\n%%----------------------------------------------------------------------\n\n%%======================================================================\n%% External functions\n%%======================================================================\n\ninit_per_suite(Config0) when is_list(Config0) ->\n\n ?DBG(\"init_per_suite -> entry with\"\n\t \"~n Config0: ~p\", [Config0]),\n\n Config1 = snmp_test_lib:init_suite_top_dir(?MODULE, Config0), \n Config2 = snmp_test_lib:fix_data_dir(Config1),\n\n %% Mib-dirs\n %% data_dir is trashed by the test-server \/ common-test\n %% so there is no point in fixing it...\n MibDir = snmp_test_lib:lookup(data_dir, Config2),\n StdMibDir = filename:join([code:priv_dir(snmp), \"mibs\"]),\n\n [{mib_dir, MibDir}, {std_mib_dir, StdMibDir} | Config2].\n\nend_per_suite(Config) when is_list(Config) ->\n\n ?DBG(\"end_per_suite -> entry with\"\n\t \"~n Config: ~p\", [Config]),\n\n Config.\n\n\ninit_per_testcase(Case, Config) when is_list(Config) ->\n io:format(user, \"~n~n*** INIT ~w:~w ***~n~n\", [?MODULE, Case]),\n p(Case, \"init_per_testcase begin when\"\n \"~n Nodes: ~p~n~n\", [erlang:nodes()]),\n %% This version of the API, based on Addr and Port, has been deprecated\n DeprecatedApiCases = \n\t[\n\t simple_sync_get1, \n\t simple_async_get1, \n\t simple_sync_get_next1, \n\t simple_async_get_next1, \n\t simple_sync_set1, \n\t simple_async_set1, \n\t simple_sync_get_bulk1, \n\t simple_async_get_bulk1,\n\t misc_async1\n\t],\n Result = \n\tcase lists:member(Case, DeprecatedApiCases) of\n\t true ->\n\t\t%% ?SKIP(api_no_longer_supported);\n\t\t{skip, api_no_longer_supported};\n\t false ->\n\t\tinit_per_testcase2(Case, Config)\n\tend,\n p(Case, \"init_per_testcase end when\"\n \"~n Nodes: ~p\"\n \"~n Result: ~p\"\n \"~n~n\", [Result, erlang:nodes()]),\n Result.\n\ninit_per_testcase2(Case, Config) ->\n ?DBG(\"init_per_testcase2 -> \"\n\t \"~n Case: ~p\"\n\t \"~n Config: ~p\"\n\t \"~n Nodes: ~p\", [Case, Config, erlang:nodes()]),\n\n CaseTopDir = snmp_test_lib:init_testcase_top_dir(Case, Config), \n\n %% -- Manager dirs --\n MgrTopDir = filename:join(CaseTopDir, \"manager\/\"), \n ?DBG(\"init_per_testcase2 -> try create manager top dir: ~n~p\", \n\t [MgrTopDir]),\n ?line ok = file:make_dir(MgrTopDir),\n\n MgrConfDir = filename:join(MgrTopDir, \"conf\/\"),\n ?line ok = file:make_dir(MgrConfDir),\n\n MgrDbDir = filename:join(MgrTopDir, \"db\/\"),\n ?line ok = file:make_dir(MgrDbDir),\n\n MgrLogDir = filename:join(MgrTopDir, \"log\/\"),\n ?line ok = file:make_dir(MgrLogDir),\n\n %% -- Agent dirs --\n AgTopDir = filename:join(CaseTopDir, \"agent\/\"),\n ?line ok = file:make_dir(AgTopDir),\n\n AgConfDir = filename:join(AgTopDir, \"conf\/\"),\n ?line ok = file:make_dir(AgConfDir),\n\n AgDbDir = filename:join(AgTopDir, \"db\/\"),\n ?line ok = file:make_dir(AgDbDir),\n\n AgLogDir = filename:join(AgTopDir, \"log\/\"),\n ?line ok = file:make_dir(AgLogDir),\n\n Family = proplists:get_value(ipfamily, Config, inet),\n\n Conf = [{watchdog, ?WD_START(?MINS(5))},\n\t {ipfamily, Family},\n\t {ip, ?LOCALHOST(Family)},\n\t {case_top_dir, CaseTopDir},\n\t {agent_dir, AgTopDir},\n\t {agent_conf_dir, AgConfDir},\n\t {agent_db_dir, AgDbDir},\n\t {agent_log_dir, AgLogDir}, \n\t {manager_agent_target_name, \"agent01\"}, \n\t {manager_dir, MgrTopDir},\n\t {manager_conf_dir, MgrConfDir},\n\t {manager_db_dir, MgrDbDir},\n\t {manager_log_dir, MgrLogDir} | Config],\n Conf2 = init_per_testcase3(Case, Conf),\n ?DBG(\"init [~w] Nodes [2]: ~p\", [Case, erlang:nodes()]),\n Conf2.\n\ninit_per_testcase3(Case, Config) ->\n ApiCases02 = \n\t[\n\t simple_sync_get2, \n\t simple_async_get2, \n\t simple_sync_get_next2, \n\t simple_async_get_next2, \n\t simple_sync_set2, \n\t simple_async_set2, \n\t simple_sync_get_bulk2, \n\t simple_async_get_bulk2,\n\t misc_async2,\n\t otp8395_1\n\t],\n ApiCases03 = \n\t[\n\t simple_sync_get3,\n\t simple_async_get3, \n\t simple_sync_get_next3, \n\t simple_async_get_next3, \n\t simple_sync_set3, \n\t simple_async_set3, \n\t simple_sync_get_bulk3, \n\t simple_async_get_bulk3\n\t],\n Cases = \n\t[\n\t trap1,\n\t trap2,\n\t inform1,\n\t inform2,\n\t inform3,\n\t inform4,\n\t inform_swarm,\n\t report\n\t] ++ \n\tApiCases02 ++\n\tApiCases03,\n case lists:member(Case, Cases) of\n\ttrue ->\n\t NoAutoInformCases = [inform1, inform2, inform3, inform_swarm], \n\t AutoInform = not lists:member(Case, NoAutoInformCases),\n\t Conf1 = if \n\t\t\tCase =:= inform_swarm ->\n\t\t\t Verb = [{manager_config_verbosity, silence},\n\t\t\t\t {manager_note_store_verbosity, silence},\n\t\t\t\t {manager_server_verbosity, info},\n\t\t\t\t {manager_net_if_verbosity, info},\n\t\t\t\t {agent_verbosity, info}, \n\t\t\t\t {agent_net_if_verbosity, info}],\n\t\t\t Verb ++ Config;\n\t\t\tCase =:= otp8395_1 ->\n\t\t\t [{manager_atl_seqno, true} | Config];\n\t\t\ttrue ->\n\t\t\t Config\n\t\t end,\n\t Conf2 = init_agent(Conf1),\n\t Conf3 = init_manager(AutoInform, Conf2), \n\t Conf4 = init_mgr_user(Conf3),\n\t case lists:member(Case, ApiCases02 ++ ApiCases03) of\n\t\ttrue ->\n\t\t init_mgr_user_data2(Conf4);\n\t\tfalse ->\n\t\t init_mgr_user_data1(Conf4)\n\t end;\n\tfalse ->\n\t Config\n end.\n\nend_per_testcase(Case, Config) when is_list(Config) ->\n p(Case, \"end_per_testcase begin when\"\n \"~n Nodes: ~p~n~n\", [erlang:nodes()]),\n ?DBG(\"fin [~w] Nodes [1]: ~p\", [Case, erlang:nodes()]),\n Dog = ?config(watchdog, Config),\n ?WD_STOP(Dog),\n Conf1 = lists:keydelete(watchdog, 1, Config),\n Conf2 = end_per_testcase2(Case, Conf1),\n ?DBG(\"fin [~w] Nodes [2]: ~p\", [Case, erlang:nodes()]),\n %% TopDir = ?config(top_dir, Conf2),\n %% ?DEL_DIR(TopDir),\n p(Case, \"end_per_testcase end when\"\n \"~n Nodes: ~p~n~n\", [erlang:nodes()]),\n Conf2.\n\nend_per_testcase2(Case, Config) ->\n ApiCases02 = \n\t[\n\t simple_sync_get2, \n\t simple_async_get2, \n\t simple_sync_get_next2, \n\t simple_async_get_next2, \n\t simple_sync_set2, \n\t simple_async_set2, \n\t simple_sync_get_bulk2, \n\t simple_async_get_bulk2,\n\t misc_async2,\n\t otp8395_1\n\t],\n ApiCases03 = \n\t[\n\t simple_sync_get3, \n\t simple_async_get3, \n\t simple_sync_get_next3, \n\t simple_async_get_next3, \n\t simple_sync_set3, \n\t simple_async_set3, \n\t simple_sync_get_bulk3, \n\t simple_async_get_bulk3 \n\t],\n Cases = \n\t[\n\t trap1,\n\t trap2,\n\t inform1,\n\t inform2,\n\t inform3,\n\t inform4,\n\t inform_swarm,\n\t report\n\t] ++ \n\tApiCases02 ++ \n\tApiCases03,\n case lists:member(Case, Cases) of\n\ttrue ->\n\t Conf1 = case lists:member(Case, ApiCases02 ++ ApiCases03) of\n\t\t\ttrue ->\n\t\t\t fin_mgr_user_data2(Config);\n\t\t\tfalse ->\n\t\t\t fin_mgr_user_data1(Config)\n\t\t end,\n\t Conf2 = fin_mgr_user(Conf1),\n\t Conf3 = fin_manager(Conf2),\n\t fin_agent(Conf3);\n\tfalse ->\n\t Config\n end.\n\n\n%%======================================================================\n%% Test case definitions\n%%======================================================================\n\nall() -> \n [\n {group, start_and_stop_tests}, \n {group, misc_tests}, \n {group, user_tests}, \n {group, agent_tests}, \n {group, request_tests}, \n {group, request_tests_mt}, \n {group, event_tests}, \n {group, event_tests_mt}, \n discovery, \n {group, tickets}, \n {group, ipv6},\n {group, ipv6_mt}\n ].\n\ngroups() -> \n [\n {start_and_stop_tests, [],\n [\n simple_start_and_stop1, \n simple_start_and_stop2,\n simple_start_and_monitor_crash1,\n simple_start_and_monitor_crash2, \n notify_started01,\n notify_started02\n ]\n },\n {misc_tests, [], \n [\n info\n ]\n },\n {user_tests, [], \n [\n register_user1\n ]\n },\n {agent_tests, [], \n [\n register_agent1, \n register_agent2, \n register_agent3\n ]\n },\n {request_tests, [],\n [\n {group, get_tests}, \n {group, get_next_tests}, \n {group, set_tests}, \n {group, bulk_tests}, \n {group, misc_request_tests} \n ]\n },\n {request_tests_mt, [],\n [\n {group, get_tests}, \n {group, get_next_tests},\n {group, set_tests}, \n {group, bulk_tests},\n {group, misc_request_tests}\n ]\n },\n {get_tests, [],\n [\n simple_sync_get1, \n simple_sync_get2, \n simple_sync_get3, \n simple_async_get1,\n simple_async_get2,\n simple_async_get3\n ]\n },\n {get_next_tests, [],\n [\n simple_sync_get_next1, \n simple_sync_get_next2,\n simple_sync_get_next3,\n simple_async_get_next1, \n simple_async_get_next2, \n simple_async_get_next3\n ]\n },\n {set_tests, [],\n [\n simple_sync_set1, \n simple_sync_set2, \n simple_sync_set3, \n simple_async_set1,\n simple_async_set2, \n simple_async_set3\n ]\n },\n {bulk_tests, [],\n [\n simple_sync_get_bulk1, \n simple_sync_get_bulk2,\n simple_sync_get_bulk3,\n simple_async_get_bulk1, \n simple_async_get_bulk2, \n\tsimple_async_get_bulk3\n ]\n },\n {misc_request_tests, [], \n [\n\tmisc_async1, \n\tmisc_async2\n ]\n },\n {event_tests, [],\n [\n trap1, \n trap2, \n inform1, \n inform2, \n inform3, \n inform4,\n inform_swarm, \n report\n ]\n },\n {event_tests_mt, [],\n [\n trap1, \n trap2, \n inform1, \n inform2, \n inform3, \n inform4,\n inform_swarm, \n report\n ]\n },\n {tickets, [], \n [\n {group, otp8015}, \n {group, otp8395}\n ]\n },\n {otp8015, [], \n [\n otp8015_1\n ]\n }, \n {otp8395, [], \n [\n otp8395_1\n ]\n },\n {ipv6, [], ipv6_tests()},\n {ipv6_mt, [], ipv6_tests()}\n\n ].\n\nipv6_tests() ->\n [\n register_agent1,\n simple_sync_get_next3,\n simple_async_get2,\n simple_sync_get3,\n simple_async_get_next2,\n simple_sync_set3,\n simple_async_set2,\n simple_sync_get_bulk2,\n simple_async_get_bulk3,\n misc_async2,\n inform1,\n inform_swarm\n ].\n\n\ninit_per_group(request_tests_mt = GroupName, Config) ->\n snmp_test_lib:init_group_top_dir(\n GroupName, \n [{manager_net_if_module, snmpm_net_if_mt} | Config]);\ninit_per_group(event_tests_mt = GroupName, Config) ->\n snmp_test_lib:init_group_top_dir(\n GroupName, \n [{manager_net_if_module, snmpm_net_if_mt} | Config]);\ninit_per_group(ipv6_mt = GroupName, Config) ->\n {ok, Hostname0} = inet:gethostname(),\n case ct:require(ipv6_hosts) of\n\tok ->\n\t case lists:member(list_to_atom(Hostname0), ct:get_config(ipv6_hosts)) of\n\t\ttrue ->\n\t\t ipv6_init(\n\t\t snmp_test_lib:init_group_top_dir(\n\t\t\tGroupName,\n\t\t\t[{manager_net_if_module, snmpm_net_if_mt}\n\t\t\t | Config]));\n\t\tfalse ->\n\t\t {skip, \"Host does not support IPv6\"}\n\t end;\n\t_ ->\n\t {skip, \"Test config ipv6_hosts is missing\"}\n end;\ninit_per_group(ipv6 = GroupName, Config) -> \n {ok, Hostname0} = inet:gethostname(),\n case ct:require(ipv6_hosts) of\n\tok ->\n\t case lists:member(list_to_atom(Hostname0), ct:get_config(ipv6_hosts)) of\n\t\ttrue ->\n\t\t ipv6_init(snmp_test_lib:init_group_top_dir(GroupName, Config));\n\t\tfalse ->\n\t\t {skip, \"Host does not support IPv6\"}\n\t end;\n\t_ ->\n\t {skip, \"Test config ipv6_hosts is missing\"}\n end;\ninit_per_group(GroupName, Config) ->\n snmp_test_lib:init_group_top_dir(GroupName, Config).\n\nend_per_group(_GroupName, Config) ->\n %% Do we really need to do this?\n lists:keydelete(snmp_group_top_dir, 1, Config).\n\n\n%%======================================================================\n%% Test functions\n%%======================================================================\n\nsimple_start_and_stop1(suite) -> [];\nsimple_start_and_stop1(Config) when is_list(Config) ->\n %% ?SKIP(not_yet_implemented),\n process_flag(trap_exit, true),\n put(tname,ssas1),\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"try starting manager\"),\n ok = snmpm:start_link(Opts),\n\n ?SLEEP(1000),\n\n p(\"manager started, now try to stop\"),\n ok = snmpm:stop(),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nsimple_start_and_stop2(suite) -> [];\nsimple_start_and_stop2(Config) when is_list(Config) ->\n %% ?SKIP(not_yet_implemented),\n process_flag(trap_exit, true),\n put(tname,ssas2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n ManagerNode = start_manager_node(), \n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n\n p(\"try load snmp application\"),\n ?line ok = load_snmp(ManagerNode),\n\n p(\"try set manager env for the snmp application\"),\n ?line ok = set_mgr_env(ManagerNode, Opts),\n\n p(\"try starting snmp application (with only manager)\"),\n ?line ok = start_snmp(ManagerNode),\n\n p(\"started\"),\n\n ?SLEEP(1000),\n\n p(\"try stopping snmp application (with only manager)\"),\n ?line ok = stop_snmp(ManagerNode),\n\n ?SLEEP(1000),\n\n stop_node(ManagerNode),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nsimple_start_and_monitor_crash1(suite) -> [];\nsimple_start_and_monitor_crash1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,ssamc1),\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"try starting manager\"),\n ok = snmpm:start(Opts),\n\n ?SLEEP(1000),\n\n p(\"create the monitor\"),\n Ref = snmpm:monitor(),\n\n p(\"make sure it has not already crashed...\"),\n receive\n\t{'DOWN', Ref, process, Obj1, Reason1} ->\n\t ?FAIL({unexpected_down, Obj1, Reason1})\n after 1000 ->\n\t ok\n end,\n\n p(\"stop the manager\"),\n ok = snmpm:stop(),\n\n p(\"await the down-message\"),\n receive\n\t{'DOWN', Ref, process, Obj2, Reason2} ->\n\t p(\"received expected down-message: \"\n\t \"~n Obj2: ~p\"\n\t \"~n Reason2: ~p\", \n\t [Obj2, Reason2]),\n\t ok\n after 1000 ->\n\t ?FAIL(timeout)\n end,\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nsimple_start_and_monitor_crash2(suite) -> [];\nsimple_start_and_monitor_crash2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,ssamc2),\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{restart_type, permanent},\n\t {server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"try starting manager\"),\n ok = snmpm:start(Opts),\n\n ?SLEEP(1000),\n\n p(\"create the monitor\"),\n Ref = snmpm:monitor(),\n\n p(\"make sure it has not already crashed...\"),\n receive\n\t{'DOWN', Ref, process, Obj1, Reason1} ->\n\t ?FAIL({unexpected_down, Obj1, Reason1})\n after 1000 ->\n\t ok\n end,\n\n p(\"crash the manager\"),\n simulate_crash(),\n\n p(\"await the down-message\"),\n receive\n\t{'DOWN', Ref, process, Obj2, Reason2} ->\n\t p(\"received expected down-message: \"\n\t \"~n Obj2: ~p\"\n\t \"~n Reason2: ~p\", \n\t [Obj2, Reason2]),\n\t ok\n after 1000 ->\n\t ?FAIL(timeout)\n end,\n\n p(\"end\"),\n ok.\n\n\n%% The server supervisor allow 5 restarts in 500 msec.\nserver_pid() ->\n whereis(snmpm_server).\n\n-define(MAX_KILLS, 6).\n\nsimulate_crash() ->\n simulate_crash(0, server_pid()).\n\nsimulate_crash(?MAX_KILLS, _) ->\n ?SLEEP(1000),\n case server_pid() of\n\tP when is_pid(P) ->\n\t exit({error, {still_alive, P}});\n\t_ ->\n\t ok\n end;\nsimulate_crash(NumKills, Pid) when (NumKills < ?MAX_KILLS) and is_pid(Pid) ->\n p(\"similate_crash -> ~w, ~p\", [NumKills, Pid]),\n Ref = erlang:monitor(process, Pid),\n exit(Pid, kill),\n receive \n\t{'DOWN', Ref, process, _Object, _Info} ->\n\t p(\"received expected 'DOWN' message\"),\n\t simulate_crash(NumKills + 1, server_pid())\n after 1000 ->\n\t case server_pid() of\n\t\tP when is_pid(P) ->\n\t\t exit({error, {no_down_from_server, P}});\n\t\t_ ->\n\t\t ok\n\t end\n end;\nsimulate_crash(NumKills, _) ->\n ?SLEEP(10),\n simulate_crash(NumKills, server_pid()).\n\n\n%%======================================================================\n\nnotify_started01(suite) -> [];\nnotify_started01(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,ns01),\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, log}]},\n\t {net_if, [{verbosity, silence}]},\n\t {note_store, [{verbosity, silence}]},\n\t {config, [{verbosity, log}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"request start notification (1)\"),\n Pid1 = snmpm:notify_started(10000),\n receive\n\t{snmpm_start_timeout, Pid1} ->\n\t p(\"received expected start timeout\"),\n\t ok;\n\tAny1 ->\n\t ?FAIL({unexpected_message, Any1})\n after 15000 ->\n\t ?FAIL({unexpected_timeout, Pid1})\n end,\n\n p(\"request start notification (2)\"),\n Pid2 = snmpm:notify_started(10000),\n\n p(\"start the snmpm starter\"),\n Pid = snmpm_starter(Opts, 5000),\n\n p(\"await the start notification\"),\n Ref = \n\treceive\n\t {snmpm_started, Pid2} ->\n\t\tp(\"received started message -> create the monitor\"),\n\t\tsnmpm:monitor();\n\t Any2 ->\n\t\t?FAIL({unexpected_message, Any2})\n\tafter 15000 ->\n\t\t?FAIL({unexpected_timeout, Pid2})\n\tend,\n\n p(\"[~p] make sure it has not already crashed...\", [Ref]),\n receive\n\t{'DOWN', Ref, process, Obj1, Reason1} ->\n\t ?FAIL({unexpected_down, Obj1, Reason1})\n after 1000 ->\n\t ok\n end,\n\n p(\"stop the manager\"),\n Pid ! {stop, self()}, %ok = snmpm:stop(),\n\n p(\"await the down-message\"),\n receive\n\t{'DOWN', Ref, process, Obj2, Reason2} ->\n\t p(\"received expected down-message: \"\n\t \"~n Obj2: ~p\"\n\t \"~n Reason2: ~p\", \n\t [Obj2, Reason2]),\n\t ok\n after 5000 ->\n\t ?FAIL(down_timeout)\n end,\n\n p(\"end\"),\n ok.\n\n\nsnmpm_starter(Opts, To) ->\n Parent = self(),\n spawn(\n fun() -> \n\t ?SLEEP(To), \n\t ok = snmpm:start(Opts),\n\t receive\n\t\t {stop, Parent} ->\n\t\t snmpm:stop()\n\t end\n end).\n\n\n%%======================================================================\n\nnotify_started02(suite) -> [];\nnotify_started02(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,ns02),\n\n %% \n %% The point of this is to catch machines running \n %% SLES9 (2.6.5)\n LinuxVersionVerify = \n\tfun() ->\n\t\tcase os:cmd(\"uname -m\") of\n\t\t \"i686\" ++ _ ->\n%% \t\t\tio:format(\"found an i686 machine, \"\n%% \t\t\t\t \"now check version~n\", []),\n\t\t\tcase os:version() of\n\t\t\t {2, 6, Rev} when Rev >= 16 ->\n\t\t\t\ttrue;\n\t\t\t {2, Min, _} when Min > 6 ->\n\t\t\t\ttrue;\n\t\t\t {Maj, _, _} when Maj > 2 ->\n\t\t\t\ttrue;\n\t\t\t _ ->\n\t\t\t\tfalse\n\t\t\tend;\n\t\t _ ->\n\t\t\ttrue\n\t\tend\n\tend,\n Skippable = [{unix, [{linux, LinuxVersionVerify}]}],\n Condition = fun() -> ?OS_BASED_SKIP(Skippable) end,\n ?NON_PC_TC_MAYBE_SKIP(Config, Condition),\n %% <\/CONDITIONAL-SKIP>\n\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, log}]},\n\t {net_if, [{verbosity, silence}]},\n\t {note_store, [{verbosity, silence}]},\n\t {config, [{verbosity, log}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"start snmpm client process\"),\n Pid1 = ns02_loop1_start(),\n\n p(\"start snmpm starter process\"),\n Pid2 = ns02_loop2_start(Opts),\n \n p(\"await snmpm client process exit\"),\n receive \n\t{'EXIT', Pid1, normal} ->\n\t ok;\n\t{'EXIT', Pid1, Reason1} ->\n\t ?FAIL(Reason1)\n after 25000 ->\n\t ?FAIL(timeout)\n end,\n\t\n p(\"await snmpm starter process exit\"),\n receive \n\t{'EXIT', Pid2, normal} ->\n\t ok;\n\t{'EXIT', Pid2, Reason2} ->\n\t ?FAIL(Reason2)\n after 5000 ->\n\t ?FAIL(timeout)\n end,\n\t\n p(\"end\"),\n ok.\n\n\nns02_loop1_start() ->\n spawn_link(fun() -> ns02_loop1() end).\n\t\t \nns02_loop1() ->\n put(tname,ns02_loop1),\n p(\"starting\"),\n ns02_loop1(dummy, snmpm:notify_started(?NS_TIMEOUT), 5).\n\nns02_loop1(_Ref, _Pid, 0) ->\n p(\"done\"),\n exit(normal);\nns02_loop1(Ref, Pid, N) ->\n p(\"entry when\"\n \"~n Ref: ~p\"\n \"~n Pid: ~p\"\n \"~n N: ~p\", [Ref, Pid, N]),\n receive\n\t{snmpm_started, Pid} ->\n\t p(\"received expected started message (~w)\", [N]),\n\t ns02_loop1(snmpm:monitor(), dummy, N);\n\t{snmpm_start_timeout, Pid} ->\n\t p(\"unexpected timout\"),\n\t ?FAIL({unexpected_start_timeout, Pid});\n\t{'DOWN', Ref, process, Obj, Reason} ->\n\t p(\"received expected DOWN message (~w) with\"\n\t \"~n Obj: ~p\"\n\t \"~n Reason: ~p\", [N, Obj, Reason]),\n\t ns02_loop1(dummy, snmpm:notify_started(?NS_TIMEOUT), N-1)\n after 10000 ->\n\t ?FAIL(timeout)\n end.\n\n\nns02_loop2_start(Opts) ->\n spawn_link(fun() -> ns02_loop2(Opts) end).\n\t\t \nns02_loop2(Opts) ->\n put(tname,ns02_loop2),\n p(\"starting\"),\n ns02_loop2(Opts, 5).\n\nns02_loop2(_Opts, 0) ->\n p(\"done\"),\n exit(normal);\nns02_loop2(Opts, N) ->\n p(\"entry when N: ~p\", [N]),\n ?SLEEP(2000),\n p(\"start manager\"),\n snmpm:start(Opts),\n ?SLEEP(2000),\n p(\"stop manager\"),\n snmpm:stop(),\n ns02_loop2(Opts, N-1).\n\n\n%%======================================================================\n\ninfo(suite) -> [];\ninfo(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,info),\n p(\"starting with Config: ~n~p\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"try starting manager\"),\n ok = snmpm:start(Opts),\n\n ?SLEEP(1000),\n\n p(\"manager started, now get info\"),\n Info = snmpm:info(), \n p(\"got info, now verify: ~n~p\", [Info]),\n ok = verify_info( Info ),\n\n p(\"info verified, now try to stop\"),\n ok = snmpm:stop(),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\nverify_info(Info) when is_list(Info) ->\n Keys = [{server, [process_memory, db_memory]},\n\t {config, [process_memory, db_memory]},\n\t {net_if, [process_memory, port_info]},\n\t {note_store, [process_memory, db_memory]},\n\t stats_counters],\n verify_info(Keys, Info);\nverify_info(BadInfo) ->\n {error, {bad_info, BadInfo}}.\n\nverify_info([], _) ->\n ok;\nverify_info([Key|Keys], Info) when is_atom(Key) ->\n case lists:keymember(Key, 1, Info) of\n\ttrue ->\n\t verify_info(Keys, Info);\n\tfalse ->\n\t {error, {missing_info, {Key, Info}}}\n end;\nverify_info([{Key, SubKeys}|Keys], Info) ->\n case lists:keysearch(Key, 1, Info) of\n\t{value, {Key, SubInfo}} ->\n\t case verify_info(SubKeys, SubInfo) of\n\t\tok ->\n\t\t verify_info(Keys, Info);\n\t\t{error, {missing_info, {SubKey, _}}} ->\n\t\t {error, {missing_subinfo, {Key, SubKey, Info}}}\n\t end;\n\tfalse ->\n\t {error, {missing_info, {Key, Info}}}\n end.\n\n\n%%======================================================================\n\nregister_user1(suite) -> [];\nregister_user1(Config) when is_list(Config) ->\n %% ?SKIP(not_yet_implemented).\n process_flag(trap_exit, true),\n put(tname,ru1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n ManagerNode = start_manager_node(), \n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n\n p(\"load snmp application\"),\n ?line ok = load_snmp(ManagerNode),\n\n p(\"set manager env for the snmp application\"),\n ?line ok = set_mgr_env(ManagerNode, Opts),\n\n p(\"starting snmp application (with only manager)\"),\n ?line ok = start_snmp(ManagerNode),\n\n p(\"started\"),\n\n ?SLEEP(1000),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"try register user(s)\"),\n ?line ok = mgr_register_user(ManagerNode, calvin, snmpm_user_default, \n\t\t\t\t [self(), \"various misc info\"]),\n\n Users1 = mgr_which_users(ManagerNode),\n p(\"users: ~p~n\", [Users1]),\n ?line ok = verify_users(Users1, [calvin]),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?line ok = mgr_register_user(ManagerNode, hobbe, snmpm_user_default, \n\t\t\t\t {\"misc info\", self()}),\n\n Users2 = mgr_which_users(ManagerNode),\n p(\"users: ~p~n\", [Users2]),\n ?line ok = verify_users(Users2, [calvin, hobbe]),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"try unregister user(s)\"),\n ?line ok = mgr_unregister_user(ManagerNode, calvin),\n\n Users3 = mgr_which_users(ManagerNode),\n p(\"users: ~p~n\", [Users3]),\n ?line ok = verify_users(Users3, [hobbe]),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?line ok = mgr_unregister_user(ManagerNode, hobbe),\n\n Users4 = mgr_which_users(ManagerNode),\n p(\"users: ~p~n\", [Users4]),\n ?line ok = verify_users(Users4, []),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?SLEEP(1000),\n\n p(\"stop snmp application (with only manager)\"),\n ?line ok = stop_snmp(ManagerNode),\n\n ?SLEEP(1000),\n\n stop_node(ManagerNode),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\nverify_users([], []) ->\n ok;\nverify_users(ActualUsers, []) ->\n {error, {unexpected_users, ActualUsers}};\nverify_users(ActualUsers0, [User|RegUsers]) ->\n case lists:delete(User, ActualUsers0) of\n\tActualUsers0 ->\n\t {error, {not_registered, User}};\n\tActualUsers ->\n\t verify_users(ActualUsers, RegUsers)\n end.\n \n\n%%======================================================================\n\nregister_agent1(doc) -> \n [\"Test registration of agents with the OLD interface functions\"];\nregister_agent1(suite) -> \n [];\nregister_agent1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,ra1),\n \n p(\"starting with Config: ~p~n\", [Config]),\n\n ManagerNode = start_manager_node(), \n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n\n p(\"load snmp application\"),\n ?line ok = load_snmp(ManagerNode),\n\n p(\"set manager env for the snmp application\"),\n ?line ok = set_mgr_env(ManagerNode, Opts),\n\n p(\"starting snmp application (with only manager)\"),\n ?line ok = start_snmp(ManagerNode),\n\n p(\"started\"),\n\n ?SLEEP(1000),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register user(s) user_alfa & user_beta\"),\n ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),\n ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register agent(s)\"),\n ?line ok = mgr_register_agent(ManagerNode, user_alfa, 5000, []),\n ?line ok = mgr_register_agent(ManagerNode, user_alfa, 5001, []),\n ?line ok = mgr_register_agent(ManagerNode, user_beta, 5002, []),\n ?line ok = mgr_register_agent(ManagerNode, user_beta, 5003, []),\n\n p(\"verify all agent(s): expect 4\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents1 when length(Agents1) =:= 4 ->\n\t p(\"all agents: ~p~n\", [Agents1]),\n\t ok;\n\tAgents1 ->\n\t ?FAIL({agent_registration_failure, Agents1})\n end,\n\n p(\"verify user_alfa agent(s)\"),\n case mgr_which_agents(ManagerNode, user_alfa) of\n\tAgents2 when length(Agents2) =:= 2 ->\n\t p(\"calvin agents: ~p~n\", [Agents2]),\n\t ok;\n\tAgents2 ->\n\t ?FAIL({agent_registration_failure, Agents2})\n end,\n\n p(\"verify user_beta agent(s)\"),\n case mgr_which_agents(ManagerNode, user_beta) of\n\tAgents3 when length(Agents3) =:= 2 ->\n\t p(\"hobbe agents: ~p~n\", [Agents3]),\n\t ok;\n\tAgents3 ->\n\t ?FAIL({agent_registration_failure, Agents3})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n \n p(\"unregister user user_alfa\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_alfa),\n\n p(\"verify all agent(s): expect 2\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents4 when length(Agents4) =:= 2 ->\n\t p(\"all agents: ~p~n\", [Agents4]),\n\t ok;\n\tAgents4 ->\n\t ?FAIL({agent_unregistration_failure, Agents4})\n end,\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user_beta agents\"),\n ?line ok = mgr_unregister_agent(ManagerNode, user_beta, 5002),\n ?line ok = mgr_unregister_agent(ManagerNode, user_beta, 5003),\n\n p(\"verify all agent(s): expect 0\"),\n case mgr_which_agents(ManagerNode) of\n\t[] ->\n\t ok;\n\tAgents5 ->\n\t p(\"all agents: ~p~n\", [Agents5]),\n\t ?FAIL({agent_unregistration_failure, Agents5})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user hobbe\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_beta),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?SLEEP(1000),\n\n p(\"stop snmp application (with only manager)\"),\n ?line ok = stop_snmp(ManagerNode),\n\n ?SLEEP(1000),\n\n stop_node(ManagerNode),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nregister_agent2(doc) -> \n [\"Test registration of agents with the NEW interface functions\"];\nregister_agent2(suite) -> \n [];\nregister_agent2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ra2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n ManagerNode = start_manager_node(), \n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n LocalHost = snmp_test_lib:localhost(), \n\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n\n p(\"load snmp application\"),\n ?line ok = load_snmp(ManagerNode),\n\n p(\"set manager env for the snmp application\"),\n ?line ok = set_mgr_env(ManagerNode, Opts),\n\n p(\"starting snmp application (with only manager)\"),\n ?line ok = start_snmp(ManagerNode),\n\n p(\"started\"),\n\n ?SLEEP(1000),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register user(s) user_alfa & user_beta\"),\n ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),\n ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register agent(s)\"),\n TargetName1 = \"agent1\", \n ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName1, \n\t\t\t\t [{address, LocalHost},\n\t\t\t\t {port, 5001},\n\t\t\t\t {engine_id, \"agentEngineId-1\"}]),\n TargetName2 = \"agent2\", \n ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName2,\n\t\t\t\t [{address, LocalHost},\n\t\t\t\t {port, 5002},\n\t\t\t\t {engine_id, \"agentEngineId-2\"}]),\n TargetName3 = \"agent3\", \n ?line ok = mgr_register_agent(ManagerNode, user_beta, TargetName3,\n\t\t\t\t [{address, LocalHost},\n\t\t\t\t {port, 5003},\n\t\t\t\t {engine_id, \"agentEngineId-3\"}]),\n TargetName4 = \"agent4\", \n ?line ok = mgr_register_agent(ManagerNode, user_beta, TargetName4,\n\t\t\t\t [{address, LocalHost},\n\t\t\t\t {port, 5004},\n\t\t\t\t {engine_id, \"agentEngineId-4\"}]),\n\n p(\"verify all agent(s): expect 4\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents1 when length(Agents1) =:= 4 ->\n\t p(\"all agents: ~p~n\", [Agents1]),\n\t ok;\n\tAgents1 ->\n\t ?FAIL({agent_registration_failure, Agents1})\n end,\n\n p(\"verify user_alfa agent(s)\"),\n case mgr_which_agents(ManagerNode, user_alfa) of\n\tAgents2 when length(Agents2) =:= 2 ->\n\t p(\"calvin agents: ~p~n\", [Agents2]),\n\t ok;\n\tAgents2 ->\n\t ?FAIL({agent_registration_failure, Agents2})\n end,\n\n p(\"verify user_beta agent(s)\"),\n case mgr_which_agents(ManagerNode, user_beta) of\n\tAgents3 when length(Agents3) =:= 2 ->\n\t p(\"hobbe agents: ~p~n\", [Agents3]),\n\t ok;\n\tAgents3 ->\n\t ?FAIL({agent_registration_failure, Agents3})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user user_alfa\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_alfa),\n\n p(\"verify all agent(s): expect 2\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents4 when length(Agents4) =:= 2 ->\n\t p(\"all agents: ~p~n\", [Agents4]),\n\t ok;\n\tAgents4 ->\n\t ?FAIL({agent_unregistration_failure, Agents4})\n end,\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user_beta agents\"),\n ?line ok = mgr_unregister_agent(ManagerNode, user_beta, TargetName3),\n ?line ok = mgr_unregister_agent(ManagerNode, user_beta, TargetName4),\n\n p(\"verify all agent(s): expect 0\"),\n case mgr_which_agents(ManagerNode) of\n\t[] ->\n\t ok;\n\tAgents5 ->\n\t p(\"all agents: ~p~n\", [Agents5]),\n\t ?FAIL({agent_unregistration_failure, Agents5})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user user_beta\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_beta),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?SLEEP(1000),\n\n p(\"stop snmp application (with only manager)\"),\n ?line ok = stop_snmp(ManagerNode),\n\n ?SLEEP(1000),\n\n stop_node(ManagerNode),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nregister_agent3(doc) -> \n [\"Test registration of agents with the NEW interface functions \"\n \"and specifying transport domain\"];\nregister_agent3(suite) -> \n [];\nregister_agent3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ra3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n ManagerNode = start_manager_node(), \n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n LocalHost = snmp_test_lib:localhost(), \n\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n\n p(\"load snmp application\"),\n ?line ok = load_snmp(ManagerNode),\n\n p(\"set manager env for the snmp application\"),\n ?line ok = set_mgr_env(ManagerNode, Opts),\n\n p(\"starting snmp application (with only manager)\"),\n ?line ok = start_snmp(ManagerNode),\n\n p(\"started\"),\n\n ?SLEEP(1000),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register user(s) user_alfa & user_beta\"),\n ?line ok = mgr_register_user(ManagerNode, user_alfa, snmpm_user_default, []),\n ?line ok = mgr_register_user(ManagerNode, user_beta, snmpm_user_default, []),\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"register agent(s)\"),\n TargetName1 = \"agent2\", \n ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName1, \n\t\t\t\t [{tdomain, transportDomainUdpIpv4},\n\t\t\t\t {address, LocalHost},\n\t\t\t\t {port, 5001},\n\t\t\t\t {engine_id, \"agentEngineId-1\"}]),\n TargetName2 = \"agent3\", \n ?line ok = mgr_register_agent(ManagerNode, user_alfa, TargetName2,\n\t\t\t\t [{tdomain, transportDomainUdpIpv6},\n\t\t\t\t {address, {0,0,0,0,0,0,0,1}},\n\t\t\t\t {port, 5002},\n\t\t\t\t {engine_id, \"agentEngineId-2\"}]),\n TargetName3 = \"agent4\", \n ?line {error, {unsupported_domain, _} = Reason4} = \n\tmgr_register_agent(ManagerNode, user_beta, TargetName3,\n\t\t\t [{tdomain, transportDomainTcpIpv4},\n\t\t\t {address, LocalHost},\n\t\t\t {port, 5003},\n\t\t\t {engine_id, \"agentEngineId-3\"}]),\n p(\"Expected registration failure: ~p\", [Reason4]),\n TargetName4 = \"agent5\", \n ?line {error, {unknown_domain, _} = Reason5} = \n\tmgr_register_agent(ManagerNode, user_beta, TargetName4,\n\t\t\t [{tdomain, transportDomainUdpIpv4_bad},\n\t\t\t {address, LocalHost},\n\t\t\t {port, 5004},\n\t\t\t {engine_id, \"agentEngineId-4\"}]),\n p(\"Expected registration failure: ~p\", [Reason5]),\n\n p(\"verify all agent(s): expect 2\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents1 when length(Agents1) =:= 2 ->\n\t p(\"all agents: ~p~n\", [Agents1]),\n\t ok;\n\tAgents1 ->\n\t ?FAIL({agent_registration_failure, Agents1})\n end,\n\n p(\"verify user_alfa agent(s)\"),\n case mgr_which_agents(ManagerNode, user_alfa) of\n\tAgents2 when length(Agents2) =:= 2 ->\n\t p(\"calvin agents: ~p~n\", [Agents2]),\n\t ok;\n\tAgents2 ->\n\t ?FAIL({agent_registration_failure, Agents2})\n end,\n\n p(\"verify user_beta agent(s)\"),\n case mgr_which_agents(ManagerNode, user_beta) of\n\tAgents3 when length(Agents3) =:= 0 ->\n\t p(\"hobbe agents: ~p~n\", [Agents3]),\n\t ok;\n\tAgents3 ->\n\t ?FAIL({agent_registration_failure, Agents3})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user user_alfa\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_alfa),\n\n p(\"verify all agent(s): expect 0\"),\n case mgr_which_agents(ManagerNode) of\n\tAgents4 when length(Agents4) =:= 0 ->\n\t p(\"all agents: ~p~n\", [Agents4]),\n\t ok;\n\tAgents4 ->\n\t ?FAIL({agent_unregistration_failure, Agents4})\n end,\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"verify all agent(s): expect 0\"),\n case mgr_which_agents(ManagerNode) of\n\t[] ->\n\t ok;\n\tAgents5 ->\n\t p(\"all agents: ~p~n\", [Agents5]),\n\t ?FAIL({agent_unregistration_failure, Agents5})\n end,\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n p(\"unregister user user_beta\"),\n ?line ok = mgr_unregister_user(ManagerNode, user_beta),\n\n p(\"manager info: ~p~n\", [mgr_info(ManagerNode)]),\n\n ?SLEEP(1000),\n\n p(\"stop snmp application (with only manager)\"),\n ?line ok = stop_snmp(ManagerNode),\n\n ?SLEEP(1000),\n\n stop_node(ManagerNode),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\nsimple_sync_get1(doc) -> [\"Simple sync get-request - Old style (Addr & Port)\"];\nsimple_sync_get1(suite) -> [];\nsimple_sync_get1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, ssg1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n Node = ?config(manager_node, Config),\n Addr = ?config(manager_agent_target_name, Config),\n Port = ?AGENT_PORT,\n\n p(\"issue get-request without loading the mib\"),\n Oids1 = [?sysObjectID_instance, ?sysDescr_instance, ?sysUpTime_instance],\n ?line ok = do_simple_sync_get(Node, Addr, Port, Oids1),\n\n p(\"issue get-request after first loading the mibs\"),\n ?line ok = mgr_user_load_mib(Node, std_mib()),\n Oids2 = [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n ?line ok = do_simple_sync_get(Node, Addr, Port, Oids2),\n\n p(\"Display log\"),\n display_log(Config),\n\n p(\"done\"),\n ok.\n\ndo_simple_sync_get(Node, Addr, Port, Oids) ->\n ?line {ok, Reply, _Rem} = mgr_user_sync_get(Node, Addr, Port, Oids),\n\n ?DBG(\"~n Reply: ~p\"\n\t \"~n Rem: ~w\", [Reply, _Rem]),\n\n %% verify that the operation actually worked:\n %% The order should be the same, so no need to seach \n ?line ok = case Reply of\n\t\t {noError, 0, [#varbind{oid = ?sysObjectID_instance,\n\t\t\t\t\t value = SysObjectID}, \n\t\t\t\t #varbind{oid = ?sysDescr_instance,\n\t\t\t\t\t value = SysDescr},\n\t\t\t\t #varbind{oid = ?sysUpTime_instance,\n\t\t\t\t\t value = SysUpTime}]} ->\n\t\t p(\"expected result from get: \"\n\t\t\t \"~n SysObjectID: ~p\"\n\t\t\t \"~n SysDescr: ~s\"\n\t\t\t \"~n SysUpTime: ~w\", \n\t\t\t [SysObjectID, SysDescr, SysUpTime]),\n\t\t ok;\n\t\t {noError, 0, Vbs} ->\n\t\t p(\"unexpected varbinds: ~n~p\", [Vbs]),\n\t\t {error, {unexpected_vbs, Vbs}};\n\t\t Else ->\n\t\t p(\"unexpected reply: ~n~p\", [Else]),\n\t\t {error, {unexpected_response, Else}}\n\t end,\n ok.\n \n\n%%======================================================================\n\nsimple_sync_get2(doc) -> \n [\"Simple sync get-request - Version 2 API (TargetName)\"];\nsimple_sync_get2(suite) -> [];\nsimple_sync_get2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssg2),\n do_simple_sync_get2(Config),\n display_log(Config),\n ok.\n\ndo_simple_sync_get2(Config) ->\n Get = fun(Node, TargetName, Oids) -> \n\t\t mgr_user_sync_get(Node, TargetName, Oids) \n\t end, \n PostVerify = fun() -> ok end,\n do_simple_sync_get2(Config, Get, PostVerify).\n\ndo_simple_sync_get2(Config, Get, PostVerify) ->\n p(\"starting with Config: ~p~n\", [Config]),\n\n Node = ?config(manager_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n p(\"issue get-request without loading the mib\"),\n Oids1 = [?sysObjectID_instance, ?sysDescr_instance, ?sysUpTime_instance],\n ?line ok = do_simple_sync_get2(Node, TargetName, Oids1, Get, PostVerify),\n\n p(\"issue get-request after first loading the mibs\"),\n ?line ok = mgr_user_load_mib(Node, std_mib()),\n Oids2 = [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n ?line ok = do_simple_sync_get2(Node, TargetName, Oids2, Get, PostVerify),\n ok.\n\ndo_simple_sync_get2(Node, TargetName, Oids, Get, PostVerify) \n when is_function(Get, 3) andalso is_function(PostVerify, 0) ->\n ?line {ok, Reply, _Rem} = Get(Node, TargetName, Oids),\n\n ?DBG(\"~n Reply: ~p\"\n\t \"~n Rem: ~w\", [Reply, _Rem]),\n\n %% verify that the operation actually worked:\n %% The order should be the same, so no need to seach \n ?line ok = case Reply of\n\t\t {noError, 0, [#varbind{oid = ?sysObjectID_instance,\n\t\t\t\t\t value = SysObjectID}, \n\t\t\t\t #varbind{oid = ?sysDescr_instance,\n\t\t\t\t\t value = SysDescr},\n\t\t\t\t #varbind{oid = ?sysUpTime_instance,\n\t\t\t\t\t value = SysUpTime}]} ->\n\t\t p(\"expected result from get: \"\n\t\t\t \"~n SysObjectID: ~p\"\n\t\t\t \"~n SysDescr: ~s\"\n\t\t\t \"~n SysUpTime: ~w\", \n\t\t\t [SysObjectID, SysDescr, SysUpTime]),\n\t\t PostVerify();\n\t\t {noError, 0, Vbs} ->\n\t\t p(\"unexpected varbinds: ~n~p\", [Vbs]),\n\t\t {error, {unexpected_vbs, Vbs}};\n\t\t Else ->\n\t\t p(\"unexpected reply: ~n~p\", [Else]),\n\t\t {error, {unexpected_response, Else}}\n\t end,\n ok.\n\n\n%%======================================================================\n\nsimple_sync_get3(doc) -> \n [\"Simple sync get-request - Version 3 API (TargetName and send-opts)\"];\nsimple_sync_get3(suite) -> [];\nsimple_sync_get3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssg3),\n do_simple_sync_get3(Config),\n display_log(Config),\n ok.\n\ndo_simple_sync_get3(Config) ->\n Self = self(), \n Msg = simple_sync_get3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n Get = fun(Node, TargetName, Oids) -> \n\t\t mgr_user_sync_get2(Node, TargetName, Oids, SendOpts) \n\t end,\n PostVerify = \n\tfun() ->\n\t\treceive\n\t\t Msg ->\n\t\t\tok\n\t\tend\n\tend,\n do_simple_sync_get2(Config, Get, PostVerify).\n\n\n%%======================================================================\n\nsimple_async_get1(doc) -> \n [\"Simple (async) get-request - Old style (Addr & Port)\"];\nsimple_async_get1(suite) -> [];\nsimple_async_get1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, sag1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Exec = fun(Data) ->\n\t\t async_g_exec1(MgrNode, Addr, Port, Data)\n\t end,\n\n Requests = \n\t[\n\t { 1, \n\t [?sysObjectID_instance], \n\t Exec, \n\t fun(X) -> sag_verify(X, [?sysObjectID_instance]) end }, \n\t { 2, \n\t [?sysDescr_instance, ?sysUpTime_instance],\n\t Exec, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t ?sysUpTime_instance]) \n\t end }, \n\t { 3, \n\t [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n\t Exec, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t ?sysDescr_instance, \n\t\t\t\t ?sysUpTime_instance]) \n\t end }, \n\t { 4, \n\t [?sysObjectID_instance, \n\t ?sysDescr_instance, \n\t ?sysUpTime_instance],\n\t Exec, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t ?sysDescr_instance, \n\t\t\t\t ?sysUpTime_instance]) \n\t end }\n\t],\n \n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\nasync_g_exec1(Node, Addr, Port, Oids) ->\n mgr_user_async_get(Node, Addr, Port, Oids).\n\nsag_verify({noError, 0, _Vbs}, any) ->\n p(\"verified [any]\"),\n ok;\nsag_verify({noError, 0, Vbs}, Exp) ->\n ?DBG(\"verified first stage ok: \"\n\t \"~n Vbs: ~p\"\n\t \"~n Exp: ~p\", [Vbs, Exp]),\n sag_verify_vbs(Vbs, Exp);\nsag_verify(Error, _) ->\n {error, {unexpected_response, Error}}.\n\nsag_verify_vbs([], []) ->\n ?DBG(\"verified second stage ok\", []),\n ok;\nsag_verify_vbs(Vbs, []) ->\n {error, {unexpected_vbs, Vbs}};\nsag_verify_vbs([], Exp) ->\n {error, {expected_vbs, Exp}};\nsag_verify_vbs([#varbind{oid = Oid}|Vbs], [any|Exp]) ->\n p(\"verified [any] oid ~w\", [Oid]),\n sag_verify_vbs(Vbs, Exp);\nsag_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [Oid|Exp]) ->\n p(\"verified oid ~w [~p]\", [Oid, Value]),\n sag_verify_vbs(Vbs, Exp);\nsag_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [{Oid,Value}|Exp]) ->\n p(\"verified oid ~w and ~p\", [Oid, Value]),\n sag_verify_vbs(Vbs, Exp);\nsag_verify_vbs([Vb|_], [E|_]) ->\n {error, {unexpected_vb, Vb, E}}.\n\n\n%%======================================================================\n\nsimple_async_get2(doc) -> \n [\"Simple (async) get-request - Version 2 API (TargetName)\"];\nsimple_async_get2(suite) -> [];\nsimple_async_get2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sag2),\n p(\"starting with Config: ~p~n\", [Config]),\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n Get = fun(Oids) -> async_g_exec2(MgrNode, TargetName, Oids) end,\n PostVerify = fun(Res) -> Res end, \n do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify) ->\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n do_simple_async_sync_get2(fun() -> mgr_info(MgrNode) end,\n\t\t\t fun() -> agent_info(AgentNode) end,\n\t\t\t Get, PostVerify).\n\ndo_simple_async_sync_get2(MgrInfo, AgentInfo, Get, PostVerify) \n when is_function(MgrInfo, 0) andalso \n is_function(AgentInfo, 0) andalso \n is_function(Get, 1) andalso \n is_function(PostVerify, 1) ->\n Requests = \n\t[\n\t { 1, \n\t [?sysObjectID_instance], \n\t Get, \n\t fun(X) -> \n\t\t PostVerify(sag_verify(X, [?sysObjectID_instance])) end}, \n\t { 2, \n\t [?sysDescr_instance, ?sysUpTime_instance],\n\t Get, \n\t fun(X) -> \n\t\t PostVerify(sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t\t ?sysUpTime_instance]))\n\t end}, \n\t { 3, \n\t [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n\t Get, \n\t fun(X) -> \n\t\t PostVerify(sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t\t ?sysDescr_instance, \n\t\t\t\t\t ?sysUpTime_instance]))\n\t\t \n\t end}, \n\t { 4, \n\t [?sysObjectID_instance, \n\t ?sysDescr_instance, \n\t ?sysUpTime_instance],\n\t Get, \n\t fun(X) -> \n\t\t PostVerify(sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t\t ?sysDescr_instance, \n\t\t\t\t\t ?sysUpTime_instance]))\n\t end}\n\t],\n \n p(\"manager info when starting test: ~n~p\", [MgrInfo()]),\n p(\"agent info when starting test: ~n~p\", [AgentInfo()]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [MgrInfo()]),\n p(\"agent info when ending test: ~n~p\", [AgentInfo()]),\n\n ok.\n\nasync_g_exec2(Node, TargetName, Oids) ->\n mgr_user_async_get(Node, TargetName, Oids).\n\n\n%%======================================================================\n\nsimple_async_get3(doc) -> \n [\"Simple (async) get-request - Version 3 API (TargetName and send-opts)\"];\nsimple_async_get3(suite) -> [];\nsimple_async_get3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sag3),\n p(\"starting with Config: ~p~n\", [Config]),\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n Self = self(), \n Msg = simple_async_get3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n Get = fun(Oids) -> async_g_exec3(MgrNode, TargetName, Oids, SendOpts) end,\n PostVerify = fun(ok) -> receive Msg -> ok end;\n\t\t (Error) -> Error \n\t\t end,\n do_simple_async_sync_get2(Config, MgrNode, AgentNode, Get, PostVerify),\n display_log(Config),\n ok.\n\nasync_g_exec3(Node, TargetName, Oids, SendOpts) ->\n mgr_user_async_get2(Node, TargetName, Oids, SendOpts).\n\n\n%%======================================================================\n\nsimple_sync_get_next1(doc) -> [\"Simple (sync) get_next-request - \"\n\t\t\t \"Old style (Addr & Port)\"];\nsimple_sync_get_next1(suite) -> [];\nsimple_sync_get_next1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, ssgn1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n %% -- 1 --\n Oids01 = [[1,3,7,1]],\n VF01 = fun(X) -> verify_ssgn_reply1(X, [{[1,3,7,1],endOfMibView}]) end,\n ?line ok = do_simple_get_next(1, \n\t\t\t\t MgrNode, Addr, Port, Oids01, VF01),\n \n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n\n %% -- 2 --\n Oids02 = [[sysDescr], [1,3,7,1]], \n VF02 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_next(2, \n\t\t\t\t MgrNode, Addr, Port, Oids02, VF02),\n \n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n %% -- 3 --\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n Oids03 = [[TCnt2, 1]], \n VF03 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}]) \n\t end,\n ?line ok = do_simple_get_next(3, \n\t\t\t\t MgrNode, Addr, Port, Oids03, VF03),\n \n %% -- 4 --\n Oids04 = [[TCnt2, 2]], \n VF04 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}]) \n\t end,\n ?line ok = do_simple_get_next(4, \n\t\t\t\t MgrNode, Addr, Port, Oids04, VF04),\n \n %% -- 5 --\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n Oids05 = [TGenErr1], \n VF05 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}) \n\t end,\n ?line ok = do_simple_get_next(5, \n\t\t\t\t MgrNode, Addr, Port, Oids05, VF05),\n \n %% -- 6 --\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n Oids06 = [TGenErr2], \n VF06 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}) \n\t end,\n ?line ok = do_simple_get_next(6, \n\t\t\t\t MgrNode, Addr, Port, Oids06, VF06),\n \n %% -- 7 --\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n Oids07 = [[sysDescr], TGenErr3], \n VF07 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 2, \n\t\t\t\t\t [?sysDescr, TGenErr3]}) \n\t end,\n ?line ok = do_simple_get_next(7, \n\t\t\t\t MgrNode, Addr, Port, Oids07, VF07),\n \n %% -- 8 --\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n Oids08 = [TTooBig], \n VF08 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end,\n ?line ok = do_simple_get_next(8, \n\t\t\t\t MgrNode, Addr, Port, Oids08, VF08),\n \n display_log(Config),\n ok.\n\n\ndo_simple_get_next(N, Node, Addr, Port, Oids, Verify) ->\n p(\"issue get-next command ~w\", [N]),\n case mgr_user_sync_get_next(Node, Addr, Port, Oids) of\n\t{ok, Reply, _Rem} ->\n\t ?DBG(\"get-next ok:\"\n\t\t \"~n Reply: ~p\"\n\t\t \"~n Rem: ~w\", [Reply, _Rem]),\n\t Verify(Reply);\n\n\tError ->\n\t {error, {unexpected_reply, Error}}\n end.\n\n\nverify_ssgn_reply1({noError, 0, _Vbs}, any) ->\n ok;\nverify_ssgn_reply1({noError, 0, Vbs}, Expected) ->\n check_ssgn_vbs(Vbs, Expected);\nverify_ssgn_reply1(R, _) ->\n {error, {unexpected_reply, R}}.\n\nverify_ssgn_reply2({ErrStatus, ErrIdx, _Vbs}, {ErrStatus, ErrIdx, any}) ->\n ok;\nverify_ssgn_reply2({ErrStatus, ErrIdx, Vbs}, {ErrStatus, ErrIdx, Expected}) ->\n check_ssgn_vbs(Vbs, Expected);\nverify_ssgn_reply2(R, _) ->\n {error, {unexpected_reply, R}}.\n\ncheck_ssgn_vbs([], []) ->\n ok;\ncheck_ssgn_vbs(Unexpected, []) ->\n {error, {unexpected_vbs, Unexpected}};\ncheck_ssgn_vbs([], Expected) ->\n {error, {expected_vbs, Expected}};\ncheck_ssgn_vbs([#varbind{value = endOfMibView}|R], \n\t [endOfMibView|Expected]) ->\n check_ssgn_vbs(R, Expected);\ncheck_ssgn_vbs([#varbind{oid = Oid}|R], [Oid|Expected]) ->\n check_ssgn_vbs(R, Expected);\ncheck_ssgn_vbs([#varbind{oid = Oid, value = Value}|R], \n\t [{Oid, Value}|Expected]) ->\n check_ssgn_vbs(R, Expected);\ncheck_ssgn_vbs([Vb|_], [E|_]) ->\n {error, {unexpected_vb, Vb, E}}.\n\n\n%%======================================================================\n\nsimple_sync_get_next2(doc) -> \n [\"Simple (sync) get_next-request - Version 2 API (TargetName)\"];\nsimple_sync_get_next2(suite) -> [];\nsimple_sync_get_next2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgn2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n GetNext = fun(Node, TargetName, Oids) -> \n\t\t mgr_user_sync_get_next(Node, TargetName, Oids) \n\t end,\n PostVerify = fun(Res) -> Res end,\n do_simple_sync_get_next2(Config, GetNext, PostVerify),\n display_log(Config),\n ok.\n\n\ndo_simple_sync_get_next2(Config, GetNext, PostVerify) \n when is_function(GetNext, 3) andalso is_function(PostVerify, 1) ->\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n %% -- 1 --\n Oids01 = [[1,3,7,1]],\n VF01 = fun(X) -> verify_ssgn_reply1(X, [{[1,3,7,1],endOfMibView}]) end,\n ?line ok = do_simple_get_next(1, \n\t\t\t\t MgrNode, TargetName, Oids01, VF01, \n\t\t\t\t GetNext, PostVerify),\n \n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n\n %% -- 2 --\n Oids02 = [[sysDescr], [1,3,7,1]], \n VF02 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_next(2, \n\t\t\t\t MgrNode, TargetName, Oids02, VF02, \n\t\t\t\t GetNext, PostVerify),\n \n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n %% -- 3 --\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n Oids03 = [[TCnt2, 1]], \n VF03 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}]) \n\t end,\n ?line ok = do_simple_get_next(3, \n\t\t\t\t MgrNode, TargetName, Oids03, VF03, \n\t\t\t\t GetNext, PostVerify),\n \n %% -- 4 --\n Oids04 = [[TCnt2, 2]], \n VF04 = fun(X) -> \n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}]) \n\t end,\n ?line ok = do_simple_get_next(4, \n\t\t\t\t MgrNode, TargetName, Oids04, VF04, \n\t\t\t\t GetNext, PostVerify),\n \n %% -- 5 --\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n Oids05 = [TGenErr1], \n VF05 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}) \n\t end,\n ?line ok = do_simple_get_next(5, \n\t\t\t\t MgrNode, TargetName, Oids05, VF05, \n\t\t\t\t GetNext, PostVerify),\n \n %% -- 6 --\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n Oids06 = [TGenErr2], \n VF06 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}) \n\t end,\n ?line ok = do_simple_get_next(6, \n\t\t\t\t MgrNode, TargetName, Oids06, VF06, \n\t\t\t\t GetNext, PostVerify),\n \n %% -- 7 --\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n Oids07 = [[sysDescr], TGenErr3], \n VF07 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {genErr, 2, \n\t\t\t\t\t [?sysDescr, TGenErr3]}) \n\t end,\n ?line ok = do_simple_get_next(7, \n\t\t\t\t MgrNode, TargetName, Oids07, VF07, \n\t\t\t\t GetNext, PostVerify),\n \n %% -- 8 --\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n Oids08 = [TTooBig], \n VF08 = fun(X) -> \n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end,\n ?line ok = do_simple_get_next(8, \n\t\t\t\t MgrNode, TargetName, Oids08, VF08, \n\t\t\t\t GetNext, PostVerify),\n ok.\n\n\ndo_simple_get_next(N, Node, TargetName, Oids, Verify, GetNext, PostVerify) ->\n p(\"issue get-next command ~w\", [N]),\n case GetNext(Node, TargetName, Oids) of\n\t{ok, Reply, _Rem} ->\n\t ?DBG(\"get-next ok:\"\n\t\t \"~n Reply: ~p\"\n\t\t \"~n Rem: ~w\", [Reply, _Rem]),\n\t PostVerify(Verify(Reply));\n\n\tError ->\n\t {error, {unexpected_reply, Error}}\n end.\n\n\n%%======================================================================\n\nsimple_sync_get_next3(doc) -> \n [\"Simple (sync) get_next-request - \"\n \"Version 3 API (TargetName with send-opts)\"];\nsimple_sync_get_next3(suite) -> [];\nsimple_sync_get_next3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgn3),\n p(\"starting with Config: ~p~n\", [Config]),\n Self = self(), \n Msg = simple_sync_get_next3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n GetNext = fun(Node, TargetName, Oids) -> \n\t\t mgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts) \n\t end,\n PostVerify = fun(ok) -> receive Msg -> ok end;\n\t\t (Error) -> Error \n\t\t end,\n do_simple_sync_get_next2(Config, GetNext, PostVerify),\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\nsimple_async_get_next1(doc) -> [\"Simple (async) get_next-request - \"\n\t\t\t\t\"Old style (Addr & Port)\"];\nsimple_async_get_next1(suite) -> [];\nsimple_async_get_next1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, ssgn1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Exec = fun(X) ->\n\t\t async_gn_exec1(MgrNode, Addr, Port, X)\n\t end,\n\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n\n Requests = \n\t[\n\t {1, \n\t [[1,3,7,1]], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [{[1,3,7,1], endOfMibView}])\n\t end}, \n\t {2, \n\t [[sysDescr], [1,3,7,1]], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])\n\t end}, \n\t {3, \n\t [[TCnt2, 1]], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}])\n\t end}, \n\t {4, \n\t [[TCnt2, 2]], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}])\n\t end}, \n\t {5, \n\t [TGenErr1], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}) \n\t end}, \n\t {6, \n\t [TGenErr2], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}) \n\t end}, \n\t {7, \n\t [[sysDescr], TGenErr3], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}) \n\t end}, \n\t {8, \n\t [TTooBig], \n\t Exec, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end}\n\t],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\n\nasync_gn_exec1(Node, Addr, Port, Oids) ->\n mgr_user_async_get_next(Node, Addr, Port, Oids).\n\n\n%%======================================================================\n\nsimple_async_get_next2(doc) -> \n [\"Simple (async) get_next-request - Version 2 API (TargetName)\"];\nsimple_async_get_next2(suite) -> [];\nsimple_async_get_next2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgn2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n GetNext = fun(Oids) ->\n\t\t async_gn_exec2(MgrNode, TargetName, Oids)\n\t end,\n PostVerify = fun(Res) -> Res end,\n do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify) \n when is_function(GetNext, 1) andalso is_function(PostVerify, 1) ->\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n\n Requests = \n\t[\n\t {1, \n\t [[1,3,7,1]], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply1(X, [{[1,3,7,1], endOfMibView}])) \n\t\t \n\t end}, \n\t {2, \n\t [[sysDescr], [1,3,7,1]], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView]))\n\t end}, \n\t {3, \n\t [[TCnt2, 1]], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), 100}]))\n\t end}, \n\t {4, \n\t [[TCnt2, 2]], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply1(X, [{fl([TCnt2,2]), endOfMibView}]))\n\t end}, \n\t {5, \n\t [TGenErr1], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}))\n\t end}, \n\t {6, \n\t [TGenErr2], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}))\n\t end}, \n\t {7, \n\t [[sysDescr], TGenErr3], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}))\n\t end}, \n\t {8, \n\t [TTooBig], \n\t GetNext, \n\t fun(X) ->\n\t\t PostVerify(\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}))\n\t end}\n\t],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n ok.\n\n\nasync_gn_exec2(Node, TargetName, Oids) ->\n mgr_user_async_get_next(Node, TargetName, Oids).\n\n\n%%======================================================================\n\nsimple_async_get_next3(doc) -> \n [\"Simple (async) get_next-request - \"\n \"Version 3 API (TargetName with send-opts)\"];\nsimple_async_get_next3(suite) -> [];\nsimple_async_get_next3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgn2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Self = self(), \n Msg = simple_async_get_next3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n\n GetNext = fun(Oids) ->\n\t\t async_gn_exec3(MgrNode, TargetName, Oids, SendOpts)\n\t end,\n PostVerify = fun(ok) -> receive Msg -> ok end;\n\t\t (Error) -> Error \n\t\t end,\n\n do_simple_async_get_next2(MgrNode, AgentNode, GetNext, PostVerify),\n display_log(Config),\n ok.\n\nasync_gn_exec3(Node, TargetName, Oids, SendOpts) ->\n mgr_user_async_get_next2(Node, TargetName, Oids, SendOpts).\n\n\n%%======================================================================\n\nsimple_sync_set1(doc) -> [\"Simple (sync) set-request - \"\n\t\t\t \"Old style (Addr & Port)\"];\nsimple_sync_set1(suite) -> [];\nsimple_sync_set1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, sss1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n Node = ?config(manager_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n p(\"issue set-request without loading the mib\"),\n Val11 = \"Arne Anka\",\n Val12 = \"Stockholm\",\n VAVs1 = [\n\t {?sysName_instance, s, Val11},\n\t {?sysLocation_instance, s, Val12}\n\t ],\n ?line ok = do_simple_set1(Node, Addr, Port, VAVs1),\n\n p(\"issue set-request after first loading the mibs\"),\n ?line ok = mgr_user_load_mib(Node, std_mib()),\n Val21 = \"Sune Anka\",\n Val22 = \"Gothenburg\",\n VAVs2 = [\n\t {[sysName, 0], Val21},\n\t {[sysLocation, 0], Val22}\n\t ],\n ?line ok = do_simple_set1(Node, Addr, Port, VAVs2),\n\n display_log(Config),\n ok.\n\ndo_simple_set1(Node, Addr, Port, VAVs) ->\n [SysName, SysLoc] = value_of_vavs(VAVs),\n ?line {ok, Reply, _Rem} = mgr_user_sync_set(Node, Addr, Port, VAVs),\n\n ?DBG(\"~n Reply: ~p\"\n\t \"~n Rem: ~w\", [Reply, _Rem]),\n\n %% verify that the operation actually worked:\n %% The order should be the same, so no need to seach \n %% The value we get should be exactly the same as we sent\n ?line ok = case Reply of\n\t\t {noError, 0, [#varbind{oid = ?sysName_instance,\n\t\t\t\t\t value = SysName},\n\t\t\t\t #varbind{oid = ?sysLocation_instance,\n\t\t\t\t\t value = SysLoc}]} ->\n\t\t ok;\n\t\t {noError, 0, Vbs} ->\n\t\t {error, {unexpected_vbs, Vbs}};\n\t\t Else ->\n\t\t p(\"unexpected reply: ~n~p\", [Else]),\n\t\t {error, {unexpected_response, Else}}\n\t end,\n ok.\n\nvalue_of_vavs(VAVs) ->\n value_of_vavs(VAVs, []).\n\nvalue_of_vavs([], Acc) ->\n lists:reverse(Acc);\nvalue_of_vavs([{_Oid, _Type, Val}|VAVs], Acc) ->\n value_of_vavs(VAVs, [Val|Acc]);\nvalue_of_vavs([{_Oid, Val}|VAVs], Acc) ->\n value_of_vavs(VAVs, [Val|Acc]).\n\n\t\t\t \n%%======================================================================\n\nsimple_sync_set2(doc) -> \n [\"Simple (sync) set-request - Version 2 API (TargetName)\"];\nsimple_sync_set2(suite) -> [];\nsimple_sync_set2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sss2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n Set = fun(Node, TargetName, VAVs) -> \n\t\t mgr_user_sync_set(Node, TargetName, VAVs) \n\t end,\n PostVerify = fun() -> ok end,\n\n do_simple_sync_set2(Config, Set, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_sync_set2(Config, Set, PostVerify) \n when is_function(Set, 3) andalso is_function(PostVerify, 0) ->\n\n Node = ?config(manager_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n p(\"issue set-request without loading the mib\"),\n Val11 = \"Arne Anka\",\n Val12 = \"Stockholm\",\n VAVs1 = [\n\t {?sysName_instance, s, Val11},\n\t {?sysLocation_instance, s, Val12}\n\t ],\n ?line ok = do_simple_set2(Node, TargetName, VAVs1, Set, PostVerify),\n\n p(\"issue set-request after first loading the mibs\"),\n ?line ok = mgr_user_load_mib(Node, std_mib()),\n Val21 = \"Sune Anka\",\n Val22 = \"Gothenburg\",\n VAVs2 = [\n\t {[sysName, 0], Val21},\n\t {[sysLocation, 0], Val22}\n\t ],\n ?line ok = do_simple_set2(Node, TargetName, VAVs2, Set, PostVerify),\n ok.\n\ndo_simple_set2(Node, TargetName, VAVs, Set, PostVerify) ->\n [SysName, SysLoc] = value_of_vavs(VAVs),\n ?line {ok, Reply, _Rem} = Set(Node, TargetName, VAVs),\n\n ?DBG(\"~n Reply: ~p\"\n\t \"~n Rem: ~w\", [Reply, _Rem]),\n\n %% verify that the operation actually worked:\n %% The order should be the same, so no need to seach \n %% The value we get should be exactly the same as we sent\n ?line ok = case Reply of\n\t\t {noError, 0, [#varbind{oid = ?sysName_instance,\n\t\t\t\t\t value = SysName},\n\t\t\t\t #varbind{oid = ?sysLocation_instance,\n\t\t\t\t\t value = SysLoc}]} ->\n\t\t PostVerify();\n\t\t {noError, 0, Vbs} ->\n\t\t {error, {unexpected_vbs, Vbs}};\n\t\t Else ->\n\t\t p(\"unexpected reply: ~n~p\", [Else]),\n\t\t {error, {unexpected_response, Else}}\n\t end,\n ok.\n\n\n%%======================================================================\n\nsimple_sync_set3(doc) -> \n [\"Simple (sync) set-request - Version 3 API (TargetName with send-opts)\"];\nsimple_sync_set3(suite) -> [];\nsimple_sync_set3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sss3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n Self = self(), \n Msg = simple_sync_set3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n \n Set = fun(Node, TargetName, VAVs) -> \n\t\t mgr_user_sync_set2(Node, TargetName, VAVs, SendOpts) \n\t end,\n PostVerify = fun() -> receive Msg -> ok end end,\n\n do_simple_sync_set2(Config, Set, PostVerify),\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\nsimple_async_set1(doc) -> [\"Simple (async) set-request - \"\n\t\t\t \"Old style (Addr & Port)\"];\nsimple_async_set1(suite) -> [];\nsimple_async_set1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, sas1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Exec = fun(X) ->\n\t\t async_s_exec1(MgrNode, Addr, Port, X)\n\t end,\n\n Requests = \n\t[\n\t {1,\n\t [{?sysName_instance, s, \"Arne Anka\"}],\n\t Exec,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysName_instance])\n\t end},\n\t {2,\n\t [{?sysLocation_instance, s, \"Stockholm\"}, \n\t {?sysName_instance, s, \"Arne Anka\"}],\n\t Exec,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysLocation_instance, ?sysName_instance])\n\t end},\n\t {3,\n\t [{[sysName, 0], \"Gothenburg\"}, \n\t {[sysLocation, 0], \"Sune Anka\"}],\n\t Exec,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysName_instance, ?sysLocation_instance])\n\t end}\n\t],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\n\nasync_s_exec1(Node, Addr, Port, VAVs) ->\n mgr_user_async_set(Node, Addr, Port, VAVs).\n\nsas_verify({noError, 0, _Vbs}, any) ->\n p(\"verified [any]\"),\n ok;\nsas_verify({noError, 0, Vbs}, Expected) ->\n ?DBG(\"verified stage 1: \"\n\t \"~n Vbs: ~p\"\n\t \"~n Exp: ~p\", [Vbs, Expected]),\n sas_verify_vbs(Vbs, Expected);\nsas_verify(Error, _) ->\n {error, {unexpected_reply, Error}}.\n\nsas_verify_vbs([], []) ->\n ok;\nsas_verify_vbs(Vbs, []) ->\n {error, {unexpected_vbs, Vbs}};\nsas_verify_vbs([], Exp) ->\n {error, {expected_vbs, Exp}};\nsas_verify_vbs([#varbind{oid = Oid}|Vbs], [any|Exp]) ->\n p(\"verified [any] oid ~w\", [Oid]),\n sas_verify_vbs(Vbs, Exp);\nsas_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [Oid|Exp]) ->\n p(\"verified oid ~w [~p]\", [Oid, Value]),\n sas_verify_vbs(Vbs, Exp);\nsas_verify_vbs([#varbind{oid = Oid, value = Value}|Vbs], [{Oid,Value}|Exp]) ->\n p(\"verified oid ~w and ~p\", [Oid, Value]),\n sas_verify_vbs(Vbs, Exp);\nsas_verify_vbs([Vb|_], [E|_]) ->\n {error, {unexpected_vb, Vb, E}}.\n\n \n%%======================================================================\n\nsimple_async_set2(doc) -> \n [\"Simple (async) set-request - Version 2 API (TargetName)\"];\nsimple_async_set2(suite) -> [];\nsimple_async_set2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sas2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Set = \n\tfun(Oids) ->\n\t\tasync_s_exec2(MgrNode, TargetName, Oids)\n\tend,\n PostVerify = fun(Res) -> Res end,\n\n do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_async_set2(MgrNode, AgentNode, Set, PostVerify) ->\n Requests = \n\t[\n\t {1,\n\t [{?sysName_instance, s, \"Arne Anka\"}],\n\t Set,\n\t fun(X) ->\n\t\t PostVerify(sas_verify(X, [?sysName_instance]))\n\t end},\n\t {2,\n\t [{?sysLocation_instance, s, \"Stockholm\"}, \n\t {?sysName_instance, s, \"Arne Anka\"}],\n\t Set,\n\t fun(X) ->\n\t\t PostVerify(sas_verify(X, \n\t\t\t\t\t[?sysLocation_instance, \n\t\t\t\t\t ?sysName_instance]))\n\t end},\n\t {3,\n\t [{[sysName, 0], \"Gothenburg\"}, \n\t {[sysLocation, 0], \"Sune Anka\"}],\n\t Set,\n\t fun(X) ->\n\t\t PostVerify(sas_verify(X, \n\t\t\t\t\t[?sysName_instance, \n\t\t\t\t\t ?sysLocation_instance]))\n\t end}\n\t],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n ok.\n\n\nasync_s_exec2(Node, TargetName, VAVs) ->\n mgr_user_async_set(Node, TargetName, VAVs).\n\n\n%%======================================================================\n\nsimple_async_set3(doc) -> \n [\"Simple (async) set-request - Version 3 API (TargetName with send-opts)\"];\nsimple_async_set3(suite) -> [];\nsimple_async_set3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sas3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Self = self(), \n Msg = simple_async_set3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n\n Set = \n\tfun(Oids) ->\n\t\tasync_s_exec3(MgrNode, TargetName, Oids, SendOpts)\n\tend,\n PostVerify = fun(ok) -> receive Msg -> ok end; \n\t\t (Res) -> Res \n\t\t end,\n\n do_simple_async_set2(MgrNode, AgentNode, Set, PostVerify),\n display_log(Config),\n ok.\n\nasync_s_exec3(Node, TargetName, VAVs, SendOpts) ->\n mgr_user_async_set2(Node, TargetName, VAVs, SendOpts).\n\n\n%%======================================================================\n\nsimple_sync_get_bulk1(doc) -> [\"Simple (sync) get_bulk-request - \"\n\t\t\t \"Old style (Addr & Port)\"];\nsimple_sync_get_bulk1(suite) -> [];\nsimple_sync_get_bulk1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, ssgb1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n %% -- 1 --\n ?line ok = do_simple_get_bulk1(1,\n\t\t\t\t MgrNode, Addr, Port, 1, 1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1), \n\n %% -- 2 --\n ?line ok = do_simple_get_bulk1(2, \n\t\t\t\t MgrNode, Addr, Port, -1, 1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1), \n\n %% -- 3 --\n ?line ok = do_simple_get_bulk1(3, \n\t\t\t\t MgrNode, Addr, Port, -1, -1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1), \n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n %% -- 4 --\n VF04 = fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk1(4,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 2, 0, [[sysDescr],[1,3,7,1]], VF04),\n\n %% -- 5 --\n ?line ok = do_simple_get_bulk1(5,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 1, 2, [[sysDescr],[1,3,7,1]], VF04),\n\n %% -- 6 --\n VF06 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk1(6,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 0, 2, [[sysDescr],[1,3,7,1]], VF06), \n\n %% -- 7 --\n VF07 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk1(7,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 2, 2, \n\t\t\t\t [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]],\n\t\t\t\t VF07), \n\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n %% -- 8 --\n VF08 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, \n\t\t\t\t ?sysDescr_instance]) \n\t end,\n ?line ok = do_simple_get_bulk1(8,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 1, 2, \n\t\t\t\t [[sysDescr],[sysDescr],[tTooBig]],\n\t\t\t\t VF08), \n\n %% -- 9 --\n ?line ok = do_simple_get_bulk1(9,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 1, 12, \n\t\t\t\t [[tDescr2], [sysDescr]], \n\t\t\t\t fun verify_ssgb_reply1\/1),\n\n %% -- 10 --\n VF10 = fun(X) -> \n\t\t verify_ssgb_reply3(X, \n\t\t\t\t [{?sysDescr, 'NULL'}, \n\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t {?sysDescr, 'NULL'}]) \n\t end,\n ?line ok = do_simple_get_bulk1(10,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 2, 2, \n\t\t\t\t [[sysDescr], \n\t\t\t\t [sysObjectID], \n\t\t\t\t [tGenErr1], \n\t\t\t\t [sysDescr]],\n\t\t\t\t VF10), \n\n %% -- 11 --\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n p(\"TCnt2: ~p\", [TCnt2]),\n VF11 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [{fl([TCnt2,2]), 100}, \n\t\t\t\t {fl([TCnt2,2]), endOfMibView}]) \n\t end,\n ?line ok = do_simple_get_bulk1(11,\n\t\t\t\t MgrNode, Addr, Port, \n\t\t\t\t 0, 2, \n\t\t\t\t [[TCnt2, 1]], VF11),\n\n display_log(Config),\n ok.\n\nfl(L) ->\n lists:flatten(L).\n\ndo_simple_get_bulk1(N, Node, Addr, Port, NonRep, MaxRep, Oids, Verify) ->\n p(\"issue get-bulk command ~w\", [N]),\n case mgr_user_sync_get_bulk(Node, Addr, Port, NonRep, MaxRep, Oids) of\n\t{ok, Reply, _Rem} ->\n\t ?DBG(\"get-bulk ok:\"\n\t\t \"~n Reply: ~p\"\n\t\t \"~n Rem: ~w\", [Reply, _Rem]),\n\t Verify(Reply);\n\n\tError ->\n\t {error, {unexpected_reply, Error}}\n end.\n\nverify_ssgb_reply1({noError, 0, []}) ->\n ok;\nverify_ssgb_reply1(X) ->\n {error, {unexpected_reply, X}}.\n\nverify_ssgb_reply2({noError, 0, Vbs}, ExpectedVbs) ->\n check_ssgb_vbs(Vbs, ExpectedVbs);\nverify_ssgb_reply2(Error, _) ->\n {error, {unexpected_reply, Error}}.\n\nverify_ssgb_reply3({genErr, 3, Vbs}, ExpectedVbs) ->\n check_ssgb_vbs(Vbs, ExpectedVbs);\nverify_ssgb_reply3(Unexpected, _) ->\n {error, {unexpected_reply, Unexpected}}.\n\ncheck_ssgb_vbs([], []) ->\n ok;\ncheck_ssgb_vbs(Unexpected, []) ->\n {error, {unexpected_vbs, Unexpected}};\ncheck_ssgb_vbs([], Expected) ->\n {error, {expected_vbs, Expected}};\ncheck_ssgb_vbs([#varbind{value = endOfMibView}|R], \n\t [endOfMibView|Expected]) ->\n check_ssgb_vbs(R, Expected);\ncheck_ssgb_vbs([#varbind{oid = Oid}|R], [Oid|Expected]) ->\n check_ssgb_vbs(R, Expected);\ncheck_ssgb_vbs([#varbind{oid = Oid, value = Value}|R], \n\t [{Oid, Value}|Expected]) ->\n check_ssgb_vbs(R, Expected);\ncheck_ssgb_vbs([R|_], [E|_]) ->\n {error, {unexpected_vb, R, E}}.\n\n\n%%======================================================================\n\nsimple_sync_get_bulk2(doc) -> \n [\"Simple (sync) get_bulk-request - Version 2 API (TargetName)\"];\nsimple_sync_get_bulk2(suite) -> [];\nsimple_sync_get_bulk2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgb2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n GetBulk = \n\tfun(NonRep, MaxRep, Oids) ->\n\t\tmgr_user_sync_get_bulk(MgrNode, TargetName, \n\t\t\t\t NonRep, MaxRep, Oids) \n\tend,\n PostVerify = fun(Res) -> Res end,\n\n do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify) ->\n %% -- 1 --\n ?line ok = do_simple_get_bulk2(1,\n\t\t\t\t 1, 1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1, \n\t\t\t\t GetBulk, PostVerify), \n \n %% -- 2 --\n ?line ok = do_simple_get_bulk2(2, \n\t\t\t\t -1, 1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1, \n\t\t\t\t GetBulk, PostVerify), \n\n %% -- 3 --\n ?line ok = do_simple_get_bulk2(3, \n\t\t\t\t -1, -1, [], \n\t\t\t\t fun verify_ssgb_reply1\/1, \n\t\t\t\t GetBulk, PostVerify), \n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n %% -- 4 --\n VF04 = fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk2(4,\n\t\t\t\t 2, 0, [[sysDescr],[1,3,7,1]], VF04, \n\t\t\t\t GetBulk, PostVerify),\n\n %% -- 5 --\n ?line ok = do_simple_get_bulk2(5,\n\t\t\t\t 1, 2, [[sysDescr],[1,3,7,1]], VF04, \n\t\t\t\t GetBulk, PostVerify),\n\n %% -- 6 --\n VF06 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk2(6,\n\t\t\t\t 0, 2, [[sysDescr],[1,3,7,1]], VF06, \n\t\t\t\t GetBulk, PostVerify), \n\n %% -- 7 --\n VF07 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n ?line ok = do_simple_get_bulk2(7,\n\t\t\t\t 2, 2, \n\t\t\t\t [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]],\n\t\t\t\t VF07, \n\t\t\t\t GetBulk, PostVerify), \n\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n %% -- 8 --\n VF08 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, \n\t\t\t\t ?sysDescr_instance]) \n\t end,\n ?line ok = do_simple_get_bulk2(8,\n\t\t\t\t 1, 2, \n\t\t\t\t [[sysDescr],[sysDescr],[tTooBig]],\n\t\t\t\t VF08, \n\t\t\t\t GetBulk, PostVerify), \n\n %% -- 9 --\n ?line ok = do_simple_get_bulk2(9,\n\t\t\t\t 1, 12, \n\t\t\t\t [[tDescr2], [sysDescr]], \n\t\t\t\t fun verify_ssgb_reply1\/1, \n\t\t\t\t GetBulk, PostVerify),\n\n %% -- 10 --\n VF10 = fun(X) -> \n\t\t verify_ssgb_reply3(X, \n\t\t\t\t [{?sysDescr, 'NULL'}, \n\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t {?sysDescr, 'NULL'}]) \n\t end,\n ?line ok = do_simple_get_bulk2(10,\n\t\t\t\t 2, 2, \n\t\t\t\t [[sysDescr], \n\t\t\t\t [sysObjectID], \n\t\t\t\t [tGenErr1], \n\t\t\t\t [sysDescr]],\n\t\t\t\t VF10, \n\t\t\t\t GetBulk, PostVerify), \n\n %% -- 11 --\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n p(\"TCnt2: ~p\", [TCnt2]),\n VF11 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [{fl([TCnt2,2]), 100}, \n\t\t\t\t {fl([TCnt2,2]), endOfMibView}]) \n\t end,\n ?line ok = do_simple_get_bulk2(11,\n\t\t\t\t 0, 2, \n\t\t\t\t [[TCnt2, 1]], VF11, \n\t\t\t\t GetBulk, PostVerify),\n \n ok.\n\ndo_simple_get_bulk2(N, \n\t\t NonRep, MaxRep, Oids, \n\t\t Verify, GetBulk, PostVerify) \n when is_function(Verify, 1) andalso \n is_function(GetBulk, 3) andalso \n is_function(PostVerify) ->\n p(\"issue get-bulk command ~w\", [N]),\n case GetBulk(NonRep, MaxRep, Oids) of\n\t{ok, Reply, _Rem} ->\n\t ?DBG(\"get-bulk ok:\"\n\t\t \"~n Reply: ~p\"\n\t\t \"~n Rem: ~w\", [Reply, _Rem]),\n\t PostVerify(Verify(Reply));\n\n\tError ->\n\t {error, {unexpected_reply, Error}}\n end.\n\n\n%%======================================================================\n\nsimple_sync_get_bulk3(doc) -> \n [\"Simple (sync) get_bulk-request - \"\n \"Version 3 API (TargetName with send-opts)\"];\nsimple_sync_get_bulk3(suite) -> [];\nsimple_sync_get_bulk3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ssgb3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n Self = self(), \n Msg = simple_async_set3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n\n GetBulk = \n\tfun(NonRep, MaxRep, Oids) ->\n\t\tmgr_user_sync_get_bulk2(MgrNode, TargetName, \n\t\t\t\t\tNonRep, MaxRep, Oids, SendOpts) \n\tend,\n PostVerify = fun(ok) -> receive Msg -> ok end;\n\t\t (Res) -> Res \n\t\t end,\n\n do_simple_sync_get_bulk2(Config, MgrNode, AgentNode, GetBulk, PostVerify),\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\nsimple_async_get_bulk1(doc) -> [\"Simple (async) get_bulk-request - \"\n\t\t\t\t\"Old style (Addr & Port)\"];\nsimple_async_get_bulk1(suite) -> [];\nsimple_async_get_bulk1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, sagb1),\n p(\"starting with Config: ~p~n\", [Config]),\n \n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Exec = fun(Data) ->\n\t\t async_gb_exec1(MgrNode, Addr, Port, Data)\n\t end,\n\n %% We re-use the verification functions from the ssgb test-case\n VF04 = fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end,\n VF06 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n VF07 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end,\n VF08 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, \n\t\t\t\t ?sysDescr_instance]) \n\t end,\n VF10 = fun(X) -> \n\t\t verify_ssgb_reply3(X, \n\t\t\t\t [{?sysDescr, 'NULL'}, \n\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t {?sysDescr, 'NULL'}]) \n\t end,\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n VF11 = fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [{fl([TCnt2,2]), 100}, \n\t\t\t\t {fl([TCnt2,2]), endOfMibView}]) \n\t end,\n Requests = [\n\t\t{ 1, \n\t\t {1, 1, []}, \n\t\t Exec, \n\t\t fun verify_ssgb_reply1\/1},\n\t\t{ 2, \n\t\t {-1, 1, []}, \n\t\t Exec, \n\t\t fun verify_ssgb_reply1\/1},\n\t\t{ 3, \n\t\t {-1, -1, []}, \n\t\t Exec, \n\t\t fun verify_ssgb_reply1\/1},\n\t\t{ 4, \n\t\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t\t Exec, \n\t\t VF04},\n\t\t{ 5, \n\t\t {1, 2, [[sysDescr],[1,3,7,1]]}, \n\t\t Exec, \n\t\t VF04},\n\t\t{ 6, \n\t\t {0, 2, [[sysDescr],[1,3,7,1]]}, \n\t\t Exec, \n\t\t VF06},\n\t\t{ 7, \n\t\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]}, \n\t\t Exec, \n\t\t VF07},\n\t\t{ 8, \n\t\t {1, 2, [[sysDescr],[sysDescr],[tTooBig]]}, \n\t\t Exec, \n\t\t VF08},\n\t\t{ 9, \n\t\t {1, 12, [[tDescr2], [sysDescr]]}, \n\t\t Exec, \n\t\t fun verify_ssgb_reply1\/1},\n\t\t{10, \n\t\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]}, \n\t\t Exec, \n\t\t VF10},\n\t\t{11, \n\t\t {0, 2, [[TCnt2, 1]]}, \n\t\t Exec,\n\t\t VF11}, \n\t\t{12, \n\t\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t\t Exec,\n\t\t VF04},\n\t\t{13, \n\t\t {1, 12, [[tDescr2], [sysDescr]]},\n\t\t Exec, \n\t\t fun verify_ssgb_reply1\/1},\n\t\t{14, \n\t\t {2, 2, [[sysDescr],[sysObjectID],[tGenErr1],[sysDescr]]},\n\t\t Exec, \n\t\t VF10},\n\t\t{15, \n\t\t {0, 2, [[TCnt2, 1]]},\n\t\t Exec, \n\t\t VF11},\n\t\t{16, \n\t\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},\n\t\t Exec, \n\t\t VF07},\n\t\t{17, \n\t\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},\n\t\t Exec, \n\t\t VF10}\n\t ],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\n\nasync_gb_exec1(Node, Addr, Port, {NR, MR, Oids}) ->\n mgr_user_async_get_bulk(Node, Addr, Port, NR, MR, Oids).\n\n\n%%======================================================================\n\nsimple_async_get_bulk2(doc) -> \n [\"Simple (async) get_bulk-request - Version 2 API (TargetName)\"];\nsimple_async_get_bulk2(suite) -> [];\nsimple_async_get_bulk2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sagb2),\n p(\"starting with Config: ~p~n\", [Config]),\n \n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n GetBulk = \n\tfun(Data) ->\n\t\tasync_gb_exec2(MgrNode, TargetName, Data)\n\tend,\n PostVerify = fun(Res) -> Res end,\n\n do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify),\n display_log(Config),\n ok.\n\ndo_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify) ->\n %% We re-use the verification functions from the ssgb test-case\n VF04 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]))\n\t end,\n VF06 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply2(X, \n\t\t\t\t\t[?sysDescr_instance, endOfMibView,\n\t\t\t\t\t ?sysObjectID_instance, endOfMibView]))\n\t end,\n VF07 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply2(X, \n\t\t\t\t\t[?sysDescr_instance, endOfMibView,\n\t\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t\t ?sysObjectID_instance, endOfMibView]))\n\t end,\n VF08 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply2(X, \n\t\t\t\t\t[?sysDescr_instance, \n\t\t\t\t\t ?sysDescr_instance])) \n\t end,\n VF10 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply3(X, \n\t\t\t\t\t[{?sysDescr, 'NULL'}, \n\t\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t\t {?sysDescr, 'NULL'}])) \n\t end,\n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n VF11 = fun(X) -> \n\t\t PostVerify(\n\t\t verify_ssgb_reply2(X, \n\t\t\t\t\t[{fl([TCnt2,2]), 100}, \n\t\t\t\t\t {fl([TCnt2,2]), endOfMibView}]))\n\t end,\n Requests = [\n\t\t{ 1, \n\t\t {1, 1, []}, \n\t\t GetBulk, \n\t\t fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},\n\t\t{ 2, \n\t\t {-1, 1, []}, \n\t\t GetBulk, \n\t\t fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},\n\t\t{ 3, \n\t\t {-1, -1, []}, \n\t\t GetBulk, \n\t\t fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},\n\t\t{ 4, \n\t\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t\t GetBulk, \n\t\t VF04},\n\t\t{ 5, \n\t\t {1, 2, [[sysDescr],[1,3,7,1]]}, \n\t\t GetBulk, \n\t\t VF04},\n\t\t{ 6, \n\t\t {0, 2, [[sysDescr],[1,3,7,1]]}, \n\t\t GetBulk, \n\t\t VF06},\n\t\t{ 7, \n\t\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]}, \n\t\t GetBulk, \n\t\t VF07},\n\t\t{ 8, \n\t\t {1, 2, [[sysDescr],[sysDescr],[tTooBig]]}, \n\t\t GetBulk, \n\t\t VF08},\n\t\t{ 9, \n\t\t {1, 12, [[tDescr2], [sysDescr]]}, \n\t\t GetBulk, \n\t\t fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},\n\t\t{10, \n\t\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]}, \n\t\t GetBulk, \n\t\t VF10},\n\t\t{11, \n\t\t {0, 2, [[TCnt2, 1]]}, \n\t\t GetBulk,\n\t\t VF11}, \n\t\t{12, \n\t\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t\t GetBulk,\n\t\t VF04},\n\t\t{13, \n\t\t {1, 12, [[tDescr2], [sysDescr]]},\n\t\t GetBulk, \n\t\t fun(X) -> PostVerify(verify_ssgb_reply1(X)) end},\n\t\t{14, \n\t\t {2, 2, [[sysDescr],[sysObjectID],[tGenErr1],[sysDescr]]},\n\t\t GetBulk, \n\t\t VF10},\n\t\t{15, \n\t\t {0, 2, [[TCnt2, 1]]},\n\t\t GetBulk, \n\t\t VF11},\n\t\t{16, \n\t\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]},\n\t\t GetBulk, \n\t\t VF07},\n\t\t{17, \n\t\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]},\n\t\t GetBulk, \n\t\t VF10}\n\t ],\n\n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n ok.\n\n\nasync_gb_exec2(Node, TargetName, {NR, MR, Oids}) ->\n mgr_user_async_get_bulk(Node, TargetName, NR, MR, Oids).\n\n\n%%======================================================================\n\nsimple_async_get_bulk3(doc) -> \n [\"Simple (async) get_bulk-request - \"\n \"Version 3 API (TargetName with send-opts)\"];\nsimple_async_get_bulk3(suite) -> [];\nsimple_async_get_bulk3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, sagb3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n\n Self = self(), \n Msg = simple_async_get_bulk3, \n Fun = fun() -> Self ! Msg end,\n Extra = {?SNMPM_EXTRA_INFO_TAG, Fun}, \n SendOpts = \n\t[\n\t {extra, Extra}\n\t], \n\n GetBulk = \n\tfun(Data) ->\n\t\tasync_gb_exec3(MgrNode, TargetName, Data, SendOpts)\n\tend,\n PostVerify = fun(ok) -> receive Msg -> ok end;\n\t\t (Res) -> Res \n\t\t end,\n\n do_simple_async_get_bulk2(MgrNode, AgentNode, GetBulk, PostVerify),\n display_log(Config),\n ok.\n\nasync_gb_exec3(Node, TargetName, {NR, MR, Oids}, SendOpts) ->\n mgr_user_async_get_bulk2(Node, TargetName, NR, MR, Oids, SendOpts).\n\n\n%%======================================================================\n\nmisc_async1(doc) -> [\"Misc (async) request(s) - \"\n\t\t \"Old style (Addr & Port)\"];\nmisc_async1(suite) -> [];\nmisc_async1(Config) when is_list(Config) ->\n ?SKIP(api_no_longer_supported), \n\n process_flag(trap_exit, true),\n put(tname, ms1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n Addr = ?config(ip, Config),\n Port = ?AGENT_PORT,\n \n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n \n ExecG = fun(Data) ->\n\t\t async_g_exec1(MgrNode, Addr, Port, Data)\n\t end,\n \n ExecGN = fun(Data) ->\n\t\t async_gn_exec1(MgrNode, Addr, Port, Data)\n\t end,\n \n ExecS = fun(Data) ->\n\t\t async_s_exec1(MgrNode, Addr, Port, Data)\n\t end,\n \n ExecGB = fun(Data) ->\n\t\t async_gb_exec1(MgrNode, Addr, Port, Data)\n\t end,\n \n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n\n Requests = \n\t[\n\t { 1, \n\t [?sysObjectID_instance], \n\t ExecG, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance]) \n\t end\n\t },\n\t { 2, \n\t {1, 1, []}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t { 3, \n\t {-1, 1, []}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t { 4,\n\t [{?sysLocation_instance, s, \"Stockholm\"}, \n\t {?sysName_instance, s, \"Arne Anka\"}],\n\t ExecS,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysLocation_instance, ?sysName_instance])\n\t end}, \n\t { 5, \n\t [[sysDescr], [1,3,7,1]], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])\n\t end}, \n\t { 6, \n\t [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n\t ExecG, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t ?sysDescr_instance, \n\t\t\t\t ?sysUpTime_instance]) \n\t end}, \n\t { 7, \n\t [TGenErr2], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}) \n\t end}, \n\t { 8, \n\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end},\n\t { 9, \n\t {1, 2, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end},\n\t {10, \n\t [TGenErr1], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}) \n\t end}, \n\t {11, \n\t {0, 2, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end},\n\t {12,\n\t [{[sysName, 0], \"Gothenburg\"}, \n\t {[sysLocation, 0], \"Sune Anka\"}],\n\t ExecS,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysName_instance, ?sysLocation_instance])\n\t end},\n\t {13, \n\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end},\n\t {14, \n\t {1, 2, [[sysDescr],[sysDescr],[tTooBig]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, \n\t\t\t\t ?sysDescr_instance]) \n\t end},\n\t {15, \n\t {1, 12, [[tDescr2], [sysDescr]]}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t {16, \n\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply3(X, \n\t\t\t\t [{?sysDescr, 'NULL'}, \n\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t {?sysDescr, 'NULL'}]) \n\t end},\n\t {17, \n\t [[sysDescr], TGenErr3], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}) \n\t end}, \n\t {18, \n\t {0, 2, [[TCnt2, 1]]}, \n\t ExecGB,\n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [{fl([TCnt2,2]), 100}, \n\t\t\t\t {fl([TCnt2,2]), endOfMibView}]) \n\t end},\n\t {19, \n\t [TTooBig], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end},\n\t {20, \n\t [TTooBig], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end}\n\t],\n \n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\nmisc_async2(doc) -> \n [\"Misc (async) request(s) - Version 2 API (TargetName)\"];\nmisc_async2(suite) -> [];\nmisc_async2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, ms2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n TargetName = ?config(manager_agent_target_name, Config),\n \n ?line ok = mgr_user_load_mib(MgrNode, std_mib()),\n Test2Mib = test2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n \n ExecG = fun(Data) ->\n\t\t async_g_exec2(MgrNode, TargetName, Data)\n\t end,\n \n ExecGN = fun(Data) ->\n\t\t async_gn_exec2(MgrNode, TargetName, Data)\n\t end,\n \n ExecS = fun(Data) ->\n\t\t async_s_exec2(MgrNode, TargetName, Data)\n\t end,\n \n ExecGB = fun(Data) ->\n\t\t async_gb_exec2(MgrNode, TargetName, Data)\n\t end,\n \n ?line {ok, [TCnt2|_]} = mgr_user_name_to_oid(MgrNode, tCnt2),\n ?line {ok, [TGenErr1|_]} = mgr_user_name_to_oid(MgrNode, tGenErr1),\n ?line {ok, [TGenErr2|_]} = mgr_user_name_to_oid(MgrNode, tGenErr2),\n ?line {ok, [TGenErr3|_]} = mgr_user_name_to_oid(MgrNode, tGenErr3),\n ?line {ok, [TTooBig|_]} = mgr_user_name_to_oid(MgrNode, tTooBig),\n\n Requests = \n\t[\n\t { 1, \n\t [?sysObjectID_instance], \n\t ExecG, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance]) \n\t end\n\t },\n\t { 2, \n\t {1, 1, []}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t { 3, \n\t {-1, 1, []}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t { 4,\n\t [{?sysLocation_instance, s, \"Stockholm\"}, \n\t {?sysName_instance, s, \"Arne Anka\"}],\n\t ExecS,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysLocation_instance, ?sysName_instance])\n\t end}, \n\t { 5, \n\t [[sysDescr], [1,3,7,1]], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply1(X, [?sysDescr_instance, endOfMibView])\n\t end}, \n\t { 6, \n\t [[sysObjectID, 0], [sysDescr, 0], [sysUpTime, 0]],\n\t ExecG, \n\t fun(X) -> \n\t\t sag_verify(X, [?sysObjectID_instance, \n\t\t\t\t ?sysDescr_instance, \n\t\t\t\t ?sysUpTime_instance]) \n\t end}, \n\t { 7, \n\t [TGenErr2], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr2]}) \n\t end}, \n\t { 8, \n\t {2, 0, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end},\n\t { 9, \n\t {1, 2, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, [?sysDescr_instance, endOfMibView]) \n\t end},\n\t {10, \n\t [TGenErr1], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 1, [TGenErr1]}) \n\t end}, \n\t {11, \n\t {0, 2, [[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end},\n\t {12,\n\t [{[sysName, 0], \"Gothenburg\"}, \n\t {[sysLocation, 0], \"Sune Anka\"}],\n\t ExecS,\n\t fun(X) ->\n\t\t sas_verify(X, [?sysName_instance, ?sysLocation_instance])\n\t end},\n\t {13, \n\t {2, 2, [[sysDescr],[1,3,7,1],[sysDescr],[1,3,7,1]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysDescr_instance, endOfMibView,\n\t\t\t\t ?sysObjectID_instance, endOfMibView]) \n\t end},\n\t {14, \n\t {1, 2, [[sysDescr],[sysDescr],[tTooBig]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [?sysDescr_instance, \n\t\t\t\t ?sysDescr_instance]) \n\t end},\n\t {15, \n\t {1, 12, [[tDescr2], [sysDescr]]}, \n\t ExecGB, \n\t fun verify_ssgb_reply1\/1},\n\t {16, \n\t {2, 2, [[sysDescr],[sysObjectID], [tGenErr1],[sysDescr]]}, \n\t ExecGB, \n\t fun(X) -> \n\t\t verify_ssgb_reply3(X, \n\t\t\t\t [{?sysDescr, 'NULL'}, \n\t\t\t\t {?sysObjectID, 'NULL'},\n\t\t\t\t {?tGenErr1, 'NULL'},\n\t\t\t\t {?sysDescr, 'NULL'}]) \n\t end},\n\t {17, \n\t [[sysDescr], TGenErr3], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {genErr, 2, [TGenErr3]}) \n\t end}, \n\t {18, \n\t {0, 2, [[TCnt2, 1]]}, \n\t ExecGB,\n\t fun(X) -> \n\t\t verify_ssgb_reply2(X, \n\t\t\t\t [{fl([TCnt2,2]), 100}, \n\t\t\t\t {fl([TCnt2,2]), endOfMibView}]) \n\t end},\n\t {19, \n\t [TTooBig], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end},\n\t {20, \n\t [TTooBig], \n\t ExecGN, \n\t fun(X) ->\n\t\t verify_ssgn_reply2(X, {tooBig, 0, []}) \n\t end}\n\t],\n \n p(\"manager info when starting test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when starting test: ~n~p\", [agent_info(AgentNode)]),\n\n ?line ok = async_exec(Requests, []),\n\n p(\"manager info when ending test: ~n~p\", [mgr_info(MgrNode)]),\n p(\"agent info when ending test: ~n~p\", [agent_info(AgentNode)]),\n\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\ndiscovery(suite) -> [];\ndiscovery(Config) when is_list(Config) ->\n ?SKIP(not_yet_implemented).\n\n\n%%======================================================================\n%% \n%% Utility functions for cases trap1 and trap2\n%% \n\ncollect_traps(N) ->\n collect_traps(N, []).\n\ncollect_traps(0, TrapInfo) ->\n TrapInfo;\ncollect_traps(N, Acc) ->\n receive\n\t{async_event, _From, {trap, TrapInfo}} ->\n\t p(\"collect_traps -> received trap: ~n ~p\", [TrapInfo]),\n\t collect_traps(N-1, [TrapInfo|Acc])\n after 10000 ->\n\t p(\"collect_traps -> still awaiting ~w trap(s) - giving up\", [N]),\n\t Acc\n end.\n\nverify_traps([], []) ->\n p(\"verify_traps -> done\"),\n ok;\nverify_traps([], Verifiers) ->\n p(\"verify_traps -> done when ~w verifiers remain\", [length(Verifiers)]),\n {error, {failed_verify, [Id || {Id, _} <- Verifiers]}};\nverify_traps([Trap|Traps], Verifiers0) ->\n p(\"verify_traps -> entry\"),\n case verify_trap(Trap, Verifiers0) of\n\t{ok, Id} ->\n\t p(\"verify_traps -> trap verified: ~p\", [Id]),\n\t Verifiers = lists:keydelete(Id, 1, Verifiers0),\n\t verify_traps(Traps, Verifiers);\n\terror ->\n\t p(\"verify_traps -> failed verifying trap: ~n ~p\", [Trap]),\n\t {error, {failed_verifying_trap, Trap}}\n end.\n\nverify_trap(Trap, []) ->\n p(\"verify_trap -> could not verify trap:\"\n \"~n Trap: ~p\", [Trap]),\n error;\nverify_trap(Trap, [{Id, Verifier}|Verifiers]) ->\n p(\"verify_trap -> entry with\"\n \"~n Id: ~p\"\n \"~n Trap: ~p\", [Id, Trap]),\n case Verifier(Trap) of\n\tok ->\n\t p(\"verify_trap -> verified\"),\n\t {ok, Id};\n\t{error, _} ->\n\t p(\"verify_trap -> not verified\"),\n\t verify_trap(Trap, Verifiers)\n end.\n\n\n%%======================================================================\n\ntrap1(suite) -> [];\ntrap1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,t1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n %% Version 1 trap verification function:\n VerifyTrap_v1 = \n\tfun(Ent, Gen, Spec, ExpVBs, Trap) ->\n\t\tcase Trap of\n\t\t {Ent, Gen, Spec, _Timestamp, VBs} ->\n\t\t\tp(\"trap info as expected\"), \n\t\t\tcase (catch validate_vbs(MgrNode, \n\t\t\t\t\t\t ExpVBs, VBs)) of\n\t\t\t ok ->\n\t\t\t\tp(\"valid trap\"),\n\t\t\t\tok;\n\t\t\t Error ->\n\t\t\t\tp(\"invalid trap: ~n Error: ~p\", [Error]),\n\t\t\t\tError\n\t\t\tend;\n\t\t {Enteprise, Generic, Spec, Timestamp, VBs} ->\n\t\t\tp(\"unepxected v1 trap info:\"\n\t\t\t \"~n Enteprise: ~p\"\n\t\t\t \"~n Generic: ~p\"\n\t\t\t \"~n Spec: ~p\"\n\t\t\t \"~n Timestamp: ~p\"\n\t\t\t \"~n VBs: ~p\", \n\t\t\t [Enteprise, Generic, Spec, Timestamp, VBs]),\n\t\t\tExpTrap = {Ent, Gen, Spec, ignore, ExpVBs}, \n\t\t\tReason = {unexpected_trap, {ExpTrap, Trap}},\n\t\t\t{error, Reason};\n\t\t {Err, Idx, VBs} ->\n\t\t\tp(\"unexpected trap info: \"\n\t\t\t \"~n Err: ~p\"\n\t\t\t \"~n Idx: ~p\"\n\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t{error, Reason}\n\t\tend\n\tend,\n\n %% Version 2 trap verification function:\n VerifyTrap_v2 = \n\tfun(ExpVBs, Trap) ->\n\t\tcase Trap of\n\t\t {noError, 0, VBs0} ->\n\t\t\tp(\"trap info as expected: ~n~p\", [VBs0]), \n\t\t\t%% The first two are a timestamp and oid\n\t\t\t[_,_|VBs] = VBs0,\n\t\t\tcase (catch validate_vbs(MgrNode, \n\t\t\t\t\t\t ExpVBs, VBs)) of\n\t\t\t ok ->\n\t\t\t\tp(\"valid trap\"),\n\t\t\t\tok;\n\t\t\t Error ->\n\t\t\t\tp(\"invalid trap: ~n Error: ~p\", \n\t\t\t\t [Error]),\n\t\t\t\tError\n\t\t\tend;\n\t\t {Err, Idx, VBs} ->\n\t\t\tp(\"unexpected error status: \"\n\t\t\t \"~n Err: ~p\"\n\t\t\t \"~n Idx: ~p\"\n\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t{error, Reason}\n\t\tend\n\tend,\n\n\n %% -- command 1 --\n %% Collect various info about the manager and the agent\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n %% -- command 2 --\n %% Make the agent send trap(s) (both a v1 and a v2 trap)\n Cmd2 = \n\tfun() ->\n\t\tVBs = [{ifIndex, [1], 1},\n\t\t {ifAdminStatus, [1], 1},\n\t\t {ifOperStatus, [1], 2}],\n\t\tagent_send_trap(AgentNode, linkUp, \"standard trap\", VBs),\n\t\tok\n\tend,\n\n %% -- command 3 --\n %% Version 1 trap verify function\n Cmd3_VerifyTrap_v1 = \n\tfun(Trap) ->\n\t\tEnt = [1,2,3], \n\t\tGen = 3, \n\t\tSpec = 0, \n\t\tExpVBs = [{[ifIndex, 1], 1},\n\t\t\t {[ifAdminStatus, 1], 1},\n\t\t\t {[ifOperStatus, 1], 2}],\n\t\tVerifyTrap_v1(Ent, Gen, Spec, ExpVBs, Trap)\n\tend,\n\n %% Version 2 trap verify function\n Cmd3_VerifyTrap_v2 = \n\tfun(Trap) ->\n\t\tExpVBs = [{[ifIndex, 1], 1},\n\t\t\t {[ifAdminStatus, 1], 1},\n\t\t\t {[ifOperStatus, 1], 2}],\n\t\tVerifyTrap_v2(ExpVBs, Trap)\n\tend,\n\n %% Verify the two traps. The order of them is unknown\n Cmd3 = \n\tfun() ->\n\t\tVerifiers = [{\"v1 trap verifier\", Cmd3_VerifyTrap_v1},\n\t\t\t {\"v2 trap verifier\", Cmd3_VerifyTrap_v2}],\n\t\tverify_traps(collect_traps(2), Verifiers)\n\tend,\n\n Cmd4 = fun() -> ?SLEEP(1000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send trap from agent\", Cmd2},\n\t {3, \"Await trap(s) to manager\", Cmd3},\n\t {4, \"Sleep some time (1 sec)\", Cmd4},\n\t {5, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n \n%%======================================================================\n\ntrap2(suite) -> [];\ntrap2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,t2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n %% Version 1 trap verification function:\n VerifyTrap_v1 = \n\tfun(Ent, Gen, Spec, ExpVBs, Trap) ->\n\t\tcase Trap of\n\t\t {Ent, Gen, Spec, _Timestamp, VBs} ->\n\t\t\tp(\"trap info as expected\"), \n\t\t\tcase (catch validate_vbs(MgrNode, \n\t\t\t\t\t\t ExpVBs, VBs)) of\n\t\t\t ok ->\n\t\t\t\tp(\"valid trap\"),\n\t\t\t\tok;\n\t\t\t Error ->\n\t\t\t\tp(\"invalid trap: ~n Error: ~p\", [Error]),\n\t\t\t\tError\n\t\t\tend;\n\t\t {Enteprise, Generic, Spec, Timestamp, VBs} ->\n\t\t\tp(\"unepxected v1 trap info:\"\n\t\t\t \"~n Enteprise: ~p\"\n\t\t\t \"~n Generic: ~p\"\n\t\t\t \"~n Spec: ~p\"\n\t\t\t \"~n Timestamp: ~p\"\n\t\t\t \"~n VBs: ~p\", \n\t\t\t [Enteprise, Generic, Spec, Timestamp, VBs]),\n\t\t\tExpTrap = {Ent, Gen, Spec, ignore, ExpVBs}, \n\t\t\tReason = {unexpected_trap, {ExpTrap, Trap}},\n\t\t\t{error, Reason};\n\t\t {Err, Idx, VBs} ->\n\t\t\tp(\"unexpected trap info: \"\n\t\t\t \"~n Err: ~p\"\n\t\t\t \"~n Idx: ~p\"\n\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t{error, Reason}\n\t\tend\n\tend,\n\n %% Version 2 trap verification function:\n VerifyTrap_v2 = \n\tfun(ExpVBs, Trap) ->\n\t\tcase Trap of\n\t\t {noError, 0, VBs0} ->\n\t\t\tp(\"trap info as expected: ~n~p\", [VBs0]), \n\t\t\t%% The first two are a timestamp and oid\n\t\t\t[_,_|VBs] = VBs0,\n\t\t\tcase (catch validate_vbs(MgrNode, \n\t\t\t\t\t\t ExpVBs, VBs)) of\n\t\t\t ok ->\n\t\t\t\tp(\"valid trap\"),\n\t\t\t\tok;\n\t\t\t Error ->\n\t\t\t\tp(\"invalid trap: ~n Error: ~p\", \n\t\t\t\t [Error]),\n\t\t\t\tError\n\t\t\tend;\n\t\t {Err, Idx, VBs} ->\n\t\t\tp(\"unexpected error status: \"\n\t\t\t \"~n Err: ~p\"\n\t\t\t \"~n Idx: ~p\"\n\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t{error, Reason}\n\t\tend\n\tend,\n\n %% -- command 1 --\n %% Collect various info about the manager and the agent\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n %% -- command 2 --\n %% Make the agent send trap(s) (both a v1 and a v2 trap)\n Cmd2 = \n\tfun() ->\n\t\tVBs = [{sysContact, \"pelle\"}],\n\t\tagent_send_trap(AgentNode, testTrap1, \"standard trap\", VBs),\n\t\tok\n\tend,\n\n %% -- command 3 --\n %% Version 1 trap verify function\n Cmd3_VerifyTrap_v1 = \n\tfun(Trap) ->\n\t\tEnt = [1,2,3], \n\t\tGen = 1, \n\t\tSpec = 0, \n\t\tExpVBs = [{[system, [4,0]], \"pelle\"}],\n\t\tVerifyTrap_v1(Ent, Gen, Spec, ExpVBs, Trap)\n\tend,\n\n %% Version 2 trap verify function\n Cmd3_VerifyTrap_v2 = \n\tfun(Trap) ->\n\t\tExpVBs = [{[system, [4,0]], \"pelle\"},\n\t\t\t {[snmpTrapEnterprise,0], any}],\n\t\tVerifyTrap_v2(ExpVBs, Trap)\n\tend,\n\t\t\n %% Verify the two traps. The order of them is unknown\n Cmd3 = \n\tfun() ->\n\t\tVerifiers = [{\"v1 trap verifier\", Cmd3_VerifyTrap_v1},\n\t\t\t {\"v2 trap verifier\", Cmd3_VerifyTrap_v2}],\n\t\tverify_traps(collect_traps(2), Verifiers)\n\tend,\n\n %% -- command 4 --\n %% Make the agent send another set of trap(s) (both a v1 and a v2 trap)\n Cmd4 = \n\tfun() ->\n\t\tVBs = [{ifIndex, [1], 1},\n\t\t {ifAdminStatus, [1], 1},\n\t\t {ifOperStatus, [1], 2}],\n\t\tagent_send_trap(AgentNode, linkUp, \"standard trap\", VBs),\n\t\tok\n\tend,\n\n \n %% -- command 5 --\n %% Expected varbinds\n ExpVBs5 = [{[ifIndex, 1], 1},\n\t {[ifAdminStatus, 1], 1},\n\t {[ifOperStatus, 1], 2}],\n\n \n %% Version 1 trap verify function\n Cmd5_VerifyTrap_v1 = \n\tfun(Trap) ->\n\t\tEnt = [1,2,3], \n\t\tGen = 3, \n\t\tSpec = 0, \n\t\tVerifyTrap_v1(Ent, Gen, Spec, ExpVBs5, Trap)\n\tend,\n\n %% Version 2 trap verify function\n Cmd5_VerifyTrap_v2 = \n\tfun(Trap) ->\n\t\tVerifyTrap_v2(ExpVBs5, Trap)\n\tend,\n\n %% Verify the two traps. The order of them is unknown\n Cmd5 = \n\tfun() ->\n\t\tVerifiers = [{\"v1 trap verifier\", Cmd5_VerifyTrap_v1},\n\t\t\t {\"v2 trap verifier\", Cmd5_VerifyTrap_v2}],\n\t\tverify_traps(collect_traps(2), Verifiers)\n\tend,\n\n %% -- command 6 --\n %% Some sleep before we are done\n Cmd6 = fun() -> ?SLEEP(1000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send first trap(s) from agent\", Cmd2},\n\t {3, \"Await the trap(s) from agent\", Cmd3},\n\t {4, \"Send second trap(s) from agent\", Cmd4},\n\t {5, \"Await the trap(s) from the agent\", Cmd5},\n\t {6, \"Sleep some time (1 sec)\", Cmd6},\n\t {7, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n \n%%======================================================================\n\ninform1(suite) -> [];\ninform1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,i1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n \n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"manager system info: ~n~p\", [mgr_sys_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n Cmd2 = \n\tfun() ->\n\t\tagent_send_notif(AgentNode, testTrapv22, \"standard inform\"),\n\t\tok\n\tend,\n\n Cmd3 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\tPid ! {handle_inform_no_response, \n\t\t\t\t\t From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 10000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd4 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\tPid ! {handle_inform_response, From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 20000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd5 = fun() -> ?SLEEP(5000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send notifcation [no receiver] from agent\", Cmd2},\n\t {3, \"Await first inform to manager - do not reply\", Cmd3},\n\t {4, \"Await second inform to manager - reply\", Cmd4},\n\t {5, \"Sleep some time (5 sec)\", Cmd5},\n\t {6, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n\n%%======================================================================\n\ninform2(suite) -> [];\ninform2(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, i2),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n %% Addr = ?config(ip, Config),\n %% Port = ?AGENT_PORT,\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n Cmd2 = \n\tfun() ->\n\t\tagent_send_notif(AgentNode, \n\t\t\t\t testTrapv22, \n\t\t\t\t {inform2_tag1, self()}, \n\t\t\t\t \"standard inform\",\n\t\t\t\t[]),\n\t\tok\n\tend,\n\n Cmd3 = \n\tfun() ->\n\t\treceive\n\t\t {snmp_targets, inform2_tag1, Addrs} ->\n\t\t\tp(\"sent inform to ~p\", [Addrs]),\n\t\t\tok\n\t\tafter 10000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd4 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\tPid ! {handle_inform_no_response, \n\t\t\t\t\t From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 10000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd5 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\tPid ! {handle_inform_response, From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 20000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd6 = \n\tfun() ->\n\t\treceive\n\t\t {snmp_notification, inform2_tag1, {got_response, Addr}} ->\n\t\t\tp(\"received expected \\\"got response\\\" notification \"\n\t\t\t \"from: \"\n\t\t\t \"~n ~p\", [Addr]),\n\t\t\tok;\n\t\t {snmp_notification, inform2_tag1, {no_response, Addr}} ->\n\t\t\tp(\" received expected \\\"no response\\\" \"\n\t\t\t \"notification from: \"\n\t\t\t \"~n ~p\", [Addr]),\n\t\t\t{error, no_response}\n\t\tafter 10000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd7 = fun() -> ?SLEEP(5000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send notifcation [no receiver] from agent\", Cmd2},\n\t {3, \"Await inform-sent acknowledge from agent\", Cmd3},\n\t {4, \"Await first inform to manager - do not reply\", Cmd4},\n\t {5, \"Await second inform to manager - reply\", Cmd5},\n\t {6, \"await inform-acknowledge from agent\", Cmd6},\n\t {7, \"Sleep some time (5 sec)\", Cmd7},\n\t {8, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n \n%%======================================================================\n\ninform3(suite) -> [];\ninform3(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,i3),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n Cmd2 = \n\tfun() ->\n\t\tagent_send_notif(AgentNode, \n\t\t\t\t testTrapv22, \n\t\t\t\t {inform3_tag1, self()}, \n\t\t\t\t \"standard inform\",\n\t\t\t\t []),\n\t\tok\n\tend,\n\n Cmd3 = \n\tfun() ->\n\t\treceive\n\t\t {snmp_targets, inform3_tag1, [_Addr]} ->\n\t\t\tp(\"received inform-sent acknowledgement\", []),\n\t\t\tok\n\t\tafter 10000 ->\n\t\t\treceive \n\t\t\t Crap ->\n\t\t\t\t{error, {timeout_crap, Crap}}\n\t\t\tafter 0 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd4 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\tPid ! {handle_inform_no_response, \n\t\t\t\t\t From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 50000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {timeout_crap, Any}}\n\t\t\tafter 0 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd7 = \n\tfun() ->\n\t\treceive\n\t\t {snmp_notification, inform3_tag1, {no_response, Addr}} ->\n\t\t\tp(\"received expected \\\"no response\\\" notification \"\n\t\t\t \"from: \"\n\t\t\t \"~n ~p\", [Addr]),\n\t\t\tok;\n\t\t {snmp_notification, inform3_tag1, {got_response, Addr}} ->\n\t\t\tp(\" received unexpected \\\"got response\\\" \"\n\t\t\t \"notification from: \"\n\t\t\t \"~n ~p\", \n\t\t\t [Addr]),\n\t\t\t{error, {got_response, Addr}}\n\t\tafter 120000 ->\n\t\t\treceive \n\t\t\t Crap ->\n\t\t\t\t{error, {timeout_crap, Crap}}\n\t\t\tafter 0 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n Cmd8 = fun() -> ?SLEEP(1000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send notifcation from agent\", Cmd2},\n\t {3, \"await inform-sent acknowledge from agent\", Cmd3},\n\t {4, \"Await first inform to manager - do not reply\", Cmd4},\n\t {5, \"Await first inform to manager - do not reply\", Cmd4},\n\t {6, \"Await first inform to manager - do not reply\", Cmd4},\n\t {7, \"await inform-acknowledge from agent\", Cmd7},\n\t {8, \"Sleep some time (1 sec)\", Cmd8},\n\t {9, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n \n%%======================================================================\n\ninform4(suite) -> [];\ninform4(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname,i4),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n Cmd2 = \n\tfun() ->\n\t\tagent_send_notif(AgentNode, testTrapv22, \"standard inform\"),\n\t\tok\n\tend,\n\n Cmd3 = \n\tfun() ->\n\t\treceive\n\t\t {async_event, From, {inform, Pid, Inform}} ->\n\t\t\tp(\"received inform\"),\n\t\t\tcase Inform of\n\t\t\t {noError, 0, VBs} when is_list(VBs) ->\n\t\t\t\tcase (catch validate_testTrapv22_vbs(MgrNode, \n\t\t\t\t\t\t\t\t VBs)) of\n\t\t\t\t ok ->\n\t\t\t\t\tp(\"valid inform\"),\n\t\t\t\t\t%% Actually, as we have\n\t\t\t\t\t%% configured the manager in\n\t\t\t\t\t%% this test case (irb = auto)\n\t\t\t\t\t%% it has already responded\n\t\t\t\t\tPid ! {handle_inform_response, From}, \n\t\t\t\t\tok;\n\t\t\t\t Error ->\n\t\t\t\t\tp(\"invalid inform: ~n Error: ~p\", \n\t\t\t\t\t [Error]),\n\t\t\t\t\tError\n\t\t\t\tend;\n\t\t\t {Err, Idx, VBs} ->\n\t\t\t\tp(\"unexpected error status: \"\n\t\t\t\t \"~n Err: ~p\"\n\t\t\t\t \"~n Idx: ~p\"\n\t\t\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t\t\tReason = {unexpected_status, {Err, Idx, VBs}},\n\t\t\t\t{error, Reason}\n\t\t\tend\n\t\tafter 20000 ->\n\t\t\treceive \n\t\t\t Any ->\n\t\t\t\t{error, {crap, Any}}\n\t\t\tafter 1000 ->\n\t\t\t\t{error, timeout}\n\t\t\tend\n\t\tend\n\tend,\n\n %% This is the a result of erroneous configuration.\n%% Cmd4 = \n%% \tfun() ->\n%% \t\treceive \n%% \t\t {async_event, _ReqId, {error, Reason}} ->\n%% \t\t\tp(\"received error\"),\n%% \t\t\tcase Reason of\n%% \t\t\t {failed_processing_message,\n%% \t\t\t {securityError, usmStatsUnknownEngineIDs}} ->\n%% \t\t\t\tp(\"expected error\"), \n%% \t\t\t\tok;\n%% \t\t\t _ ->\n%% \t\t\t\tp(\"unexpected error: \"\n%% \t\t\t\t \"~n Reason: ~p\", [Reason]),\n%% \t\t\t\t{error, {unexpected_error, Reason}}\n%% \t\t\tend\n%% \t\tafter 20000 ->\n%% \t\t\treceive \n%% \t\t\t Any ->\n%% \t\t\t\t{error, {crap, Any}}\n%% \t\t\tafter 1000 ->\n%% \t\t\t\t{error, timeout}\n%% \t\t\tend\n%% \t\tend\n%% \tend,\n\n Cmd5 = fun() -> ?SLEEP(1000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send notifcation [no receiver] from agent\", Cmd2},\n\t {3, \"Await inform to manager\", Cmd3},\n%% \t {4, \"Await error info (because of erroneous config)\", Cmd4},\n\t {5, \"Sleep some time (1 sec)\", Cmd5},\n\t {6, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n\n%%======================================================================\n%% \n%% Test: ts:run(snmp, snmp_manager_test, inform_swarm, [batch]).\n\ninform_swarm(suite) -> [];\ninform_swarm(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, is),\n p(\"starting with Config: ~p~n\", [Config]),\n\n MgrNode = ?config(manager_node, Config),\n AgentNode = ?config(agent_node, Config),\n\n ?line ok = mgr_user_load_mib(MgrNode, snmpv2_mib()),\n Test2Mib = test2_mib(Config), \n TestTrapMib = test_trap_mib(Config), \n TestTrapv2Mib = test_trap_v2_mib(Config), \n ?line ok = mgr_user_load_mib(MgrNode, Test2Mib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapMib),\n ?line ok = mgr_user_load_mib(MgrNode, TestTrapv2Mib),\n ?line ok = agent_load_mib(AgentNode, Test2Mib),\n ?line ok = agent_load_mib(AgentNode, TestTrapMib),\n ?line ok = agent_load_mib(AgentNode, TestTrapv2Mib),\n NumInforms = 100, \n\n Collector = self(),\n\n Generator = \n\terlang:spawn(\n\t fun() ->\n\t\t receive\n\t\t {Collector, start} ->\n\t\t\t ok\n\t\t end,\n\t\t Seqs = lists:seq(1, NumInforms),\n\t\t lists:foreach(\n\t\t fun(N) ->\n\t\t\t p(\"send notification ~w\", [N]),\n\t\t\t agent_send_notif(AgentNode, \n\t\t\t\t\t testTrapv22, \n\t\t\t\t\t {{inform2_tag1, N}, Collector},\n\t\t\t\t\t \"standard inform\",\n\t\t\t\t\t []),\n\t\t\t %% Sleep some [(N div 10)*100 ms] \n\t\t\t %% every tenth notification\n\t\t\t if \n\t\t\t\tN rem 10 == 0 ->\n\t\t\t\t %% Time to sleep some\n\t\t\t\t Sleep = (N div 10) * 50,\n\t\t\t\t p(\"sleep ~w [~w]\", [Sleep, N]),\n\t\t\t\t ?SLEEP(Sleep);\n\t\t\t\ttrue ->\n\t\t\t\t ok\n\t\t\t end\n\t\t end,\n\t\t Seqs),\n\t\t ok\n\t end), \n\n Cmd1 = \n\tfun() ->\n\t\tp(\"manager info: ~n~p\", [mgr_info(MgrNode)]),\n\t\tp(\"agent info: ~n~p\", [agent_info(AgentNode)]),\n\t\tok\n\tend,\n\n Cmd2 = fun() -> Generator ! {Collector, start}, ok end,\n\n Cmd3 = \n\tfun() ->\n\t\tinform_swarm_collector(NumInforms)\n\tend,\n\n\n Cmd4 = fun() -> ?SLEEP(1000), ok end,\n\n Commands = \n\t[\n\t {1, \"Manager and agent info at start of test\", Cmd1},\n\t {2, \"Send notifcation(s) from agent\", Cmd2},\n\t {3, \"Await send-ack(s)\/inform(s)\/response(s)\", Cmd3},\n\t {4, \"Sleep some time (1 sec)\", Cmd4},\n\t {5, \"Manager and agent info after test completion\", Cmd1}\n\t],\n\n command_handler(Commands),\n display_log(Config),\n ok.\n\n\ninform_swarm_collector(N) ->\n inform_swarm_collector(N, 0, 0, 0, 10000).\n\n%% Note that we need to deal with re-transmissions!\n%% That is, the agent did not receive the ack in time,\n%% and therefor did a re-transmit. This means that we \n%% expect to receive more inform's then we actually \n%% sent. So for sucess we assume: \n%% \n%% SentAckCnt = N\n%% RespCnt = N\n%% RecvCnt >= N\n%% \ninform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt, _) \n when ((N == SentAckCnt) and \n\t(N == RespCnt) and\n\t(N =< RecvCnt)) ->\n p(\"inform_swarm_collector -> done when\"\n \"~n N: ~w\"\n \"~n SentAckCnt: ~w\"\n \"~n RecvCnt: ~w\"\n \"~n RespCnt: ~w\", [N, SentAckCnt, RecvCnt, RespCnt]),\n ok;\ninform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt, Timeout) ->\n p(\"inform_swarm_collector -> entry with\"\n \"~n N: ~w\"\n \"~n SentAckCnt: ~w\"\n \"~n RecvCnt: ~w\"\n \"~n RespCnt: ~w\", [N, SentAckCnt, RecvCnt, RespCnt]),\n receive\n\t{snmp_targets, {inform2_tag1, Id}, [_Addr]} ->\n\t p(\"received inform-sent acknowledgement for ~w\", [Id]),\n\t inform_swarm_collector(N, SentAckCnt+1, RecvCnt, RespCnt, \n\t\t\t\t Timeout);\n\n\t%% The manager has received the actual inform\n\t{async_event, From, {inform, Pid, Inform}} ->\n\t p(\"received inform\"),\n\t case Inform of\n\t\t{noError, 0, VBs} when is_list(VBs) ->\n\t\t Pid ! {handle_inform_response, From}, \n\t\t inform_swarm_collector(N, SentAckCnt, RecvCnt+1, RespCnt, \n\t\t\t\t\t Timeout);\n\t\t{Err, Idx, VBs} ->\n\t\t p(\" unexpected error status: \"\n\t\t \"~n Err: ~p\"\n\t\t \"~n Idx: ~p\"\n\t\t \"~n VBs: ~p\", [Err, Idx, VBs]),\n\t\t Reason = {unexpected_status, {Err, Idx, VBs}},\n\t\t {error, Reason}\n\t end;\n\n\t%% The agent has received ack from the manager \n\t{snmp_notification, {inform2_tag1, Id}, {got_response, Addr}} ->\n\t p(\"received expected \\\"got response\\\" for ~w\"\n\t \"notification from: \"\n\t \"~n ~p\", \n\t [Id, Addr]),\n\t inform_swarm_collector(N, SentAckCnt, RecvCnt, RespCnt+1, \n\t\t\t\t Timeout);\n\n\t%% The agent did not received ack from the manager in time \n\t{snmp_notification, inform2_tag1, {no_response, Addr}} ->\n\t p(\" received expected \\\"no response\\\" notification \"\n\t \"from: \"\n\t \"~n ~p\", [Addr]),\n\t Reason = {no_response, Addr, {N, SentAckCnt, RecvCnt, RespCnt}},\n\t {error, Reason}\n\n after Timeout ->\n\t %% Give up when we have been dead in the water for Timeout ms\n\t {error, {timeout, N, SentAckCnt, RecvCnt, RespCnt}}\n end.\n\t\t \n\n%%======================================================================\n\nreport(suite) -> [];\nreport(Config) when is_list(Config) ->\n ?SKIP(not_yet_implemented).\n\n \n\n%%======================================================================\n\notp8015_1(doc) -> [\"OTP-8015:1 - testing the new api-function.\"];\notp8015_1(suite) -> [];\notp8015_1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, otp8015_1),\n p(\"starting with Config: ~p~n\", [Config]),\n\n ConfDir = ?config(manager_conf_dir, Config),\n DbDir = ?config(manager_db_dir, Config),\n\n write_manager_conf(ConfDir),\n\n Opts = [{server, [{verbosity, trace}]},\n\t {net_if, [{verbosity, trace}]},\n\t {note_store, [{verbosity, trace}]},\n\t {config, [{verbosity, trace}, {dir, ConfDir}, {db_dir, DbDir}]}],\n\n p(\"starting manager\"),\n ok = snmpm:start_link(Opts),\n\n ?SLEEP(1000),\n\n snmpm:load_mib(std_mib()), \n snmpm:load_mib(test_trap_mib(Config)),\n\n p(\"manager started, now sleep some\"),\n\n ?SLEEP(1000),\n\n p(\"loaded mibs: ~p\", [snmpm:which_mibs()]),\n\n p(\"get some type(s) from the mibs\"), \n {ok, 'Counter32'} = snmpm:oid_to_type(?snmpOutTraps), \n {ok, [IfIndex]} = snmpm:name_to_oid(ifIndex),\n {ok, 'INTEGER'} = snmpm:oid_to_type(IfIndex),\n \n\n p(\"stop manager\"),\n ok = snmpm:stop(),\n\n ?SLEEP(1000),\n\n p(\"end\"),\n ok.\n\n\n%%======================================================================\n\notp8395_1(doc) -> [\"OTP-8395:1 - simple get with ATL sequence numbering.\"];\notp8395_1(suite) -> [];\notp8395_1(Config) when is_list(Config) ->\n process_flag(trap_exit, true),\n put(tname, otp8395_1),\n do_simple_sync_get2(Config).\n\n\n%%======================================================================\n%% async snmp utility functions\n%%======================================================================\n\nasync_exec([], Acc) ->\n p(\"all async request's sent => now await reponses\"),\n async_verify(async_collector(Acc, []));\nasync_exec([{Id, Data, Exec, Ver}|Reqs], Acc) ->\n p(\"issue async request ~w\", [Id]),\n ?line {ok, ReqId} = Exec(Data),\n async_exec(Reqs, [{ReqId, Id, Ver}|Acc]).\n\nasync_collector([], Acc) ->\n p(\"received replies for all requests - now sort\"),\n lists:keysort(1, Acc);\nasync_collector(Expected, Acc) ->\n receive\n\t{async_event, ReqId, Reply} ->\n\t p(\"received async event with request-id ~w\", [ReqId]),\n\t case lists:keysearch(ReqId, 1, Expected) of\n\t\t{value, {_, Id, Ver}} ->\n\t\t p(\"event was for request ~w\", [Id]),\n\t\t Expected2 = lists:keydelete(ReqId, 1, Expected),\n\t\t async_collector(Expected2, [{Id, Ver, Reply}|Acc]);\n\t\tfalse ->\n\t\t % Duplicate reply?\n\t\t ?FAIL({unexpected_async_event, ReqId, Reply})\n\t end\n after 10000 ->\n\t ?FAIL({timeout, {Expected, Acc}})\n end.\n\nasync_verify([]) ->\n ok;\nasync_verify([{Id, Verify, Reply}|Replies]) ->\n p(\"verify reply ~w\", [Id]),\n Verify(Reply),\n async_verify(Replies).\n\n\n\n%%======================================================================\n%% Internal functions\n%%======================================================================\n\n\n%% -- Verify varbinds --\n\nvalidate_vbs(Node, ExpVBs, VBs) ->\n validate_vbs(purify_oids(Node, ExpVBs), VBs).\n\nvalidate_testTrapv22_vbs(Node, VBs) ->\n ExpVBs = [{[sysUpTime, 0], any},\n\t {[snmpTrapOID, 0], ?system ++ [0,1]}],\n validate_vbs(purify_oids(Node, ExpVBs), VBs).\n\nvalidate_vbs([], []) ->\n ok;\nvalidate_vbs(Exp, []) ->\n {error, {expected_vbs, Exp}};\nvalidate_vbs([], VBs) ->\n {error, {unexpected_vbs, VBs}};\nvalidate_vbs([any|Exp], [_|VBs]) ->\n validate_vbs(Exp, VBs);\nvalidate_vbs([{_, any}|Exp], [#varbind{}|VBs]) ->\n validate_vbs(Exp, VBs);\nvalidate_vbs([{Oid, Val}|Exp], [#varbind{oid = Oid, value = Val}|VBs]) ->\n validate_vbs(Exp, VBs);\nvalidate_vbs([{Oid, Val1}|_], [#varbind{oid = Oid, value = Val2}|_]) ->\n {error, {unexpected_vb_value, Oid, Val1, Val2}};\nvalidate_vbs([{Oid1, _}|_], [#varbind{oid = Oid2}|_]) ->\n {error, {unexpected_vb_oid, Oid1, Oid2}}.\n\npurify_oids(_, []) ->\n [];\npurify_oids(Node, [{Oid, Val}|Oids]) ->\n [{purify_oid(Node, Oid), Val}| purify_oids(Node, Oids)].\n\npurify_oid(Node, Oid) ->\n case mgr_user_purify_oid(Node, Oid) of\n\tOid2 when is_list(Oid2) ->\n\t Oid2;\n\t{error, _} = Error ->\n\t throw(Error)\n end.\n\n\n%% -- Test case command handler (executor) ---\n\ncommand_handler([]) ->\n ok;\ncommand_handler([{No, Desc, Cmd}|Cmds]) ->\n p(\"command_handler -> command ~w: \"\n \"~n ~s\", [No, Desc]),\n case (catch Cmd()) of\n\tok ->\n p(\"command_handler -> ~w: ok\",[No]),\n command_handler(Cmds);\n {error, Reason} ->\n p(\" command_handler -> ~w error: ~n~p\",[No, Reason]),\n ?line ?FAIL({command_failed, No, Reason});\n Error ->\n p(\" command_handler -> ~w unexpected: ~n~p\",[No, Error]),\n ?line ?FAIL({unexpected_command_result, No, Error})\n end.\n\n\n%% -- Misc manager functions --\n\ninit_manager(AutoInform, Config) ->\n ?LOG(\"init_manager -> entry with\"\n\t \"~n AutoInform: ~p\"\n\t \"~n Config: ~p\", [AutoInform, Config]),\n\n\n %% -- \n %% Start node\n %% \n\n ?line Node = start_manager_node(),\n\n %% The point with this (try catch block) is to be \n %% able to do some cleanup in case we fail to \n %% start some of the apps. That is, if we fail to \n %% start the apps (mnesia, crypto and snmp agent) \n %% we stop the (agent) node!\n\n try\n\tbegin\n\n\t %% -- \n\t %% Start and initiate crypto on manager node\n\t %% \n\t \n\t ?line ok = init_crypto(Node),\n\t \n\t %% \n\t %% Write manager config\n\t %% \n\t \n\t ?line ok = write_manager_config(Config),\n\t \n\t IRB = case AutoInform of\n\t\t true ->\n\t\t\t auto;\n\t\t _ ->\n\t\t\t user\n\t\t end,\n\t Conf = [{manager_node, Node}, {irb, IRB} | Config],\n\t Vsns = [v1,v2,v3], \n\t start_manager(Node, Vsns, Conf)\n\tend\n catch\n\tT:E ->\n\t StackTrace = ?STACK(), \n\t p(\"Failure during manager start: \"\n\t \"~n Error Type: ~p\"\n\t \"~n Error: ~p\"\n\t \"~n StackTrace: ~p\", [T, E, StackTrace]), \n\t %% And now, *try* to cleanup\n\t (catch stop_node(Node)), \n\t ?FAIL({failed_starting_manager, T, E, StackTrace})\n end.\n\nfin_manager(Config) ->\n Node = ?config(manager_node, Config),\n StopMgrRes = stop_manager(Node),\n StopCryptoRes = fin_crypto(Node),\n StopNode = stop_node(Node),\n p(\"fin_agent -> stop apps and (mgr node ~p) node results: \"\n \"~n SNMP Mgr: ~p\"\n \"~n Crypto: ~p\"\n \"~n Node: ~p\", \n [Node, StopMgrRes, StopCryptoRes, StopNode]),\n Config.\n \n\n%% -- Misc agent functions --\n\ninit_agent(Config) ->\n ?LOG(\"init_agent -> entry with\"\n\t \"~n Config: ~p\", [Config]),\n\n %% -- \n %% Retrieve some dir's\n %% \n Dir = ?config(agent_dir, Config),\n MibDir = ?config(mib_dir, Config),\n\n %% -- \n %% Start node\n %% \n\n ?line Node = start_agent_node(),\n\n %% The point with this (try catch block) is to be \n %% able to do some cleanup in case we fail to \n %% start some of the apps. That is, if we fail to \n %% start the apps (mnesia, crypto and snmp agent) \n %% we stop the (agent) node!\n\n try\n\tbegin\n\t \n\t %% -- \n\t %% Start and initiate mnesia on agent node\n\t %% \n\t \n\t ?line ok = init_mnesia(Node, Dir, ?config(mnesia_debug, Config)),\n\t \n\t \n\t %% -- \n\t %% Start and initiate crypto on agent node\n\t %% \n\t \n\t ?line ok = init_crypto(Node),\n\t \n\t \n\t %% \n\t %% Write agent config\n\t %% \n\t \n\t Vsns = [v1,v2], \n\t ?line ok = write_agent_config(Vsns, Config),\n\t \n\t Conf = [{agent_node, Node},\n\t\t {mib_dir, MibDir} | Config],\n \n\t %% \n\t %% Start the agent \n\t %% \n\t \n\t start_agent(Node, Vsns, Conf)\n\tend\n catch\n\tT:E ->\n\t StackTrace = ?STACK(), \n\t p(\"Failure during agent start: \"\n\t \"~n Error Type: ~p\"\n\t \"~n Error: ~p\"\n\t \"~n StackTrace: ~p\", [T, E, StackTrace]), \n\t %% And now, *try* to cleanup\n\t (catch stop_node(Node)), \n\t ?FAIL({failed_starting_agent, T, E, StackTrace})\n end.\n\t \n\nfin_agent(Config) ->\n Node = ?config(agent_node, Config),\n StopAgentRes = stop_agent(Node),\n StopCryptoRes = fin_crypto(Node),\n StopMnesiaRes = fin_mnesia(Node),\n StopNode = stop_node(Node),\n p(\"fin_agent -> stop apps and (agent node ~p) node results: \"\n \"~n SNMP Agent: ~p\"\n \"~n Crypto: ~p\"\n \"~n Mnesia: ~p\"\n \"~n Node: ~p\", \n [Node, StopAgentRes, StopCryptoRes, StopMnesiaRes, StopNode]),\n Config.\n\ninit_mnesia(Node, Dir, MnesiaDebug) \n when ((MnesiaDebug =\/= none) andalso \n\t(MnesiaDebug =\/= debug) andalso (MnesiaDebug =\/= trace)) ->\n init_mnesia(Node, Dir, ?DEFAULT_MNESIA_DEBUG);\ninit_mnesia(Node, Dir, MnesiaDebug) ->\n ?DBG(\"init_mnesia -> load application mnesia\", []),\n ?line ok = load_mnesia(Node),\n\n ?DBG(\"init_mnesia -> application mnesia: set_env dir: ~n~p\",[Dir]),\n ?line ok = set_mnesia_env(Node, dir, filename:join(Dir, \"mnesia\")),\n\n %% Just in case, only set (known to be) valid values for debug\n if\n\t((MnesiaDebug =:= debug) orelse (MnesiaDebug =:= trace)) ->\n\t ?DBG(\"init_mnesia -> application mnesia: set_env debug: ~w\", \n\t\t [MnesiaDebug]),\n\t ?line ok = set_mnesia_env(Node, debug, MnesiaDebug);\n\ttrue ->\n\t ok\n end,\n\n ?DBG(\"init_mnesia -> create mnesia schema\",[]),\n ?line case create_schema(Node) of\n\t ok ->\n\t\t ok;\n\t {error, {Node, {already_exists, Node}}} ->\n\t\t ?line ok = delete_schema(Node),\n\t\t ?line ok = create_schema(Node);\n\t Error ->\n\t\t ?FAIL({failed_creating_mnesia_schema, Error})\n\t end,\n \n ?DBG(\"init_mnesia -> start application mnesia\",[]),\n ?line ok = start_mnesia(Node),\n\n ?DBG(\"init_mnesia -> create tables\",[]),\n ?line ok = create_tables(Node),\n ok.\n\nfin_mnesia(Node) ->\n ?line ok = delete_tables(Node),\n ?line ok = stop_mnesia(Node),\n ok.\n\n\ninit_crypto(Node) ->\n ?line ok = load_crypto(Node),\n ?line ok = start_crypto(Node),\n ok.\n\nfin_crypto(Node) ->\n ?line ok = stop_crypto(Node),\n ok.\n\n\n%% -- Misc application wrapper functions --\n\nload_app(Node, App) ->\n VerifySuccess = fun(ok) ->\n\t\t\t ok;\n\t\t ({error, {already_loaded, LoadedApp}}) when (LoadedApp =:= App) ->\n\t\t\t ok;\n\t\t ({error, Reason}) ->\n\t\t\t p(\"failed loading app ~w on ~p: \"\n\t\t\t \"~n ~p\", [App, Node, Reason]),\n\t\t\t ?FAIL({failed_load, Node, App, Reason})\n\t\t end,\n do_load_app(Node, App, VerifySuccess).\n\ndo_load_app(Node, App, VerifySuccess) \n when (Node =:= node()) andalso is_atom(App) ->\n %% Local app\n exec(fun() -> application:load(App) end, VerifySuccess);\ndo_load_app(Node, App, VerifySuccess) ->\n %% Remote app\n exec(fun() -> rcall(Node, application, load, [App]) end, VerifySuccess).\n\n\nstart_app(Node, App) ->\n VerifySuccess = fun(ok) ->\n\t\t\t ok;\n\t\t ({error, {already_started, LoadedApp}}) when (LoadedApp =:= App) ->\n\t\t\t ok;\n\t\t ({error, Reason}) ->\n\t\t\t p(\"failed starting app ~w on ~p: \"\n\t\t\t \"~n ~p\", [App, Node, Reason]),\n\t\t\t ?FAIL({failed_start, Node, App, Reason})\n\t\t end,\n start_app(Node, App, VerifySuccess).\n\nstart_app(Node, App, VerifySuccess) \n when (Node =:= node()) andalso is_atom(App) ->\n exec(fun() -> application:start(App) end, VerifySuccess);\nstart_app(Node, App, VerifySuccess) ->\n exec(fun() -> rcall(Node, application, start, [App]) end, VerifySuccess).\n\n\nstop_app(Node, App) ->\n VerifySuccess = fun(ok) ->\n\t\t\t ok;\n\t\t ({error, {not_started, LoadedApp}}) when (LoadedApp =:= App) ->\n\t\t\t ok;\n\t\t ({error, Reason}) ->\n\t\t\t p(\"failed stopping app ~w on ~p: \"\n\t\t\t \"~n ~p\", [App, Node, Reason]),\n\t\t\t ?FAIL({failed_stop, Node, App, Reason})\n\t\t end,\n stop_app(Node, App, VerifySuccess).\n \nstop_app(Node, App, VerifySuccess) \n when (Node =:= node()) andalso is_atom(App) ->\n exec(fun() -> application:stop(App) end, VerifySuccess);\nstop_app(Node, App, VerifySuccess) when is_atom(App) ->\n exec(fun() -> rcall(Node, application, stop, [App]) end, VerifySuccess).\n\n\nset_app_env(Node, App, Key, Val) ->\n VerifySuccess = fun(ok) ->\n\t\t\t ok;\n\t\t ({error, Reason}) ->\n\t\t\t p(\"failed setting app ~w env on ~p\"\n\t\t\t \"~n Key: ~p\"\n\t\t\t \"~n Val: ~p\"\n\t\t\t \"~n Reason: ~p\"\n\t\t\t \"~n ~p\", [App, Node, Key, Val, Reason]),\n\t\t\t ?FAIL({failed_set_app_env, \n\t\t\t\t Node, App, Key, Val, Reason})\n\t\t end,\n set_app_env(Node, App, Key, Val, VerifySuccess).\n\nset_app_env(Node, App, Key, Val, VerifySuccess) \n when (Node =:= node()) andalso is_atom(App) ->\n exec(fun() -> application:set_env(App, Key, Val) end, VerifySuccess);\nset_app_env(Node, App, Key, Val, VerifySuccess) when is_atom(App) ->\n exec(fun() -> rcall(Node, application, set_env, [App, Key, Val]) end, \n\t VerifySuccess).\n\n\nexec(Cmd, VerifySuccess) ->\n VerifySuccess(Cmd()).\n\n\n%% -- Misc snmp wrapper functions --\n\nload_snmp(Node) -> load_app(Node, snmp).\nstart_snmp(Node) -> start_app(Node, snmp).\nstop_snmp(Node) -> stop_app(Node, snmp).\nset_agent_env(Node, Env) -> set_snmp_env(Node, agent, Env).\nset_mgr_env(Node, Env) -> set_snmp_env(Node, manager, Env).\nset_snmp_env(Node, Entity, Env) -> set_app_env(Node, snmp, Entity, Env).\n\nmgr_info(Node) ->\n rcall(Node, snmpm, info, []).\n\nmgr_sys_info(Node) ->\n rcall(Node, snmpm_config, system_info, []).\n\n%% mgr_register_user(Node, Id, Data) ->\n%% mgr_register_user(Node, Id, ?MODULE, Data).\n\nmgr_register_user(Node, Id, Mod, Data) when is_atom(Mod) ->\n rcall(Node, snmpm, register_user, [Id, Mod, Data]).\n\nmgr_unregister_user(Node, Id) ->\n rcall(Node, snmpm, unregister_user, [Id]).\n\nmgr_which_users(Node) ->\n rcall(Node, snmpm, which_users, []).\n\n%% mgr_register_agent(Node, Id) ->\n%% mgr_register_agent(Node, Id, []).\n\n%% mgr_register_agent(Node, Id, Conf) when is_list(Conf) ->\n%% mgr_register_agent(Node, Id, 5000, Conf).\n\nmgr_register_agent(Node, Id, Port, Conf) \n when is_integer(Port) andalso is_list(Conf) ->\n Localhost = snmp_test_lib:localhost(),\n mgr_register_agent(Node, Id, Localhost, Port, Conf);\nmgr_register_agent(Node, Id, TargetName, Config) \n when is_list(TargetName) andalso is_list(Config) ->\n rcall(Node, snmpm, register_agent, [Id, TargetName, Config]).\n\nmgr_register_agent(Node, Id, Addr, Port, Conf) \n when is_integer(Port) andalso is_list(Conf) ->\n rcall(Node, snmpm, register_agent, [Id, Addr, Port, Conf]).\n\n%% mgr_unregister_agent(Node, Id) ->\n%% mgr_unregister_agent(Node, Id, 4000).\n\nmgr_unregister_agent(Node, Id, Port) when is_integer(Port) ->\n Localhost = snmp_test_lib:localhost(),\n rcall(Node, snmpm, unregister_agent, [Id, Localhost, Port]);\nmgr_unregister_agent(Node, Id, TargetName) when is_list(TargetName) ->\n rcall(Node, snmpm, unregister_agent, [Id, TargetName]).\n\nmgr_which_agents(Node) ->\n rcall(Node, snmpm, which_agents, []).\n\nmgr_which_agents(Node, Id) ->\n rcall(Node, snmpm, which_agents, [Id]).\n\n\n%% -- Misc crypto wrapper functions --\n\nload_crypto(Node) -> load_app(Node, crypto).\nstart_crypto(Node) -> start_app(Node, crypto).\nstop_crypto(Node) -> stop_app(Node, crypto).\n\n\n%% -- Misc mnesia wrapper functions --\n\nload_mnesia(Node) -> load_app(Node, mnesia).\nstart_mnesia(Node) -> start_app(Node, mnesia).\nstop_mnesia(Node) -> stop_app(Node, mnesia).\nset_mnesia_env(Node, Key, Val) -> set_app_env(Node, mnesia, Key, Val).\n\ncreate_schema(Node) ->\n rcall(Node, mnesia, create_schema, [[Node]]).\n\ndelete_schema(Node) ->\n rcall(Node, mnesia, delete_schema, [[Node]]).\n\ncreate_table(Node, Table) ->\n rcall(Node, mnesia, create_table, [Table]).\n\ndelete_table(Node, Table) ->\n rcall(Node, mnesia, delete_table, [Table]).\n\ncreate_tables(Node) ->\n Tab1 = [{name, friendsTable2},\n\t {ram_copies, [Node]},\n\t {snmp, [{key, integer}]},\n\t {attributes, [a1,a2,a3]}],\n Tab2 = [{name, kompissTable2},\n\t {ram_copies, [Node]},\n\t {snmp, [{key, integer}]},\n\t {attributes, [a1,a2,a3]}],\n Tab3 = [{name, snmp_variables},\n\t {attributes, [a1,a2]}],\n Tabs = [Tab1, Tab2, Tab3],\n create_tables(Node, Tabs).\n\ncreate_tables(_Node, []) ->\n ok;\ncreate_tables(Node, [Tab|Tabs]) ->\n case create_table(Node, Tab) of\n\t{atomic, ok} ->\n\t create_tables(Node, Tabs);\n\tError ->\n\t ?FAIL({failed_creating_table, Node, Tab, Error})\n end.\n\ndelete_tables(Node) ->\n Tabs = [friendsTable2, kompissTable2, snmp_variables],\n delete_tables(Node, Tabs).\n\n%% delete_mib_storage_tables(Node) ->\n%% Tabs = [snmpa_mib_data, snmpa_mib_tree, snmpa_symbolic_store],\n%% delete_tables(Node, Tabs).\n\ndelete_tables(Node, Tabs) ->\n lists:foreach(fun(Tab) -> delete_table(Node, Tab) end, Tabs).\n\n\n%% -- Misc manager user wrapper functions --\n\ninit_mgr_user(Conf) ->\n ?DBG(\"init_mgr_user -> entry with\"\n\t \"~n Conf: ~p\", [Conf]),\n\n Node = ?config(manager_node, Conf),\n %% UserId = ?config(user_id, Conf),\n\n ?line {ok, User} = mgr_user_start(Node),\n ?DBG(\"start_mgr_user -> User: ~p\", [User]),\n link(User),\n \n [{user_pid, User} | Conf].\n\nfin_mgr_user(Conf) ->\n User = ?config(user_pid, Conf),\n unlink(User),\n Node = ?config(manager_node, Conf),\n ?line ok = mgr_user_stop(Node),\n Conf.\n\ninit_mgr_user_data1(Conf) ->\n Node = ?config(manager_node, Conf),\n TargetName = ?config(manager_agent_target_name, Conf),\n IpFamily = ?config(ipfamily, Conf),\n Ip = ?config(ip, Conf),\n Port = ?AGENT_PORT,\n ?line ok =\n\tcase IpFamily of\n\t inet ->\n\t\tmgr_user_register_agent(\n\t\t Node, TargetName,\n\t\t [{address, Ip},\n\t\t {port, Port},\n\t\t {engine_id, \"agentEngine\"}]);\n\t inet6 ->\n\t\tmgr_user_register_agent(\n\t\t Node, TargetName,\n\t\t [{tdomain, transportDomainUdpIpv6},\n\t\t {taddress, {Ip, Port}},\n\t\t {engine_id, \"agentEngine\"}])\n\tend,\n _Agents = mgr_user_which_own_agents(Node),\n ?DBG(\"Own agents: ~p\", [_Agents]),\n\n ?line {ok, _DefAgentConf} = mgr_user_agent_info(Node, TargetName, all),\n ?DBG(\"Default agent config: ~n~p\", [_DefAgentConf]),\n\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t community, \"all-rights\"),\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t sec_name, \"all-rights\"),\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t engine_id, \"agentEngine\"),\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t max_message_size, 1024),\n\n ?line {ok, _AgentConf} = mgr_user_agent_info(Node, TargetName, all),\n ?DBG(\"Updated agent config: ~n~p\", [_AgentConf]),\n Conf.\n\ninit_mgr_user_data2(Conf) ->\n ?DBG(\"init_mgr_user_data2 -> entry with\"\n\t \"~n Conf: ~p\", [Conf]),\n Node = ?config(manager_node, Conf),\n TargetName = ?config(manager_agent_target_name, Conf),\n IpFamily = ?config(ipfamily, Conf),\n Ip = ?config(ip, Conf),\n Port = ?AGENT_PORT,\n ?line ok =\n\tcase IpFamily of\n\t inet ->\n\t\tmgr_user_register_agent(\n\t\t Node, TargetName,\n\t\t [{address, Ip},\n\t\t {port, Port},\n\t\t {engine_id, \"agentEngine\"}]);\n\t inet6 ->\n\t\tmgr_user_register_agent(\n\t\t Node, TargetName,\n\t\t [{tdomain, transportDomainUdpIpv6},\n\t\t {taddress, {Ip, Port}},\n\t\t {engine_id, \"agentEngine\"}])\n\tend,\n _Agents = mgr_user_which_own_agents(Node),\n ?DBG(\"Own agents: ~p\", [_Agents]),\n\n ?line {ok, _DefAgentConf} = mgr_user_agent_info(Node, TargetName, all),\n ?DBG(\"Default agent config: ~n~p\", [_DefAgentConf]),\n\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t community, \"all-rights\"),\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t sec_name, \"all-rights\"),\n ?line ok = mgr_user_update_agent_info(Node, TargetName, \n\t\t\t\t\t max_message_size, 1024),\n\n ?line {ok, _AgentConf} = mgr_user_agent_info(Node, TargetName, all),\n ?DBG(\"Updated agent config: ~n~p\", [_AgentConf]),\n Conf.\n\nfin_mgr_user_data1(Conf) ->\n Node = ?config(manager_node, Conf),\n TargetName = ?config(manager_agent_target_name, Conf),\n mgr_user_unregister_agent(Node, TargetName),\n mgr_user_which_own_agents(Node),\n Conf.\n\nfin_mgr_user_data2(Conf) ->\n Node = ?config(manager_node, Conf),\n TargetName = ?config(manager_agent_target_name, Conf),\n mgr_user_unregister_agent(Node, TargetName),\n mgr_user_which_own_agents(Node),\n Conf.\n\nmgr_user_start(Node) ->\n mgr_user_start(Node, snmp_manager_test_user).\nmgr_user_start(Node, Id) ->\n rcall(Node, snmp_manager_user, start, [self(), Id]).\n\nmgr_user_stop(Node) ->\n rcall(Node, snmp_manager_user, stop, []).\n\n%% mgr_user_register_agent(Node) ->\n%% mgr_user_register_agent(Node, ?LOCALHOST(), ?AGENT_PORT, []).\n%% mgr_user_register_agent(Node, TargetName) when is_list(TargetName) ->\n%% mgr_user_register_agent(Node, TargetName, []);\n%% mgr_user_register_agent(Node, Addr) ->\n%% mgr_user_register_agent(Node, Addr, ?AGENT_PORT, []).\nmgr_user_register_agent(Node, TargetName, Conf) \n when is_list(TargetName) andalso is_list(Conf) ->\n rcall(Node, snmp_manager_user, register_agent, [TargetName, Conf]).\n%% \n%% mgr_user_register_agent(Node, Addr, Port) ->\n%% mgr_user_register_agent(Node, Addr, Port, []).\n%% mgr_user_register_agent(Node, Addr, Port, Conf) ->\n%% rcall(Node, snmp_manager_user, register_agent, [Addr, Port, Conf]).\n%% <\/REMOVED-IN-R16B>\n\n%% mgr_user_unregister_agent(Node) ->\n%% mgr_user_unregister_agent(Node, ?LOCALHOST(), ?AGENT_PORT).\nmgr_user_unregister_agent(Node, TargetName) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, unregister_agent, [TargetName]).\n%% \n%% mgr_user_unregister_agent(Node, Addr, Port) ->\n%% rcall(Node, snmp_manager_user, unregister_agent, [Addr, Port]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_agent_info(Node, TargetName, Item) \n when is_list(TargetName) andalso is_atom(Item) ->\n rcall(Node, snmp_manager_user, agent_info, [TargetName, Item]).\n%% \n%% mgr_user_agent_info(Node, Addr, Port, Item) when is_atom(Item) ->\n%% rcall(Node, snmp_manager_user, agent_info, [Addr, Port, Item]).\n%% <\/REMOVED-IN-R16B>\n\n%% mgr_user_update_agent_info(Node, Item, Val) when atom(Item) ->\n%% mgr_user_update_agent_info(Node, ?LOCALHOST(), ?AGENT_PORT, Item, Val).\nmgr_user_update_agent_info(Node, TargetName, Item, Val) \n when is_list(TargetName) andalso is_atom(Item) ->\n rcall(Node, snmp_manager_user, update_agent_info, [TargetName, Item, Val]).\n%% \n%% mgr_user_update_agent_info(Node, Addr, Port, Item, Val) when is_atom(Item) ->\n%% rcall(Node, snmp_manager_user, update_agent_info, \n%% \t [Addr, Port, Item, Val]).\n%% <\/REMOVED-IN-R16B>\n\n%% mgr_user_which_all_agents(Node) ->\n%% rcall(Node, snmp_manager_user, which_all_agents, []).\n\nmgr_user_which_own_agents(Node) ->\n rcall(Node, snmp_manager_user, which_own_agents, []).\n\nmgr_user_load_mib(Node, Mib) ->\n rcall(Node, snmp_manager_user, load_mib, [Mib]).\n\n%% mgr_user_sync_get(Node, Oids) ->\n%% mgr_user_sync_get(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).\nmgr_user_sync_get(Node, TargetName, Oids) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get, [TargetName, Oids]).\n%% \nmgr_user_sync_get(Node, Addr, Port, Oids) ->\n rcall(Node, snmp_manager_user, sync_get, [Addr, Port, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_sync_get2(Node, TargetName, Oids, SendOpts) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get2, [TargetName, Oids, SendOpts]).\n\n%% mgr_user_async_get(Node, Oids) ->\n%% mgr_user_async_get(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).\nmgr_user_async_get(Node, TargetName, Oids) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get, [TargetName, Oids]).\n%% \nmgr_user_async_get(Node, Addr, Port, Oids) ->\n rcall(Node, snmp_manager_user, async_get, [Addr, Port, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_async_get2(Node, TargetName, Oids, SendOpts) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get2, [TargetName, Oids, SendOpts]).\n\n%% mgr_user_sync_get_next(Node, Oids) ->\n%% mgr_user_sync_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).\nmgr_user_sync_get_next(Node, TargetName, Oids) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get_next, [TargetName, Oids]).\n%% \nmgr_user_sync_get_next(Node, Addr, Port, Oids) ->\n rcall(Node, snmp_manager_user, sync_get_next, [Addr, Port, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_sync_get_next2(Node, TargetName, Oids, SendOpts) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get_next2, [TargetName, Oids, SendOpts]).\n\n%% mgr_user_async_get_next(Node, Oids) ->\n%% mgr_user_async_get_next(Node, ?LOCALHOST(), ?AGENT_PORT, Oids).\nmgr_user_async_get_next(Node, TargetName, Oids) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get_next, [TargetName, Oids]).\n%% \nmgr_user_async_get_next(Node, Addr, Port, Oids) ->\n rcall(Node, snmp_manager_user, async_get_next, [Addr, Port, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_async_get_next2(Node, TargetName, Oids, SendOpts) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get_next2, [TargetName, Oids, SendOpts]).\n\n%% mgr_user_sync_set(Node, VAV) ->\n%% mgr_user_sync_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).\nmgr_user_sync_set(Node, TargetName, VAV) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_set, [TargetName, VAV]).\n%% \nmgr_user_sync_set(Node, Addr, Port, VAV) ->\n rcall(Node, snmp_manager_user, sync_set, [Addr, Port, VAV]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_sync_set2(Node, TargetName, VAV, SendOpts) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_set2, [TargetName, VAV, SendOpts]).\n\n%% mgr_user_async_set(Node, VAV) ->\n%% mgr_user_async_set(Node, ?LOCALHOST(), ?AGENT_PORT, VAV).\nmgr_user_async_set(Node, TargetName, VAV) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_set, [TargetName, VAV]).\n%% \nmgr_user_async_set(Node, Addr, Port, VAV) ->\n rcall(Node, snmp_manager_user, async_set, [Addr, Port, VAV]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_async_set2(Node, TargetName, VAV, SendOpts) when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_set2, [TargetName, VAV, SendOpts]).\n\n%% mgr_user_sync_get_bulk(Node, NonRep, MaxRep, Oids) ->\n%% mgr_user_sync_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT, \n%% \t\t\t NonRep, MaxRep, Oids).\nmgr_user_sync_get_bulk(Node, TargetName, NonRep, MaxRep, Oids) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get_bulk, \n\t [TargetName, NonRep, MaxRep, Oids]).\n%% \nmgr_user_sync_get_bulk(Node, Addr, Port, NonRep, MaxRep, Oids) ->\n rcall(Node, snmp_manager_user, sync_get_bulk, \n\t [Addr, Port, NonRep, MaxRep, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_sync_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, sync_get_bulk2, \n\t [TargetName, NonRep, MaxRep, Oids, SendOpts]).\n\n%% mgr_user_async_get_bulk(Node, NonRep, MaxRep, Oids) ->\n%% mgr_user_async_get_bulk(Node, ?LOCALHOST(), ?AGENT_PORT, \n%% \t\t\t NonRep, MaxRep, Oids).\nmgr_user_async_get_bulk(Node, TargetName, NonRep, MaxRep, Oids) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get_bulk, \n\t [TargetName, NonRep, MaxRep, Oids]).\n%% \nmgr_user_async_get_bulk(Node, Addr, Port, NonRep, MaxRep, Oids) ->\n rcall(Node, snmp_manager_user, async_get_bulk, \n\t [Addr, Port, NonRep, MaxRep, Oids]).\n%% <\/REMOVED-IN-R16B>\n\nmgr_user_async_get_bulk2(Node, TargetName, NonRep, MaxRep, Oids, SendOpts) \n when is_list(TargetName) ->\n rcall(Node, snmp_manager_user, async_get_bulk2, \n\t [TargetName, NonRep, MaxRep, Oids, SendOpts]).\n\nmgr_user_purify_oid(Node, Oid) ->\n rcall(Node, snmp_manager_user, purify_oid, [Oid]).\n\nmgr_user_name_to_oid(Node, Name) ->\n rcall(Node, snmp_manager_user, name_to_oid, [Name]).\n\n \n%% -- Misc manager wrapper functions --\n\nstart_manager(Node, Vsns, Config) ->\n start_manager(Node, Vsns, Config, []).\nstart_manager(Node, Vsns, Conf0, _Opts) ->\n ?DBG(\"start_manager -> entry with\"\n\t \"~n Node: ~p\"\n\t \"~n Vsns: ~p\"\n\t \"~n Conf0: ~p\"\n\t \"~n Opts: ~p\", [Node, Vsns, Conf0, _Opts]),\n \n AtlDir = ?config(manager_log_dir, Conf0),\n ConfDir = ?config(manager_conf_dir, Conf0),\n DbDir = ?config(manager_db_dir, Conf0),\n IRB = ?config(irb, Conf0),\n\n ConfigVerbosity = get_opt(manager_config_verbosity, Conf0, trace),\n NoteStoreVerbosity = get_opt(manager_note_store_verbosity, Conf0, log),\n ServerVerbosity = get_opt(manager_server_verbosity, Conf0, trace),\n NetIfVerbosity = get_opt(manager_net_if_verbosity, Conf0, trace),\n\n AtlSeqNo = get_opt(manager_atl_seqno, Conf0, false),\n\n NetIfConf = \n\tcase get_opt(manager_net_if_module, Conf0, no_module) of\n\t no_module ->\n\t\t[{verbosity, NetIfVerbosity}];\n\t NetIfModule ->\n\t\t[{module, NetIfModule}, \n\t\t {verbosity, NetIfVerbosity}]\n\tend,\n\n Env = [{versions, Vsns},\n\t {inform_request_behaviour, IRB},\n\t {audit_trail_log, [{type, read_write},\n\t\t\t {dir, AtlDir},\n\t\t\t {size, {10240, 10}},\n\t\t\t {repair, true},\n\t\t\t {seqno, AtlSeqNo}]},\n\t {config, [{dir, ConfDir}, \n\t\t\t {db_dir, DbDir}, \n\t\t\t {verbosity, ConfigVerbosity}]},\n\t {note_store, [{verbosity, NoteStoreVerbosity}]},\n\t {server, [{verbosity, ServerVerbosity}]},\n\t {net_if, NetIfConf}],\n ?line ok = set_mgr_env(Node, Env),\n\n ?line ok = start_snmp(Node),\n \n Conf0.\n\nstop_manager(Node) ->\n stop_snmp(Node).\n\n\n%% -- Misc agent wrapper functions --\n\nstart_agent(Node, Vsns, Config) ->\n start_agent(Node, Vsns, Config, []).\nstart_agent(Node, Vsns, Conf0, _Opts) ->\n ?DBG(\"start_agent -> entry with\"\n\t \"~n Node: ~p\"\n\t \"~n Vsns: ~p\"\n\t \"~n Conf0: ~p\"\n\t \"~n Opts: ~p\", [Node, Vsns, Conf0, _Opts]),\n \n AtlDir = ?config(agent_log_dir, Conf0),\n ConfDir = ?config(agent_conf_dir, Conf0),\n DbDir = ?config(agent_db_dir, Conf0),\n\n MAV = get_opt(agent_verbosity, Conf0, trace),\n CV = get_opt(agent_config_verbosity, Conf0, info),\n LDBV = get_opt(agent_local_db_verbosity, Conf0, info),\n MSV = get_opt(agent_mib_server_verbosity, Conf0, info),\n NSV = get_opt(agent_note_store_verbosity, Conf0, info),\n SSV = get_opt(agent_symbolic_store_verbosity, Conf0, info),\n NIV = get_opt(agent_net_if_verbosity, Conf0, log),\n\n Env = [{versions, Vsns},\n\t {type, master},\n\t {agent_verbosity, MAV},\n\t {audit_trail_log, [{type, read_write},\n\t\t\t {dir, AtlDir},\n\t\t\t {size, {10240, 10}},\n\t\t\t {repair, true}]},\n\t {config, [{dir, ConfDir}, \n\t\t\t {force_load, false}, \n\t\t\t {verbosity, CV}]},\n\t {db_dir, DbDir},\n\t {local_db, [{repair, true},\n\t\t\t {auto_save, 10000},\n\t\t\t {verbosity, LDBV}]},\n\t {mib_server, [{verbosity, MSV}]},\n\t {note_store, [{verbosity, NSV}]},\n\t {stymbolic_store, [{verbosity, SSV}]},\n\t {net_if, [{verbosity, NIV}]},\n\t {multi_threaded, true}],\n ?line ok = set_agent_env(Node, Env),\n\n ?line ok = start_snmp(Node),\n Conf0.\n\nstop_agent(Node) ->\n stop_snmp(Node).\n\nagent_load_mib(Node, Mib) ->\n rcall(Node, snmpa, load_mibs, [[Mib]]).\n%% agent_unload_mib(Node, Mib) ->\n%% rcall(Node, snmpa, unload_mibs, [[Mib]]).\n\n%% agent_send_trap(Node, Trap, Community) ->\n%% Args = [snmp_master_agent, Trap, Community],\n%% rcall(Node, snmpa, send_trap, Args).\n\nagent_send_trap(Node, Trap, Community, VBs) ->\n Args = [snmp_master_agent, Trap, Community, VBs],\n rcall(Node, snmpa, send_trap, Args).\n\nagent_send_notif(Node, Trap, Name) ->\n agent_send_notif(Node, Trap, Name, []).\n\nagent_send_notif(Node, Trap, Name, VBs) ->\n agent_send_notif(Node, Trap, no_receiver, Name, VBs).\n\nagent_send_notif(Node, Trap, Recv, Name, VBs) ->\n Args = [snmp_master_agent, Trap, Recv, Name, VBs],\n rcall(Node, snmpa, send_notification, Args).\n\nagent_info(Node) ->\n rcall(Node, snmpa, info, []).\n\n%% agent_which_mibs(Node) ->\n%% rcall(Node, snmpa, which_mibs, []).\n\n\n%% -- Misc node operation wrapper functions --\n\nstart_agent_node() ->\n start_node(snmp_agent).\n\nstart_manager_node() ->\n start_node(snmp_manager).\n\nstart_node(Name) ->\n Pa = filename:dirname(code:which(?MODULE)),\n Args = case init:get_argument('CC_TEST') of\n {ok, [[]]} ->\n \" -pa \/clearcase\/otp\/libraries\/snmp\/ebin \";\n {ok, [[Path]]} ->\n \" -pa \" ++ Path;\n error ->\n \"\"\n end,\n A = Args ++ \" -pa \" ++ Pa,\n case (catch ?START_NODE(Name, A)) of\n\t{ok, Node} ->\n\t Node;\n\tElse ->\n\t ?line ?FAIL(Else)\n end.\n\nstop_node(Node) ->\n rpc:cast(Node, erlang, halt, []),\n await_stopped(Node, 5).\n\nawait_stopped(Node, 0) ->\n p(\"await_stopped -> ~p still exist: giving up\", [Node]),\n ok;\nawait_stopped(Node, N) ->\n Nodes = erlang:nodes(),\n case lists:member(Node, Nodes) of\n\ttrue ->\n\t p(\"await_stopped -> ~p still exist: ~w\", [Node, N]),\n\t ?SLEEP(1000),\n\t await_stopped(Node, N-1);\n\tfalse ->\n\t p(\"await_stopped -> ~p gone: ~w\", [Node, N]),\n\t ok\n end.\n \n \n\n%% -- Misc config wrapper functions --\n\nwrite_manager_config(Config) ->\n Dir = ?config(manager_conf_dir, Config),\n Ip = tuple_to_list(?config(ip, Config)),\n {Addr, Port} =\n\tcase ?config(ipfamily, Config) of\n\t inet ->\n\t\t{Ip, ?MGR_PORT};\n\t inet6 ->\n\t\t{transportDomainUdpIpv6, {Ip, ?MGR_PORT}}\n\tend,\n snmp_config:write_manager_snmp_files(\n Dir, Addr, Port, ?MGR_MMS, ?MGR_ENGINE_ID, [], [], []).\n\nwrite_manager_conf(Dir) ->\n Port = \"5000\",\n MMS = \"484\",\n EngineID = \"\\\"mgrEngine\\\"\",\n Str = lists:flatten(\n io_lib:format(\"%% Minimum manager config file\\n\"\n \"{port, ~s}.\\n\"\n \"{max_message_size, ~s}.\\n\"\n \"{engine_id, ~s}.\\n\",\n [Port, MMS, EngineID])),\n write_manager_conf(Dir, Str).\n\n%% write_manager_conf(Dir, IP, Port, MMS, EngineID) ->\n%% Str = lists:flatten(\n%% io_lib:format(\"{address, ~s}.\\n\"\n%% \"{port, ~s}.\\n\"\n%% \"{max_message_size, ~s}.\\n\"\n%% \"{engine_id, ~s}.\\n\",\n%% [IP, Port, MMS, EngineID])),\n%% write_manager_conf(Dir, Str).\n\nwrite_manager_conf(Dir, Str) ->\n write_conf_file(Dir, \"manager.conf\", Str).\n\n\nwrite_agent_config(Vsns, Conf) ->\n Dir = ?config(agent_conf_dir, Conf),\n ?line Ip = tuple_to_list(?config(ip, Conf)),\n ?line Domain =\n\tcase ?config(ipfamily, Conf) of\n\t inet ->\n\t\tsnmpUDPDomain;\n\t inet6 ->\n\t\ttransportDomainUdpIpv6\n\tend,\n ?line ok = write_agent_config_files(Dir, Vsns, Domain, Ip),\n ?line ok = update_agent_usm(Vsns, Dir),\n ?line ok = update_agent_community(Vsns, Dir),\n ?line ok = update_agent_vacm(Vsns, Dir),\n ?line ok = write_agent_target_addr_conf(Dir, Domain, Ip, Vsns),\n ?line ok = write_agent_target_params_conf(Dir, Vsns),\n ?line ok = write_agent_notify_conf(Dir),\n ok.\n \nwrite_agent_config_files(Dir, Vsns, Domain, Ip) ->\n snmp_config:write_agent_snmp_files(\n Dir, Vsns, Domain, {Ip, ?MGR_PORT}, {Ip, ?AGENT_PORT}, \"mgr-test\",\n trap, none, \"\", ?AGENT_ENGINE_ID, ?AGENT_MMS).\n\nupdate_agent_usm(Vsns, Dir) ->\n case lists:member(v3, Vsns) of\n true ->\n Conf = [{\"agentEngine\", \"all-rights\", \"all-rights\", zeroDotZero, \n usmNoAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"\", \"\"}, \n\n {\"agentEngine\", \"no-rights\", \"no-rights\", zeroDotZero, \n usmNoAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"\", \"\"}, \n\n {\"agentEngine\", \"authMD5\", \"authMD5\", zeroDotZero, \n usmHMACMD5AuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"passwd_md5xxxxxx\", \"\"}, \n\n {\"agentEngine\", \"authSHA\", \"authSHA\", zeroDotZero, \n usmHMACSHAAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \n \"passwd_shaxxxxxxxxxx\", \"\"}, \n\n {\"agentEngine\", \"privDES\", \"privDES\", zeroDotZero, \n usmHMACSHAAuthProtocol, \"\", \"\", \n usmDESPrivProtocol, \"\", \"\", \"\", \n \"passwd_shaxxxxxxxxxx\", \"passwd_desxxxxxx\"}, \n\n {\"mgrEngine\", \"all-rights\", \"all-rights\", zeroDotZero, \n usmNoAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"\", \"\"}, \n\n {\"mgrEngine\", \"no-rights\", \"no-rights\", zeroDotZero, \n usmNoAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"\", \"\"}, \n\n {\"mgrEngine\", \"authMD5\", \"authMD5\", zeroDotZero, \n usmHMACMD5AuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \"passwd_md5xxxxxx\", \"\"}, \n\n {\"mgrEngine\", \"authSHA\", \"authSHA\", zeroDotZero, \n usmHMACSHAAuthProtocol, \"\", \"\", \n usmNoPrivProtocol, \"\", \"\", \"\", \n \"passwd_shaxxxxxxxxxx\", \"\"}, \n\n {\"mgrEngine\", \"privDES\", \"privDES\", zeroDotZero, \n usmHMACSHAAuthProtocol, \"\", \"\", \n usmDESPrivProtocol, \"\", \"\", \"\", \n \"passwd_shaxxxxxxxxxx\", \"passwd_desxxxxxx\"}],\n snmp_config:update_agent_usm_config(Dir, Conf);\n false ->\n ok\n end.\n\nupdate_agent_community([v3], _Dir) -> \n ok;\nupdate_agent_community(_, Dir) ->\n Conf = [{\"no-rights\", \"no-rights\", \"no-rights\", \"\", \"\"}],\n snmp_config:update_agent_community_config(Dir, Conf).\n\nupdate_agent_vacm(_Vsns, Dir) ->\n Conf = [{vacmSecurityToGroup, usm, \"authMD5\", \"initial\"}, \n {vacmSecurityToGroup, usm, \"authSHA\", \"initial\"}, \n {vacmSecurityToGroup, usm, \"privDES\", \"initial\"}, \n {vacmSecurityToGroup, usm, \"newUser\", \"initial\"},\n {vacmViewTreeFamily, \"internet\", ?tDescr_instance, \n excluded, null}],\n snmp_config:update_agent_vacm_config(Dir, Conf).\n\nwrite_agent_target_addr_conf(Dir, Domain, Ip, Vsns) ->\n snmp_config:write_agent_snmp_target_addr_conf(\n Dir, Domain, {Ip, ?MGR_PORT}, 300, 3, Vsns).\n\nwrite_agent_target_params_conf(Dir, Vsns) -> \n F = fun(v1) -> {\"target_v1\", v1, v1, \"all-rights\", noAuthNoPriv};\n (v2) -> {\"target_v2\", v2c, v2c, \"all-rights\", noAuthNoPriv};\n (v3) -> {\"target_v3\", v3, usm, \"all-rights\", noAuthNoPriv}\n end,\n Conf = [F(Vsn) || Vsn <- Vsns],\n snmp_config:write_agent_target_params_config(Dir, \"\", Conf).\n\nwrite_agent_notify_conf(Dir) -> \n Conf = [{\"standard trap\", \"std_trap\", trap}, \n {\"standard inform\", \"std_inform\", inform}],\n snmp_config:write_agent_notify_config(Dir, \"\", Conf).\n\n\nwrite_conf_file(Dir, File, Str) ->\n ?line {ok, Fd} = file:open(filename:join(Dir, File), write),\n ?line ok = io:format(Fd, \"~s\", [Str]),\n file:close(Fd).\n \n\n%% ------\n\ndisplay_log(Config) ->\n case lists:keysearch(manager_log_dir, 1, Config) of\n\t{value, {_, Dir}} ->\n\t case lists:keysearch(manager_node, 1, Config) of\n\t\t{value, {_, Node}} ->\n\t\t LogDir = Dir, \n\t\t Mibs = [], \n\t\t OutFile = j(LogDir, \"snmpm_log.txt\"), \n\t\t p(\"~n\"\n\t\t \"=========================\"\n\t\t \" < Audit Trail Log > \"\n\t\t \"=========================\"\n\t\t \"~n\"),\n\t\t rcall(Node, snmpm, log_to_txt, [LogDir, Mibs, OutFile]),\n\t\t rcall(Node, snmpm, log_to_io, [LogDir, Mibs]),\n\t\t p(\"~n\"\n\t\t \"=========================\"\n\t\t \" < \/ Audit Trail Log > \"\n\t\t \"=========================\"\n\t\t \"~n\");\n\t\tfalse ->\n\t\t p(\"display_log -> no manager node found\"),\n\t\t ok\n\t end;\n\tfalse ->\n\t p(\"display_log -> no manager log dir found\"),\n\t ok\n end.\n\n\n%% ------\n\ntest2_mib(Config) ->\n j(test_mib_dir(Config), \"Test2.bin\").\n\ntest_trap_mib(Config) ->\n j(test_mib_dir(Config), \"TestTrap.bin\").\n\ntest_trap_v2_mib(Config) ->\n j(test_mib_dir(Config), \"TestTrapv2.bin\").\n\nstd_mib() ->\n j(mib_dir(), \"STANDARD-MIB.bin\").\n\nsnmpv2_mib() ->\n j(mib_dir(), \"SNMPv2-MIB.bin\").\n\ntest_mib_dir(Config) ->\n ?config(mib_dir, Config).\n\nmib_dir() ->\n j(code:priv_dir(snmp), \"mibs\").\n\nj(A, B) ->\n filename:join(A, B).\n\n\n%% ------\n\nget_opt(Key, Opts, Def) ->\n snmp_misc:get_option(Key, Opts, Def).\n\n\n%% ------\n\nrcall(Node, Mod, Func, Args) ->\n case rpc:call(Node, Mod, Func, Args) of\n\t{badrpc, nodedown} ->\n\t ?FAIL({rpc_failure, Node});\n\tElse ->\n\t Else\n end.\n\n\n%% ------\n\n%% Time in milli sec\n%% t() ->\n%% {A,B,C} = os:timestamp(),\n%% A*1000000000+B*1000+(C div 1000).\n\n\n%% ------\n\np(F) ->\n p(F, []).\n \np(F, A) ->\n p(get(tname), F, A).\n \np(TName, F, A) ->\n io:format(\"*** [~w][~s] ***\"\n \"~n \" ++ F ++ \"~n\", [TName, formated_timestamp()|A]).\n\nformated_timestamp() ->\n snmp_test_lib:formated_timestamp().\n\n%% p(TName, F, A) ->\n%% io:format(\"~w -> \" ++ F ++ \"~n\", [TName|A]).\n\nipv6_init(Config) when is_list(Config) ->\n [{ipfamily, inet6} | Config].\n","avg_line_length":27.9331083154,"max_line_length":82,"alphanum_fraction":0.5808928532} +{"size":24124,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% Copyright (c) 2014-2019, Lo\u00efc Hoguin \n%%\n%% Permission to use, copy, modify, and\/or distribute this software for any\n%% purpose with or without fee is hereby granted, provided that the above\n%% copyright notice and this permission notice appear in all copies.\n%%\n%% THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n-module(gun_http).\n\n-export([check_options\/1]).\n-export([name\/0]).\n-export([init\/4]).\n-export([handle\/2]).\n-export([close\/2]).\n-export([keepalive\/1]).\n-export([headers\/8]).\n-export([request\/9]).\n-export([data\/5]).\n-export([connect\/5]).\n-export([cancel\/3]).\n-export([stream_info\/2]).\n-export([down\/1]).\n-export([ws_upgrade\/7]).\n\n%% Functions shared with gun_http2.\n-export([host_header\/3]).\n\n-type io() :: head | {body, non_neg_integer()} | body_close | body_chunked | body_trailer.\n\n%% @todo Make that a record.\n-type connect_info() :: {connect, reference(), gun:connect_destination()}.\n\n%% @todo Make that a record.\n-type websocket_info() :: {websocket, reference(), binary(), [binary()], gun:ws_opts()}. %% key, extensions, options\n\n-record(stream, {\n\tref :: reference() | connect_info() | websocket_info(),\n\treply_to :: pid(),\n\tmethod :: binary(),\n\tis_alive :: boolean(),\n\thandler_state :: undefined | gun_content_handler:state()\n}).\n\n-record(http_state, {\n\towner :: pid(),\n\tsocket :: inet:socket() | ssl:sslsocket(),\n\ttransport :: module(),\n\tversion = 'HTTP\/1.1' :: cow_http:version(),\n\tcontent_handlers :: gun_content_handler:opt(),\n\tconnection = keepalive :: keepalive | close,\n\tbuffer = <<>> :: binary(),\n\tstreams = [] :: [#stream{}],\n\tin = head :: io(),\n\tin_state = {0, 0} :: {non_neg_integer(), non_neg_integer()},\n\tout = head :: io(),\n\ttransform_header_name :: fun((binary()) -> binary())\n}).\n\ncheck_options(Opts) ->\n\tdo_check_options(maps:to_list(Opts)).\n\ndo_check_options([]) ->\n\tok;\ndo_check_options([Opt={content_handlers, Handlers}|Opts]) ->\n\tcase gun_content_handler:check_option(Handlers) of\n\t\tok -> do_check_options(Opts);\n\t\terror -> {error, {options, {http, Opt}}}\n\tend;\ndo_check_options([{keepalive, infinity}|Opts]) ->\n\tdo_check_options(Opts);\ndo_check_options([{keepalive, K}|Opts]) when is_integer(K), K > 0 ->\n\tdo_check_options(Opts);\ndo_check_options([{transform_header_name, F}|Opts]) when is_function(F) ->\n\tdo_check_options(Opts);\ndo_check_options([{version, V}|Opts]) when V =:= 'HTTP\/1.1'; V =:= 'HTTP\/1.0' ->\n\tdo_check_options(Opts);\ndo_check_options([Opt|_]) ->\n\t{error, {options, {http, Opt}}}.\n\nname() -> http.\n\ninit(Owner, Socket, Transport, Opts) ->\n\tVersion = maps:get(version, Opts, 'HTTP\/1.1'),\n\tHandlers = maps:get(content_handlers, Opts, [gun_data_h]),\n\tTransformHeaderName = maps:get(transform_header_name, Opts, fun (N) -> N end),\n\t#http_state{owner=Owner, socket=Socket, transport=Transport, version=Version,\n\t\tcontent_handlers=Handlers, transform_header_name=TransformHeaderName}.\n\n%% Stop looping when we got no more data.\nhandle(<<>>, State) ->\n\t{state, State};\n%% Close when server responds and we don't have any open streams.\nhandle(_, #http_state{streams=[]}) ->\n\tclose;\n%% Wait for the full response headers before trying to parse them.\nhandle(Data, State=#http_state{in=head, buffer=Buffer}) ->\n\tData2 = << Buffer\/binary, Data\/binary >>,\n\tcase binary:match(Data2, <<\"\\r\\n\\r\\n\">>) of\n\t\tnomatch -> {state, State#http_state{buffer=Data2}};\n\t\t{_, _} -> handle_head(Data2, State#http_state{buffer= <<>>})\n\tend;\n%% Everything sent to the socket until it closes is part of the response body.\nhandle(Data, State=#http_state{in=body_close}) ->\n\t{state, send_data_if_alive(Data, State, nofin)};\n%% Chunked transfer-encoding may contain both data and trailers.\nhandle(Data, State=#http_state{in=body_chunked, in_state=InState,\n\t\tbuffer=Buffer, connection=Conn}) ->\n\tBuffer2 = << Buffer\/binary, Data\/binary >>,\n\tcase cow_http_te:stream_chunked(Buffer2, InState) of\n\t\tmore ->\n\t\t\t{state, State#http_state{buffer=Buffer2}};\n\t\t{more, Data2, InState2} ->\n\t\t\t{state, send_data_if_alive(Data2,\n\t\t\t\tState#http_state{buffer= <<>>, in_state=InState2},\n\t\t\t\tnofin)};\n\t\t{more, Data2, Length, InState2} when is_integer(Length) ->\n\t\t\t%% @todo See if we can recv faster than one message at a time.\n\t\t\t{state, send_data_if_alive(Data2,\n\t\t\t\tState#http_state{buffer= <<>>, in_state=InState2},\n\t\t\t\tnofin)};\n\t\t{more, Data2, Rest, InState2} ->\n\t\t\t%% @todo See if we can recv faster than one message at a time.\n\t\t\t{state, send_data_if_alive(Data2,\n\t\t\t\tState#http_state{buffer=Rest, in_state=InState2},\n\t\t\t\tnofin)};\n\t\t{done, HasTrailers, Rest} ->\n\t\t\tIsFin = case HasTrailers of\n\t\t\t\ttrailers -> nofin;\n\t\t\t\tno_trailers -> fin\n\t\t\tend,\n\t\t\t%% I suppose it doesn't hurt to append an empty binary.\n\t\t\tState1 = send_data_if_alive(<<>>, State, IsFin),\n\t\t\tcase {HasTrailers, Conn} of\n\t\t\t\t{trailers, _} ->\n\t\t\t\t\thandle(Rest, State1#http_state{buffer = <<>>, in=body_trailer});\n\t\t\t\t{no_trailers, keepalive} ->\n\t\t\t\t\thandle(Rest, end_stream(State1#http_state{buffer= <<>>}));\n\t\t\t\t{no_trailers, close} ->\n\t\t\t\t\t[{state, end_stream(State1)}, close]\n\t\t\tend;\n\t\t{done, Data2, HasTrailers, Rest} ->\n\t\t\tIsFin = case HasTrailers of\n\t\t\t\ttrailers -> nofin;\n\t\t\t\tno_trailers -> fin\n\t\t\tend,\n\t\t\tState1 = send_data_if_alive(Data2, State, IsFin),\n\t\t\tcase {HasTrailers, Conn} of\n\t\t\t\t{trailers, _} ->\n\t\t\t\t\thandle(Rest, State1#http_state{buffer = <<>>, in=body_trailer});\n\t\t\t\t{no_trailers, keepalive} ->\n\t\t\t\t\thandle(Rest, end_stream(State1#http_state{buffer= <<>>}));\n\t\t\t\t{no_trailers, close} ->\n\t\t\t\t\t[{state, end_stream(State1)}, close]\n\t\t\tend\n\tend;\nhandle(Data, State=#http_state{in=body_trailer, buffer=Buffer, connection=Conn,\n\t\tstreams=[#stream{ref=StreamRef, reply_to=ReplyTo}|_]}) ->\n\tData2 = << Buffer\/binary, Data\/binary >>,\n\tcase binary:match(Data2, <<\"\\r\\n\\r\\n\">>) of\n\t\tnomatch -> {state, State#http_state{buffer=Data2}};\n\t\t{_, _} ->\n\t\t\t{Trailers, Rest} = cow_http:parse_headers(Data2),\n\t\t\t%% @todo We probably want to pass this to gun_content_handler?\n\t\t\tReplyTo ! {gun_trailers, self(), stream_ref(StreamRef), Trailers},\n\t\t\tcase Conn of\n\t\t\t\tkeepalive ->\n\t\t\t\t\thandle(Rest, end_stream(State#http_state{buffer= <<>>}));\n\t\t\t\tclose ->\n\t\t\t\t\t[{state, end_stream(State)}, close]\n\t\t\tend\n\tend;\n%% We know the length of the rest of the body.\nhandle(Data, State=#http_state{in={body, Length}, connection=Conn}) ->\n\tDataSize = byte_size(Data),\n\tif\n\t\t%% More data coming.\n\t\tDataSize < Length ->\n\t\t\t{state, send_data_if_alive(Data,\n\t\t\t\tState#http_state{in={body, Length - DataSize}},\n\t\t\t\tnofin)};\n\t\t%% Stream finished, no rest.\n\t\tDataSize =:= Length ->\n\t\t\tState1 = send_data_if_alive(Data, State, fin),\n\t\t\tcase Conn of\n\t\t\t\tkeepalive -> {state, end_stream(State1)};\n\t\t\t\tclose -> [{state, end_stream(State1)}, close]\n\t\t\tend;\n\t\t%% Stream finished, rest.\n\t\ttrue ->\n\t\t\t<< Body:Length\/binary, Rest\/bits >> = Data,\n\t\t\tState1 = send_data_if_alive(Body, State, fin),\n\t\t\tcase Conn of\n\t\t\t\tkeepalive -> handle(Rest, end_stream(State1));\n\t\t\t\tclose -> [{state, end_stream(State1)}, close]\n\t\t\tend\n\tend.\n\nhandle_head(Data, State=#http_state{socket=Socket, version=ClientVersion,\n\t\tcontent_handlers=Handlers0, connection=Conn,\n\t\tstreams=[Stream=#stream{ref=StreamRef, reply_to=ReplyTo,\n\t\t\tmethod=Method, is_alive=IsAlive}|Tail]}) ->\n\t{Version, Status, _, Rest} = cow_http:parse_status_line(Data),\n\t{Headers, Rest2} = cow_http:parse_headers(Rest),\n\tcase {Status, StreamRef} of\n\t\t{101, {websocket, RealStreamRef, WsKey, WsExtensions, WsOpts}} ->\n\t\t\tws_handshake(Rest2, State, RealStreamRef, Headers, WsKey, WsExtensions, WsOpts);\n\t\t{_, {connect, RealStreamRef, Destination}} when Status >= 200, Status < 300 ->\n\t\t\tcase IsAlive of\n\t\t\t\tfalse ->\n\t\t\t\t\tok;\n\t\t\t\ttrue ->\n\t\t\t\t\tReplyTo ! {gun_response, self(), RealStreamRef,\n\t\t\t\t\t\tfin, Status, Headers},\n\t\t\t\t\tok\n\t\t\tend,\n\t\t\t%% We expect there to be no additional data after the CONNECT response.\n\t\t\t<<>> = Rest2,\n\t\t\tState2 = end_stream(State#http_state{streams=[Stream|Tail]}),\n\t\t\tNewHost = maps:get(host, Destination),\n\t\t\tNewPort = maps:get(port, Destination),\n\t\t\tcase Destination of\n\t\t\t\t#{transport := tls} ->\n\t\t\t\t\tTLSOpts = maps:get(tls_opts, Destination, []),\n\t\t\t\t\tTLSTimeout = maps:get(tls_handshake_timeout, Destination, infinity),\n\t\t\t\t\tcase gun_tls:connect(Socket, TLSOpts, TLSTimeout) of\n\t\t\t\t\t\t{ok, TLSSocket} ->\n\t\t\t\t\t\t\tcase ssl:negotiated_protocol(TLSSocket) of\n\t\t\t\t\t\t\t\t{ok, <<\"h2\">>} ->\n\t\t\t\t\t\t\t\t\t[{origin, <<\"https\">>, NewHost, NewPort, connect},\n\t\t\t\t\t\t\t\t\t\t{switch_transport, gun_tls, TLSSocket},\n\t\t\t\t\t\t\t\t\t\t{switch_protocol, gun_http2, State2}];\n\t\t\t\t\t\t\t\t_ ->\n\t\t\t\t\t\t\t\t\t[{state, State2#http_state{socket=TLSSocket, transport=gun_tls}},\n\t\t\t\t\t\t\t\t\t\t{origin, <<\"https\">>, NewHost, NewPort, connect},\n\t\t\t\t\t\t\t\t\t\t{switch_transport, gun_tls, TLSSocket}]\n\t\t\t\t\t\t\tend;\n\t\t\t\t\t\tError ->\n\t\t\t\t\t\t\tError\n\t\t\t\t\tend;\n\t\t\t\t_ ->\n\t\t\t\t\tcase maps:get(protocols, Destination, [http]) of\n\t\t\t\t\t\t[http] ->\n\t\t\t\t\t\t\t[{state, State2},\n\t\t\t\t\t\t\t\t{origin, <<\"http\">>, NewHost, NewPort, connect}];\n\t\t\t\t\t\t[http2] ->\n\t\t\t\t\t\t\t[{origin, <<\"http\">>, NewHost, NewPort, connect},\n\t\t\t\t\t\t\t\t{switch_protocol, gun_http2, State2}]\n\t\t\t\t\tend\n\t\t\tend;\n\t\t{_, _} when Status >= 100, Status =< 199 ->\n\t\t\tReplyTo ! {gun_inform, self(), stream_ref(StreamRef), Status, Headers},\n\t\t\thandle(Rest2, State);\n\t\t_ ->\n\t\t\tIn = response_io_from_headers(Method, Version, Status, Headers),\n\t\t\tIsFin = case In of head -> fin; _ -> nofin end,\n\t\t\tHandlers = case IsAlive of\n\t\t\t\tfalse ->\n\t\t\t\t\tundefined;\n\t\t\t\ttrue ->\n\t\t\t\t\tReplyTo ! {gun_response, self(), stream_ref(StreamRef),\n\t\t\t\t\t\tIsFin, Status, Headers},\n\t\t\t\t\tcase IsFin of\n\t\t\t\t\t\tfin -> undefined;\n\t\t\t\t\t\tnofin ->\n\t\t\t\t\t\t\tgun_content_handler:init(ReplyTo, stream_ref(StreamRef),\n\t\t\t\t\t\t\t\tStatus, Headers, Handlers0)\n\t\t\t\t\tend\n\t\t\tend,\n\t\t\tConn2 = if\n\t\t\t\tConn =:= close -> close;\n\t\t\t\tVersion =:= 'HTTP\/1.0' -> close;\n\t\t\t\tClientVersion =:= 'HTTP\/1.0' -> close;\n\t\t\t\ttrue -> conn_from_headers(Version, Headers)\n\t\t\tend,\n\t\t\t%% We always reset in_state even if not chunked.\n\t\t\tif\n\t\t\t\tIsFin =:= fin, Conn2 =:= close ->\n\t\t\t\t\tclose;\n\t\t\t\tIsFin =:= fin ->\n\t\t\t\t\thandle(Rest2, end_stream(State#http_state{in=In,\n\t\t\t\t\t\tin_state={0, 0}, connection=Conn2,\n\t\t\t\t\t\tstreams=[Stream#stream{handler_state=Handlers}|Tail]}));\n\t\t\t\ttrue ->\n\t\t\t\t\thandle(Rest2, State#http_state{in=In,\n\t\t\t\t\t\tin_state={0, 0}, connection=Conn2,\n\t\t\t\t\t\tstreams=[Stream#stream{handler_state=Handlers}|Tail]})\n\t\t\tend\n\tend.\n\nstream_ref({connect, StreamRef, _}) -> StreamRef;\nstream_ref({websocket, StreamRef, _, _, _}) -> StreamRef;\nstream_ref(StreamRef) -> StreamRef.\n\nsend_data_if_alive(<<>>, State, nofin) ->\n\tState;\n%% @todo What if we receive data when the HEAD method was used?\nsend_data_if_alive(Data, State=#http_state{streams=[Stream=#stream{\n\t\tis_alive=true, handler_state=Handlers0}|Tail]}, IsFin) ->\n\tHandlers = gun_content_handler:handle(IsFin, Data, Handlers0),\n\tState#http_state{streams=[Stream#stream{handler_state=Handlers}|Tail]};\nsend_data_if_alive(_, State, _) ->\n\tState.\n\n%% @todo Use Reason.\nclose(_, State=#http_state{in=body_close, streams=[_|Tail]}) ->\n\t_ = send_data_if_alive(<<>>, State, fin),\n\tclose_streams(Tail);\nclose(_, #http_state{streams=Streams}) ->\n\tclose_streams(Streams).\n\nclose_streams([]) ->\n\tok;\nclose_streams([#stream{is_alive=false}|Tail]) ->\n\tclose_streams(Tail);\nclose_streams([#stream{ref=StreamRef, reply_to=ReplyTo}|Tail]) ->\n\tReplyTo ! {gun_error, self(), StreamRef, {closed,\n\t\t\"The connection was lost.\"}},\n\tclose_streams(Tail).\n\n%% We don't send a keep-alive when a CONNECT request was initiated.\nkeepalive(State=#http_state{streams=[#stream{ref={connect, _, _}}]}) ->\n\tState;\n%% We can only keep-alive by sending an empty line in-between streams.\nkeepalive(State=#http_state{socket=Socket, transport=Transport, out=head}) ->\n\tTransport:send(Socket, <<\"\\r\\n\">>),\n\tState;\nkeepalive(State) ->\n\tState.\n\nheaders(State=#http_state{socket=Socket, transport=Transport, version=Version,\n\t\tout=head}, StreamRef, ReplyTo, Method, Host, Port, Path, Headers) ->\n\tHeaders2 = lists:keydelete(<<\"transfer-encoding\">>, 1, Headers),\n\tHeaders3 = case lists:keymember(<<\"host\">>, 1, Headers) of\n\t\tfalse -> [{<<\"host\">>, host_header(Transport, Host, Port)}|Headers2];\n\t\ttrue -> Headers2\n\tend,\n\t%% We use Headers2 because this is the smallest list.\n\tConn = conn_from_headers(Version, Headers2),\n\tOut = request_io_from_headers(Headers2),\n\tHeaders4 = case Out of\n\t\tbody_chunked when Version =:= 'HTTP\/1.0' -> Headers3;\n\t\tbody_chunked -> [{<<\"transfer-encoding\">>, <<\"chunked\">>}|Headers3];\n\t\t_ -> Headers3\n\tend,\n\tHeaders5 = transform_header_names(State, Headers4),\n\tTransport:send(Socket, cow_http:request(Method, Path, Version, Headers5)),\n\tnew_stream(State#http_state{connection=Conn, out=Out}, StreamRef, ReplyTo, Method).\n\nrequest(State=#http_state{socket=Socket, transport=Transport, version=Version,\n\t\tout=head}, StreamRef, ReplyTo, Method, Host, Port, Path, Headers, Body) ->\n\tHeaders2 = lists:keydelete(<<\"content-length\">>, 1,\n\t\tlists:keydelete(<<\"transfer-encoding\">>, 1, Headers)),\n\tHeaders3 = case lists:keymember(<<\"host\">>, 1, Headers) of\n\t\tfalse -> [{<<\"host\">>, host_header(Transport, Host, Port)}|Headers2];\n\t\ttrue -> Headers2\n\tend,\n\tHeaders4 = transform_header_names(State, Headers3),\n\t%% We use Headers2 because this is the smallest list.\n\tConn = conn_from_headers(Version, Headers2),\n\tTransport:send(Socket, [\n\t\tcow_http:request(Method, Path, Version, [\n\t\t\t{<<\"content-length\">>, integer_to_binary(iolist_size(Body))}\n\t\t|Headers4]),\n\t\tBody]),\n\tnew_stream(State#http_state{connection=Conn}, StreamRef, ReplyTo, Method).\n\nhost_header(Transport, Host0, Port) ->\n\tHost = case Host0 of\n\t\t{local, _SocketPath} -> <<>>;\n\t\tTuple when is_tuple(Tuple) -> inet:ntoa(Tuple);\n\t\tAtom when is_atom(Atom) -> atom_to_list(Atom);\n\t\t_ -> Host0\n\tend,\n\tcase {Transport:name(), Port} of\n\t\t{tcp, 80} -> Host;\n\t\t{tls, 443} -> Host;\n\t\t_ -> [Host, $:, integer_to_binary(Port)]\n\tend.\n\ntransform_header_names(#http_state{transform_header_name = Fun}, Headers) ->\n\tlists:keymap(Fun, 1, Headers).\n\n%% We are expecting a new stream.\ndata(State=#http_state{out=head}, StreamRef, ReplyTo, _, _) ->\n\terror_stream_closed(State, StreamRef, ReplyTo);\n%% There are no active streams.\ndata(State=#http_state{streams=[]}, StreamRef, ReplyTo, _, _) ->\n\terror_stream_not_found(State, StreamRef, ReplyTo);\n%% We can only send data on the last created stream.\ndata(State=#http_state{socket=Socket, transport=Transport, version=Version,\n\t\tout=Out, streams=Streams}, StreamRef, ReplyTo, IsFin, Data) ->\n\tcase lists:last(Streams) of\n\t\t#stream{ref=StreamRef, is_alive=true} ->\n\t\t\tDataLength = iolist_size(Data),\n\t\t\tcase Out of\n\t\t\t\tbody_chunked when Version =:= 'HTTP\/1.1', IsFin =:= fin ->\n\t\t\t\t\tcase Data of\n\t\t\t\t\t\t<<>> ->\n\t\t\t\t\t\t\tTransport:send(Socket, cow_http_te:last_chunk());\n\t\t\t\t\t\t_ ->\n\t\t\t\t\t\t\tTransport:send(Socket, [\n\t\t\t\t\t\t\t\tcow_http_te:chunk(Data),\n\t\t\t\t\t\t\t\tcow_http_te:last_chunk()\n\t\t\t\t\t\t\t])\n\t\t\t\t\tend,\n\t\t\t\t\tState#http_state{out=head};\n\t\t\t\tbody_chunked when Version =:= 'HTTP\/1.1' ->\n\t\t\t\t\tTransport:send(Socket, cow_http_te:chunk(Data)),\n\t\t\t\t\tState;\n\t\t\t\t{body, Length} when DataLength =< Length ->\n\t\t\t\t\tTransport:send(Socket, Data),\n\t\t\t\t\tLength2 = Length - DataLength,\n\t\t\t\t\tif\n\t\t\t\t\t\tLength2 =:= 0, IsFin =:= fin ->\n\t\t\t\t\t\t\tState#http_state{out=head};\n\t\t\t\t\t\tLength2 > 0, IsFin =:= nofin ->\n\t\t\t\t\t\t\tState#http_state{out={body, Length2}}\n\t\t\t\t\tend;\n\t\t\t\tbody_chunked -> %% HTTP\/1.0\n\t\t\t\t\tTransport:send(Socket, Data),\n\t\t\t\t\tState\n\t\t\tend;\n\t\t_ ->\n\t\t\terror_stream_not_found(State, StreamRef, ReplyTo)\n\tend.\n\nconnect(State=#http_state{streams=Streams}, StreamRef, ReplyTo, _, _) when Streams =\/= [] ->\n\tReplyTo ! {gun_error, self(), StreamRef, {badstate,\n\t\t\"CONNECT can only be used with HTTP\/1.1 when no other streams are active.\"}},\n\tState;\nconnect(State=#http_state{socket=Socket, transport=Transport, version=Version},\n\t\tStreamRef, ReplyTo, Destination=#{host := Host0}, Headers0) ->\n\tHost = case Host0 of\n\t\tTuple when is_tuple(Tuple) -> inet:ntoa(Tuple);\n\t\t_ -> Host0\n\tend,\n\tPort = maps:get(port, Destination, 1080),\n\tAuthority = [Host, $:, integer_to_binary(Port)],\n\tHeaders1 = lists:keydelete(<<\"content-length\">>, 1,\n\t\tlists:keydelete(<<\"transfer-encoding\">>, 1, Headers0)),\n\tHeaders2 = case lists:keymember(<<\"host\">>, 1, Headers1) of\n\t\tfalse -> [{<<\"host\">>, Authority}|Headers1];\n\t\ttrue -> Headers1\n\tend,\n\tHasProxyAuthorization = lists:keymember(<<\"proxy-authorization\">>, 1, Headers2),\n\tHeaders3 = case {HasProxyAuthorization, Destination} of\n\t\t{false, #{username := UserID, password := Password}} ->\n\t\t\t[{<<\"proxy-authorization\">>, [\n\t\t\t\t\t<<\"Basic \">>,\n\t\t\t\t\tbase64:encode(iolist_to_binary([UserID, $:, Password]))]}\n\t\t\t\t|Headers2];\n\t\t_ ->\n\t\t\tHeaders2\n\tend,\n\tHeaders = transform_header_names(State, Headers3),\n\tTransport:send(Socket, [\n\t\tcow_http:request(<<\"CONNECT\">>, Authority, Version, Headers)\n\t]),\n\tnew_stream(State, {connect, StreamRef, Destination}, ReplyTo, <<\"CONNECT\">>).\n\n%% We can't cancel anything, we can just stop forwarding messages to the owner.\ncancel(State, StreamRef, ReplyTo) ->\n\tcase is_stream(State, StreamRef) of\n\t\ttrue ->\n\t\t\tcancel_stream(State, StreamRef);\n\t\tfalse ->\n\t\t\terror_stream_not_found(State, StreamRef, ReplyTo)\n\tend.\n\nstream_info(#http_state{streams=Streams}, StreamRef) ->\n\tcase lists:keyfind(StreamRef, #stream.ref, Streams) of\n\t\t#stream{reply_to=ReplyTo, is_alive=IsAlive} ->\n\t\t\t{ok, #{\n\t\t\t\tref => StreamRef,\n\t\t\t\treply_to => ReplyTo,\n\t\t\t\tstate => case IsAlive of\n\t\t\t\t\ttrue -> running;\n\t\t\t\t\tfalse -> stopping\n\t\t\t\tend\n\t\t\t}};\n\t\tfalse ->\n\t\t\t{ok, undefined}\n\tend.\n\n%% HTTP does not provide any way to figure out what streams are unprocessed.\ndown(#http_state{streams=Streams}) ->\n\tKilledStreams = [case Ref of\n\t\t{connect, Ref2, _} -> Ref2;\n\t\t{websocket, Ref2, _, _, _} -> Ref2;\n\t\t_ -> Ref\n\tend || #stream{ref=Ref} <- Streams],\n\t{KilledStreams, []}.\n\nerror_stream_closed(State, StreamRef, ReplyTo) ->\n\tReplyTo ! {gun_error, self(), StreamRef, {badstate,\n\t\t\"The stream has already been closed.\"}},\n\tState.\n\nerror_stream_not_found(State, StreamRef, ReplyTo) ->\n\tReplyTo ! {gun_error, self(), StreamRef, {badstate,\n\t\t\"The stream cannot be found.\"}},\n\tState.\n\n%% Headers information retrieval.\n\nconn_from_headers(Version, Headers) ->\n\tcase lists:keyfind(<<\"connection\">>, 1, Headers) of\n\t\tfalse when Version =:= 'HTTP\/1.0' ->\n\t\t\tclose;\n\t\tfalse ->\n\t\t\tkeepalive;\n\t\t{_, ConnHd} ->\n\t\t\tConnList = cow_http_hd:parse_connection(ConnHd),\n\t\t\tcase lists:member(<<\"keep-alive\">>, ConnList) of\n\t\t\t\ttrue -> keepalive;\n\t\t\t\tfalse -> close\n\t\t\tend\n\tend.\n\nrequest_io_from_headers(Headers) ->\n\tcase lists:keyfind(<<\"content-length\">>, 1, Headers) of\n\t\t{_, <<\"0\">>} ->\n\t\t\thead;\n\t\t{_, Length} ->\n\t\t\t{body, cow_http_hd:parse_content_length(Length)};\n\t\t_ ->\n\t\t\tbody_chunked\n\tend.\n\nresponse_io_from_headers(<<\"HEAD\">>, _, _, _) ->\n\thead;\nresponse_io_from_headers(_, _, Status, _) when (Status =:= 204) or (Status =:= 304) ->\n\thead;\nresponse_io_from_headers(_, Version, _Status, Headers) ->\n\tcase lists:keyfind(<<\"transfer-encoding\">>, 1, Headers) of\n\t\t{_, TE} when Version =:= 'HTTP\/1.1' ->\n\t\t\tcase cow_http_hd:parse_transfer_encoding(TE) of\n\t\t\t\t[<<\"chunked\">>] -> body_chunked;\n\t\t\t\t[<<\"identity\">>] -> body_close\n\t\t\tend;\n\t\t_ ->\n\t\t\tcase lists:keyfind(<<\"content-length\">>, 1, Headers) of\n\t\t\t\t{_, <<\"0\">>} ->\n\t\t\t\t\thead;\n\t\t\t\t{_, Length} ->\n\t\t\t\t\t{body, cow_http_hd:parse_content_length(Length)};\n\t\t\t\t_ ->\n\t\t\t\t\tbody_close\n\t\t\tend\n\tend.\n\n%% Streams.\n\nnew_stream(State=#http_state{streams=Streams}, StreamRef, ReplyTo, Method) ->\n\tState#http_state{streams=Streams\n\t\t++ [#stream{ref=StreamRef, reply_to=ReplyTo,\n\t\t\tmethod=iolist_to_binary(Method), is_alive=true}]}.\n\nis_stream(#http_state{streams=Streams}, StreamRef) ->\n\tlists:keymember(StreamRef, #stream.ref, Streams).\n\ncancel_stream(State=#http_state{streams=Streams}, StreamRef) ->\n\tStreams2 = [case Ref of\n\t\tStreamRef ->\n\t\t\tTuple#stream{is_alive=false};\n\t\t_ ->\n\t\t\tTuple\n\tend || Tuple = #stream{ref=Ref} <- Streams],\n\tState#http_state{streams=Streams2}.\n\nend_stream(State=#http_state{streams=[_|Tail]}) ->\n\tState#http_state{in=head, streams=Tail}.\n\n%% Websocket upgrade.\n\n%% Ensure version is 1.1.\nws_upgrade(#http_state{version='HTTP\/1.0'}, _, _, _, _, _, _) ->\n\terror; %% @todo\nws_upgrade(State=#http_state{socket=Socket, transport=Transport, owner=Owner, out=head},\n\t\tStreamRef, Host, Port, Path, Headers0, WsOpts) ->\n\t{Headers1, GunExtensions} = case maps:get(compress, WsOpts, false) of\n\t\ttrue -> {[{<<\"sec-websocket-extensions\">>,\n\t\t\t\t<<\"permessage-deflate; client_max_window_bits; server_max_window_bits=15\">>}\n\t\t\t|Headers0],\n\t\t\t[<<\"permessage-deflate\">>]};\n\t\tfalse -> {Headers0, []}\n\tend,\n\tHeaders2 = case maps:get(protocols, WsOpts, []) of\n\t\t[] -> Headers1;\n\t\tProtoOpt ->\n\t\t\t<< _, _, Proto\/bits >> = iolist_to_binary([[<<\", \">>, P] || {P, _} <- ProtoOpt]),\n\t\t\t[{<<\"sec-websocket-protocol\">>, Proto}|Headers1]\n\tend,\n\tKey = cow_ws:key(),\n\tHeaders3 = [\n\t\t{<<\"connection\">>, <<\"upgrade\">>},\n\t\t{<<\"upgrade\">>, <<\"websocket\">>},\n\t\t{<<\"sec-websocket-version\">>, <<\"13\">>},\n\t\t{<<\"sec-websocket-key\">>, Key}\n\t\t|Headers2\n\t],\n\tIsSecure = Transport =:= gun_tls,\n\tHeaders = case lists:keymember(<<\"host\">>, 1, Headers0) of\n\t\ttrue -> Headers3;\n\t\tfalse when Port =:= 80, not IsSecure -> [{<<\"host\">>, Host}|Headers3];\n\t\tfalse when Port =:= 443, IsSecure -> [{<<\"host\">>, Host}|Headers3];\n\t\tfalse -> [{<<\"host\">>, [Host, $:, integer_to_binary(Port)]}|Headers3]\n\tend,\n\tTransport:send(Socket, cow_http:request(<<\"GET\">>, Path, 'HTTP\/1.1', Headers)),\n\tnew_stream(State#http_state{connection=keepalive, out=head},\n\t\t{websocket, StreamRef, Key, GunExtensions, WsOpts}, Owner, <<\"GET\">>).\n\nws_handshake(Buffer, State, StreamRef, Headers, Key, GunExtensions, Opts) ->\n\t%% @todo check upgrade, connection\n\tcase lists:keyfind(<<\"sec-websocket-accept\">>, 1, Headers) of\n\t\tfalse ->\n\t\t\tclose;\n\t\t{_, Accept} ->\n\t\t\tcase cow_ws:encode_key(Key) of\n\t\t\t\tAccept ->\n\t\t\t\t\tws_handshake_extensions(Buffer, State, StreamRef,\n\t\t\t\t\t\tHeaders, GunExtensions, Opts);\n\t\t\t\t_ ->\n\t\t\t\t\tclose\n\t\t\tend\n\tend.\n\nws_handshake_extensions(Buffer, State, StreamRef, Headers, GunExtensions, Opts) ->\n\tcase lists:keyfind(<<\"sec-websocket-extensions\">>, 1, Headers) of\n\t\tfalse ->\n\t\t\tws_handshake_protocols(Buffer, State, StreamRef, Headers, #{}, Opts);\n\t\t{_, ExtHd} ->\n\t\t\tcase ws_validate_extensions(cow_http_hd:parse_sec_websocket_extensions(ExtHd), GunExtensions, #{}, Opts) of\n\t\t\t\tclose ->\n\t\t\t\t\tclose;\n\t\t\t\tExtensions ->\n\t\t\t\t\tws_handshake_protocols(Buffer, State, StreamRef, Headers, Extensions, Opts)\n\t\t\tend\n\tend.\n\nws_validate_extensions([], _, Acc, _) ->\n\tAcc;\nws_validate_extensions([{Name = <<\"permessage-deflate\">>, Params}|Tail], GunExts, Acc, Opts) ->\n\tcase lists:member(Name, GunExts) of\n\t\ttrue ->\n\t\t\tcase cow_ws:validate_permessage_deflate(Params, Acc, Opts) of\n\t\t\t\t{ok, Acc2} -> ws_validate_extensions(Tail, GunExts, Acc2, Opts);\n\t\t\t\terror -> close\n\t\t\tend;\n\t\t%% Fail the connection if extension was not requested.\n\t\tfalse ->\n\t\t\tclose\n\tend;\n%% Fail the connection on unknown extension.\nws_validate_extensions(_, _, _, _) ->\n\tclose.\n\n%% @todo Validate protocols.\nws_handshake_protocols(Buffer, State, StreamRef, Headers, Extensions, Opts) ->\n\tcase lists:keyfind(<<\"sec-websocket-protocol\">>, 1, Headers) of\n\t\tfalse ->\n\t\t\tws_handshake_end(Buffer, State, StreamRef, Headers, Extensions,\n\t\t\t\tmaps:get(default_protocol, Opts, gun_ws_h), Opts);\n\t\t{_, Proto} ->\n\t\t\tProtoOpt = maps:get(protocols, Opts, []),\n\t\t\tcase lists:keyfind(Proto, 1, ProtoOpt) of\n\t\t\t\t{_, Handler} ->\n\t\t\t\t\tws_handshake_end(Buffer, State, StreamRef,\n\t\t\t\t\t\tHeaders, Extensions, Handler, Opts);\n\t\t\t\tfalse ->\n\t\t\t\t\tclose\n\t\t\tend\n\tend.\n\nws_handshake_end(Buffer, #http_state{owner=Owner, socket=Socket, transport=Transport},\n\t\tStreamRef, Headers, Extensions, Handler, Opts) ->\n\t%% Send ourselves the remaining buffer, if any.\n\t_ = case Buffer of\n\t\t<<>> ->\n\t\t\tok;\n\t\t_ ->\n\t\t\t{OK, _, _} = Transport:messages(),\n\t\t\tself() ! {OK, Socket, Buffer}\n\tend,\n\tgun_ws:init(Owner, Socket, Transport, StreamRef, Headers, Extensions, Handler, Opts).\n","avg_line_length":34.810966811,"max_line_length":116,"alphanum_fraction":0.6721522136} +{"size":6099,"ext":"erl","lang":"Erlang","max_stars_count":1588.0,"content":"%% Copyright 2018 Octavo Labs AG Zurich Switzerland (https:\/\/octavolabs.com)\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n-module(vmq_swc_edist_srv).\n-include(\"vmq_swc.hrl\").\n\n-behaviour(gen_server).\n\n%% API\n-export([start_link\/1,\n transport_init\/2,\n start_connection\/2,\n stop_connection\/2,\n rpc\/5,\n rpc_cast\/5]).\n\n%% gen_server callbacks\n-export([init\/1,\n handle_call\/3,\n handle_cast\/2,\n handle_info\/2,\n terminate\/2,\n code_change\/3]).\n\n-define(SERVER, ?MODULE).\n\n-record(state, {config}).\n\n%%%===================================================================\n%%% API\n%%%===================================================================\n\n%%--------------------------------------------------------------------\n%% @doc\n%% Starts the server\n%%\n%% @end\n%%--------------------------------------------------------------------\n-spec start_link(SwcConfig::config()) -> {ok, Pid::pid()} | ignore | {error, Error::term()}.\nstart_link(#swc_config{group=SwcGroup} = Config) ->\n gen_server:start_link({local, name(SwcGroup)}, ?MODULE, [Config], []).\n\ntransport_init(_Config, _Opts) ->\n ok.\n\nstart_connection(_Config, _Member) ->\n ok.\n\nstop_connection(_Config, _Member) ->\n ok.\n\nrpc(SwcGroup, RemotePeer, Module, Function, Args) ->\n gen_server:call({name(SwcGroup), RemotePeer}, {apply, Module, Function, Args}, infinity).\n\nrpc_cast(SwcGroup, RemotePeer, Module, Function, Args) ->\n gen_server:cast({name(SwcGroup), RemotePeer}, {apply, Module, Function, Args}).\n\nname(SwcGroup) ->\n list_to_atom(\"vmq_swc_edist_\" ++ atom_to_list(SwcGroup)).\n\n\n%%%===================================================================\n%%% gen_server callbacks\n%%%===================================================================\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% Initializes the server\n%%\n%% @spec init(Args) -> {ok, State} |\n%% {ok, State, Timeout} |\n%% ignore |\n%% {stop, Reason}\n%% @end\n%%--------------------------------------------------------------------\ninit([Config]) ->\n {ok, #state{config=Config}}.\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% Handling call messages\n%%\n%% @spec handle_call(Request, From, State) ->\n%% {reply, Reply, State} |\n%% {reply, Reply, State, Timeout} |\n%% {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, Reply, State} |\n%% {stop, Reason, State}\n%% @end\n%%--------------------------------------------------------------------\nhandle_call({apply, Module, Function, Args}, From, State) ->\n _ = rpc_apply(From, Module, Function, Args, State#state.config),\n {noreply, State};\n\nhandle_call(_Request, _From, State) ->\n Reply = ok,\n {reply, Reply, State}.\n\nrpc_apply(From, Module, Function, Args, Config) ->\n spawn(\n fun() ->\n Reply =\n try\n apply(Module, Function, Args ++ [Config])\n catch\n E:R ->\n {error, {Module, Function, length(Args) + 1, {E, R}}}\n end,\n case From of\n undefined -> ok;\n _ ->\n gen_server:reply(From, Reply)\n end\n end).\n\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% Handling cast messages\n%%\n%% @spec handle_cast(Msg, State) -> {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, State}\n%% @end\n%%--------------------------------------------------------------------\nhandle_cast({apply, Module, Function, Args}, State) ->\n _ = rpc_apply(undefined, Module, Function, Args, State#state.config),\n {noreply, State};\nhandle_cast(_Msg, State) ->\n {noreply, State}.\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% Handling all non call\/cast messages\n%%\n%% @spec handle_info(Info, State) -> {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, State}\n%% @end\n%%--------------------------------------------------------------------\nhandle_info(_Info, State) ->\n {noreply, State}.\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% This function is called by a gen_server when it is about to\n%% terminate. It should be the opposite of Module:init\/1 and do any\n%% necessary cleaning up. When it returns, the gen_server terminates\n%% with Reason. The return value is ignored.\n%%\n%% @spec terminate(Reason, State) -> void()\n%% @end\n%%--------------------------------------------------------------------\nterminate(_Reason, _State) ->\n ok.\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% Convert process state when code is changed\n%%\n%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}\n%% @end\n%%--------------------------------------------------------------------\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\n%%%===================================================================\n%%% Internal functions\n%%%===================================================================\n\n\n\n\n","avg_line_length":31.765625,"max_line_length":93,"alphanum_fraction":0.4381046073} +{"size":2623,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(oauth2_tests).\n\n-include_lib(\"eunit\/include\/eunit.hrl\").\n-include_lib(\"zotonic_core\/include\/zotonic.hrl\").\n\noauth2_request_test() ->\n ok = z_sites_manager:await_startup(zotonic_site_testsandbox),\n Context = z_context:new(zotonic_site_testsandbox),\n SudoContext = z_acl:sudo(Context),\n ok = z_module_manager:activate_await(mod_oauth2, Context),\n ok = z_module_manager:upgrade_await(Context),\n\n % Make a new OAuth2 token with full access to the admin (user 1) account\n TPs = [\n {is_read_only, false},\n {is_full_access, true}\n ],\n\n % Should have permission to make a token for user 1\n {error, eacces} = m_oauth2:insert(1, TPs, Context),\n\n {ok, TId_1} = m_oauth2:insert(1, TPs, SudoContext),\n {ok, Token_1} = m_oauth2:encode_bearer_token(TId_1, 60, SudoContext),\n {ok, {TId_1, _TSecret_1}} = m_oauth2:decode_bearer_token(Token_1, Context),\n\n {ok, Token_1a} = m_oauth2:encode_bearer_token(TId_1, undefined, SudoContext),\n {ok, {TId_1, _TSecret_1a}} = m_oauth2:decode_bearer_token(Token_1a, Context),\n\n % Tokens can expire\n {ok, Token_1t} = m_oauth2:encode_bearer_token(TId_1, -1, SudoContext),\n {error, expired} = m_oauth2:decode_bearer_token(Token_1t, Context),\n\n Url = z_context:abs_url( z_dispatcher:url_for(api, [ {star, <<\"model\/acl\/get\/user\">> } ], Context), Context),\n\n % No token\n {ok, {_, _, _, NoT}} = z_url_fetch:fetch(Url, []),\n #{ <<\"result\">> := undefined, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(NoT),\n\n % Valid tokens\n {ok, {_, _, _, T1}} = z_url_fetch:fetch(Url, [ {authorization, <<\"Bearer \", Token_1\/binary>>} ]),\n #{ <<\"result\">> := 1, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(T1),\n\n {ok, {_, _, _, T1a}} = z_url_fetch:fetch(Url, [ {authorization, <<\"Bearer \", Token_1a\/binary>>} ]),\n #{ <<\"result\">> := 1, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(T1a),\n\n % Expired token\n {ok, {_, _, _, T1t}} = z_url_fetch:fetch(Url, [ {authorization, <<\"Bearer \", Token_1t\/binary>>} ]),\n #{ <<\"result\">> := undefined, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(T1t),\n\n % Illegal token\n {ok, {_, _, _, Tx}} = z_url_fetch:fetch(Url, [ {authorization, <<\"Bearer \", Token_1\/binary, \"xxx\">>} ]),\n #{ <<\"result\">> := undefined, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(Tx),\n\n % Uknown token\n {ok, {_, _, _, Tu}} = z_url_fetch:fetch(Url, [ {authorization, <<\"Bearer xxx\">>} ]),\n #{ <<\"result\">> := undefined, <<\"status\">> := <<\"ok\">> } = jsxrecord:decode(Tu),\n\n % TODO:\n % - test limitations on groups\n % - test read only flag\n % - test IP restrictions\n\n ok.\n\n","avg_line_length":40.3538461538,"max_line_length":113,"alphanum_fraction":0.6145634769} +{"size":3605,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% @author Andreas Stenius \n%% @copyright 2012 Andreas Stenius\n%% @doc 'sort' filter, sort a resource id list on property.\n\n%% Copyright 2012 Andreas Stenius\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n-module(filter_sort).\n-export([sort\/2, sort\/3]).\n\n-include_lib(\"zotonic.hrl\").\n\n%% no arg, sort on id, default order\nsort(undefined, _Context) ->\n undefined;\nsort(Input, _Context) when is_list(Input) ->\n lists:sort(Input);\nsort(Input, Context) when is_record(Input, rsc_list) ->\n sort(Input, [id], Context).\n\nsort(undefined, _Arg, _Context) ->\n undefined;\nsort(Input, Arg, _Context) when is_list(Input) ->\n case is_opt(Arg) of\n false -> Input;\n ascending -> lists:sort(Input);\n descending -> lists:reverse(lists:sort(Input))\n end;\nsort(#rsc_list{ list=Rscs }, Args, Context) when is_list(Args) ->\n Args1 = case z_string:is_string(Args) of\n true -> [Args];\n false -> Args\n end,\n sort_list({0, Rscs}, {ascending, Args1}, Context);\nsort(Input, Arg, Context) when is_record(Input, rsc_list) ->\n sort(Input, [Arg], Context).\n\n\n%% Internal functions\n\nsort_list({_, Result}, {_, []}, _Context) ->\n #rsc_list{ list=lists:flatten(Result) };\nsort_list(Input, {DefaultOpt, Args}, Context) ->\n {Opt, [Prop|Rest]} = split_opt(Args, DefaultOpt),\n Output = do_sort(Input, Opt, Prop, Context),\n sort_list(Output, {Opt, Rest}, Context).\n\ndo_sort({0, Rscs}, Opt, Prop, Context) ->\n Tagged = [{get_prop(Id, Prop, Context), Id} || Id <- Rscs],\n Sorted = lists:keysort(1, Tagged),\n Fold = case Opt of\n ascending -> fun lists:foldr\/3;\n descending -> fun lists:foldl\/3\n end,\n Grouped = Fold(\n fun({V, _}=This, [[{V, _}|_]=Group|Tail]) ->\n [[This|Group]|Tail];\n (This, Acc) ->\n [[This]|Acc]\n end,\n [],\n Sorted),\n {1, [[Id || {_, Id} <- Group] || Group <- Grouped]};\ndo_sort({Lvl, RscGrps}, Opt, Prop, Context) ->\n Sorted = [do_sort({Lvl - 1, Group}, Opt, Prop, Context) || Group <- RscGrps],\n {Lvl + 1, [Group || {_, Group} <- Sorted]}.\n\nget_prop(Id, Prop, Context) ->\n case m_rsc:p(Id, Prop, Context) of\n {trans, _} = T -> z_trans:lookup(T, Context);\n Value -> Value\n end.\n\nsplit_opt([CheckOpt|Tail]=Args, Default) ->\n case is_opt(CheckOpt) of\n false ->\n {Default, Args};\n Opt ->\n {Opt, Tail}\n end.\n\nis_opt(Opt) ->\n %% work-around for `lists:member` not being legal to use in if guards... bah !\n %% and I don't want to use nested case statments, so this was the most concise\n %% I could come up with... :p\n proplists:get_value(\n true,\n [{lists:member(Opt, ascending_keywords()), ascending},\n {lists:member(Opt, descending_keywords()), descending}],\n false).\n\nascending_keywords() ->\n [ascending, asc, '+', \"+\", \"ascending\", \"asc\"].\n\ndescending_keywords() ->\n [descending, desc, '-', \"-\", \"descending\", \"desc\"].\n","avg_line_length":33.3796296296,"max_line_length":82,"alphanum_fraction":0.6} +{"size":8675,"ext":"erl","lang":"Erlang","max_stars_count":10.0,"content":"% Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n% use this file except in compliance with the License. You may obtain a copy of\n% the License at\n%\n% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n% License for the specific language governing permissions and limitations under\n% the License.\n\n-module(mem3_util).\n\n-export([hash\/1, name_shard\/2, create_partition_map\/5, build_shards\/2,\n n_val\/2, to_atom\/1, to_integer\/1, write_db_doc\/1, delete_db_doc\/1,\n shard_info\/1, ensure_exists\/1, open_db_doc\/1]).\n-export([is_deleted\/1, rotate_list\/2]).\n\n%% do not use outside mem3.\n-export([build_ordered_shards\/2, downcast\/1]).\n\n-export([create_partition_map\/4, name_shard\/1]).\n-deprecated({create_partition_map, 4, eventually}).\n-deprecated({name_shard, 1, eventually}).\n\n-define(RINGTOP, 2 bsl 31). % CRC32 space\n\n-include_lib(\"mem3\/include\/mem3.hrl\").\n-include_lib(\"couch\/include\/couch_db.hrl\").\n\nhash(Item) when is_binary(Item) ->\n erlang:crc32(Item);\nhash(Item) ->\n erlang:crc32(term_to_binary(Item)).\n\nname_shard(Shard) ->\n name_shard(Shard, \"\").\n\nname_shard(#shard{dbname = DbName, range=Range} = Shard, Suffix) ->\n Name = make_name(DbName, Range, Suffix),\n Shard#shard{name = ?l2b(Name)};\n\nname_shard(#ordered_shard{dbname = DbName, range=Range} = Shard, Suffix) ->\n Name = make_name(DbName, Range, Suffix),\n Shard#ordered_shard{name = ?l2b(Name)}.\n\nmake_name(DbName, [B,E], Suffix) ->\n [\"shards\/\", couch_util:to_hex(<>), \"-\",\n couch_util:to_hex(<>), \"\/\", DbName, Suffix].\n\ncreate_partition_map(DbName, N, Q, Nodes) ->\n create_partition_map(DbName, N, Q, Nodes, \"\").\n\ncreate_partition_map(DbName, N, Q, Nodes, Suffix) ->\n UniqueShards = make_key_ranges((?RINGTOP) div Q, 0, []),\n Shards0 = lists:flatten([lists:duplicate(N, S) || S <- UniqueShards]),\n Shards1 = attach_nodes(Shards0, [], Nodes, []),\n [name_shard(S#shard{dbname=DbName}, Suffix) || S <- Shards1].\n\nmake_key_ranges(_, CurrentPos, Acc) when CurrentPos >= ?RINGTOP ->\n Acc;\nmake_key_ranges(Increment, Start, Acc) ->\n case Start + 2*Increment of\n X when X > ?RINGTOP ->\n End = ?RINGTOP - 1;\n _ ->\n End = Start + Increment - 1\n end,\n make_key_ranges(Increment, End+1, [#shard{range=[Start, End]} | Acc]).\n\nattach_nodes([], Acc, _, _) ->\n lists:reverse(Acc);\nattach_nodes(Shards, Acc, [], UsedNodes) ->\n attach_nodes(Shards, Acc, lists:reverse(UsedNodes), []);\nattach_nodes([S | Rest], Acc, [Node | Nodes], UsedNodes) ->\n attach_nodes(Rest, [S#shard{node=Node} | Acc], Nodes, [Node | UsedNodes]).\n\nopen_db_doc(DocId) ->\n DbName = ?l2b(config:get(\"mem3\", \"shards_db\", \"_dbs\")),\n {ok, Db} = couch_db:open(DbName, [?ADMIN_CTX]),\n try couch_db:open_doc(Db, DocId, [ejson_body]) after couch_db:close(Db) end.\n\nwrite_db_doc(Doc) ->\n DbName = ?l2b(config:get(\"mem3\", \"shards_db\", \"_dbs\")),\n write_db_doc(DbName, Doc, true).\n\nwrite_db_doc(DbName, #doc{id=Id, body=Body} = Doc, ShouldMutate) ->\n {ok, Db} = couch_db:open(DbName, [?ADMIN_CTX]),\n try couch_db:open_doc(Db, Id, [ejson_body]) of\n {ok, #doc{body = Body}} ->\n % the doc is already in the desired state, we're done here\n ok;\n {not_found, _} when ShouldMutate ->\n try couch_db:update_doc(Db, Doc, []) of\n {ok, _} ->\n ok\n catch conflict ->\n % check to see if this was a replication race or a different edit\n write_db_doc(DbName, Doc, false)\n end;\n _ ->\n % the doc already exists in a different state\n conflict\n after\n couch_db:close(Db)\n end.\n\ndelete_db_doc(DocId) ->\n gen_server:cast(mem3_shards, {cache_remove, DocId}),\n DbName = ?l2b(config:get(\"mem3\", \"shards_db\", \"_dbs\")),\n delete_db_doc(DbName, DocId, true).\n\ndelete_db_doc(DbName, DocId, ShouldMutate) ->\n {ok, Db} = couch_db:open(DbName, [?ADMIN_CTX]),\n {ok, Revs} = couch_db:open_doc_revs(Db, DocId, all, []),\n try [Doc#doc{deleted=true} || {ok, #doc{deleted=false}=Doc} <- Revs] of\n [] ->\n not_found;\n Docs when ShouldMutate ->\n try couch_db:update_docs(Db, Docs, []) of\n {ok, _} ->\n ok\n catch conflict ->\n % check to see if this was a replication race or if leafs survived\n delete_db_doc(DbName, DocId, false)\n end;\n _ ->\n % we have live leafs that we aren't allowed to delete. let's bail\n conflict\n after\n couch_db:close(Db)\n end.\n\n%% Always returns original #shard records.\n-spec build_shards(binary(), list()) -> [#shard{}].\nbuild_shards(DbName, DocProps) ->\n build_shards_by_node(DbName, DocProps).\n\n%% Will return #ordered_shard records if by_node and by_range\n%% are symmetrical, #shard records otherwise.\n-spec build_ordered_shards(binary(), list()) ->\n [#shard{}] | [#ordered_shard{}].\nbuild_ordered_shards(DbName, DocProps) ->\n ByNode = build_shards_by_node(DbName, DocProps),\n ByRange = build_shards_by_range(DbName, DocProps),\n Symmetrical = lists:sort(ByNode) =:= lists:sort(downcast(ByRange)),\n case Symmetrical of\n true -> ByRange;\n false -> ByNode\n end.\n\nbuild_shards_by_node(DbName, DocProps) ->\n {ByNode} = couch_util:get_value(<<\"by_node\">>, DocProps, {[]}),\n Suffix = couch_util:get_value(<<\"shard_suffix\">>, DocProps, \"\"),\n lists:flatmap(fun({Node, Ranges}) ->\n lists:map(fun(Range) ->\n [B,E] = string:tokens(?b2l(Range), \"-\"),\n Beg = httpd_util:hexlist_to_integer(B),\n End = httpd_util:hexlist_to_integer(E),\n name_shard(#shard{\n dbname = DbName,\n node = to_atom(Node),\n range = [Beg, End]\n }, Suffix)\n end, Ranges)\n end, ByNode).\n\nbuild_shards_by_range(DbName, DocProps) ->\n {ByRange} = couch_util:get_value(<<\"by_range\">>, DocProps, {[]}),\n Suffix = couch_util:get_value(<<\"shard_suffix\">>, DocProps, \"\"),\n lists:flatmap(fun({Range, Nodes}) ->\n lists:map(fun({Node, Order}) ->\n [B,E] = string:tokens(?b2l(Range), \"-\"),\n Beg = httpd_util:hexlist_to_integer(B),\n End = httpd_util:hexlist_to_integer(E),\n name_shard(#ordered_shard{\n dbname = DbName,\n node = to_atom(Node),\n range = [Beg, End],\n order = Order\n }, Suffix)\n end, lists:zip(Nodes, lists:seq(1, length(Nodes))))\n end, ByRange).\n\nto_atom(Node) when is_binary(Node) ->\n list_to_atom(binary_to_list(Node));\nto_atom(Node) when is_atom(Node) ->\n Node.\n\nto_integer(N) when is_integer(N) ->\n N;\nto_integer(N) when is_binary(N) ->\n list_to_integer(binary_to_list(N));\nto_integer(N) when is_list(N) ->\n list_to_integer(N).\n\nn_val(undefined, NodeCount) ->\n n_val(config:get(\"cluster\", \"n\", \"3\"), NodeCount);\nn_val(N, NodeCount) when is_list(N) ->\n n_val(list_to_integer(N), NodeCount);\nn_val(N, NodeCount) when is_integer(NodeCount), N > NodeCount ->\n couch_log:error(\"Request to create N=~p DB but only ~p node(s)\", [N, NodeCount]),\n NodeCount;\nn_val(N, _) when N < 1 ->\n 1;\nn_val(N, _) ->\n N.\n\nshard_info(DbName) ->\n [{n, mem3:n(DbName)},\n {q, length(mem3:shards(DbName)) div mem3:n(DbName)}].\n\nensure_exists(DbName) when is_list(DbName) ->\n ensure_exists(list_to_binary(DbName));\nensure_exists(DbName) ->\n Options = [nologifmissing, sys_db, {create_if_missing, true}, ?ADMIN_CTX],\n case couch_db:open(DbName, Options) of\n {ok, Db} ->\n {ok, Db};\n file_exists ->\n couch_db:open(DbName, [sys_db, ?ADMIN_CTX])\n end.\n\n\nis_deleted(Change) ->\n case couch_util:get_value(<<\"deleted\">>, Change) of\n undefined ->\n % keep backwards compatibility for a while\n couch_util:get_value(deleted, Change, false);\n Else ->\n Else\n end.\n\nrotate_list(_Key, []) ->\n [];\nrotate_list(Key, List) when not is_binary(Key) ->\n rotate_list(term_to_binary(Key), List);\nrotate_list(Key, List) ->\n {H, T} = lists:split(erlang:crc32(Key) rem length(List), List),\n T ++ H.\n\ndowncast(#shard{}=S) ->\n S;\ndowncast(#ordered_shard{}=S) ->\n #shard{\n name = S#ordered_shard.name,\n node = S#ordered_shard.node,\n dbname = S#ordered_shard.dbname,\n range = S#ordered_shard.range,\n ref = S#ordered_shard.ref\n };\ndowncast(Shards) when is_list(Shards) ->\n [downcast(Shard) || Shard <- Shards].\n","avg_line_length":34.0196078431,"max_line_length":85,"alphanum_fraction":0.6320461095} +{"size":974,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%--------------------------------------------------------------------\n%% Copyright (c) 2013-2018 EMQ Enterprise, Inc. (http:\/\/emqtt.io)\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%--------------------------------------------------------------------\n\n-module(emq_realtime_online_cli).\n\n-include_lib(\"emqttd\/include\/emqttd_cli.hrl\").\n\n-export([cmd\/1]).\n\ncmd([\"arg1\", \"arg2\"]) ->\n ?PRINT_MSG(\"ok\");\n\ncmd(_) ->\n ?USAGE([{\"cmd arg1 arg2\", \"cmd demo\"}]).\n\n","avg_line_length":33.5862068966,"max_line_length":75,"alphanum_fraction":0.6016427105} +{"size":5393,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% Licensed to the Apache Software Foundation (ASF) under one\n%% or more contributor license agreements. See the NOTICE file\n%% distributed with this work for additional information\n%% regarding copyright ownership. The ASF licenses this file\n%% to you under the Apache License, Version 2.0 (the\n%% \"License\"); you may not use this file except in compliance\n%% with the License. You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing,\n%% software distributed under the License is distributed on an\n%% \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n%% KIND, either express or implied. See the License for the\n%% specific language governing permissions and limitations\n%% under the License.\n%%\n\n-module(test_client).\n\n-export([start\/0, start\/1]).\n\n-include(\"thrift_test_thriftTest_types.hrl\").\n\n-record(options, {port = 9090,\n client_opts = []}).\n\nparse_args(Args) -> parse_args(Args, #options{}).\nparse_args([], Opts) -> Opts;\nparse_args([Head | Rest], Opts) ->\n NewOpts =\n case catch list_to_integer(Head) of\n Port when is_integer(Port) ->\n Opts#options{port = Port};\n _Else ->\n case Head of\n \"framed\" ->\n Opts#options{client_opts = [{framed, true} | Opts#options.client_opts]};\n \"\" ->\n Opts;\n _Else ->\n erlang:error({bad_arg, Head})\n end\n end,\n parse_args(Rest, NewOpts).\n\n\nstart() -> start([]).\nstart(Args) ->\n #options{port = Port, client_opts = ClientOpts} = parse_args(Args),\n {ok, Client0} = thrift_client_util:new(\n \"127.0.0.1\", Port, thriftTest_thrift, ClientOpts),\n\n DemoXtruct = #xtruct{\n string_thing = <<\"Zero\">>,\n byte_thing = 1,\n i32_thing = 9128361,\n i64_thing = 9223372036854775807},\n\n DemoNest = #xtruct2{\n byte_thing = 7,\n struct_thing = DemoXtruct,\n % Note that we don't set i32_thing, it will come back as undefined\n % from the Python server, but 0 from the C++ server, since it is not\n % optional\n i32_thing = 2},\n\n % Is it safe to match these things?\n DemoDict = dict:from_list([ {Key, Key-10} || Key <- lists:seq(0,10) ]),\n DemoSet = sets:from_list([ Key || Key <- lists:seq(-3,3) ]),\n\n %DemoInsane = #insanity{\n % userMap = dict:from_list([{?thriftTest_FIVE, 5000}]),\n % xtructs = [#xtruct{ string_thing = <<\"Truck\">>, byte_thing = 8, i32_thing = 8, i64_thing = 8}]},\n\n {Client01, {ok, ok}} = thrift_client:call(Client0, testVoid, []),\n\n {Client02, {ok, <<\"Test\">>}} = thrift_client:call(Client01, testString, [\"Test\"]),\n {Client03, {ok, <<\"Test\">>}} = thrift_client:call(Client02, testString, [<<\"Test\">>]),\n {Client04, {ok, 63}} = thrift_client:call(Client03, testByte, [63]),\n {Client05, {ok, -1}} = thrift_client:call(Client04, testI32, [-1]),\n {Client06, {ok, 0}} = thrift_client:call(Client05, testI32, [0]),\n {Client07, {ok, -34359738368}} = thrift_client:call(Client06, testI64, [-34359738368]),\n {Client08, {ok, -5.2098523}} = thrift_client:call(Client07, testDouble, [-5.2098523]),\n {Client09, {ok, DemoXtruct}} = thrift_client:call(Client08, testStruct, [DemoXtruct]),\n {Client10, {ok, DemoNest}} = thrift_client:call(Client09, testNest, [DemoNest]),\n {Client11, {ok, DemoDict}} = thrift_client:call(Client10, testMap, [DemoDict]),\n {Client12, {ok, DemoSet}} = thrift_client:call(Client11, testSet, [DemoSet]),\n {Client13, {ok, [-1,2,3]}} = thrift_client:call(Client12, testList, [[-1,2,3]]),\n {Client14, {ok, 1}} = thrift_client:call(Client13, testEnum, [?thriftTest_Numberz_ONE]),\n {Client15, {ok, 309858235082523}} = thrift_client:call(Client14, testTypedef, [309858235082523]),\n\n % No python implementation, but works with C++ and Erlang.\n %{Client16, {ok, InsaneResult}} = thrift_client:call(Client15, testInsanity, [DemoInsane]),\n %io:format(\"~p~n\", [InsaneResult]),\n Client16 = Client15,\n\n {Client17, {ok, #xtruct{string_thing = <<\"Message\">>}}} =\n thrift_client:call(Client16, testMultiException, [\"Safe\", \"Message\"]),\n\n Client18 =\n try\n {ClientS1, Result1} = thrift_client:call(Client17, testMultiException, [\"Xception\", \"Message\"]),\n io:format(\"Unexpected return! ~p~n\", [Result1]),\n ClientS1\n catch\n throw:{ClientS2, {exception, ExnS1 = #xception{}}} ->\n #xception{errorCode = 1001, message = <<\"This is an Xception\">>} = ExnS1,\n ClientS2;\n throw:{ClientS2, {exception, _ExnS1 = #xception2{}}} ->\n io:format(\"Wrong exception type!~n\", []),\n ClientS2\n end,\n\n Client19 =\n try\n {ClientS3, Result2} = thrift_client:call(Client18, testMultiException, [\"Xception2\", \"Message\"]),\n io:format(\"Unexpected return! ~p~n\", [Result2]),\n ClientS3\n catch\n throw:{ClientS4, {exception, _ExnS2 = #xception{}}} ->\n io:format(\"Wrong exception type!~n\", []),\n ClientS4;\n throw:{ClientS4, {exception, ExnS2 = #xception2{}}} ->\n #xception2{errorCode = 2002,\n struct_thing = #xtruct{\n string_thing = <<\"This is an Xception2\">>}} = ExnS2,\n ClientS4\n end,\n\n thrift_client:close(Client19).\n","avg_line_length":40.5488721805,"max_line_length":104,"alphanum_fraction":0.6183942147} +{"size":3317,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%% @author Justin Sheehy \n%% @author Andy Gross \n%% @copyright 2007-2008 Basho Technologies\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n-module(webmachine_skel).\n-export([skelcopy\/2]).\n\n-include_lib(\"kernel\/include\/file.hrl\").\n\n%% External API\n\nskelcopy(DestDir, Name) ->\n ok = ensuredir(DestDir),\n LDst = case length(filename:dirname(DestDir)) of \n 1 -> %% handle case when dirname returns \"\/\"\n 0;\n N ->\n N + 1\n end,\n skelcopy(src(), DestDir, Name, LDst),\n Webmachine = unmunge(filename:join(filename:dirname(code:which(?MODULE)), \"..\")),\n Target = unmunge(filename:join([DestDir, Name, \"lib\", \"webmachine\"])),\n io:format(\"Symlinking ~p to ~p.~n\", [Webmachine,Target]),\n ok = file:make_symlink(Webmachine,\n Target).\n\nunmunge(Path) -> \n Comps = filename:split(Path),\n filename:join(unmunge2(Comps)).\n\nunmunge2([]) -> [];\nunmunge2([_Dir, \"..\" | Rest]) ->\n unmunge2(Rest);\nunmunge2([Dir | Rest]) ->\n [Dir | unmunge2(Rest)].\n\n%% Internal API\n\nsrc() ->\n Dir = filename:dirname(code:which(?MODULE)),\n filename:join(Dir, \"..\/priv\/skel\").\n\nskel() ->\n \"skel\".\n\nskelcopy(Src, DestDir, Name, LDst) ->\n {ok, Dest, _} = regexp:gsub(filename:basename(Src), skel(), Name),\n case file:read_file_info(Src) of\n {ok, #file_info{type=directory, mode=Mode}} ->\n Dir = DestDir ++ \"\/\" ++ Dest,\n EDst = lists:nthtail(LDst, Dir),\n ok = ensuredir(Dir),\n ok = file:write_file_info(Dir, #file_info{mode=Mode}),\n {ok, Files} = file:list_dir(Src),\n io:format(\"~s\/~n\", [EDst]),\n lists:foreach(fun (\".\" ++ _) -> ok;\n (F) ->\n skelcopy(filename:join(Src, F), \n Dir,\n Name,\n LDst)\n end,\n Files),\n ok;\n {ok, #file_info{type=regular, mode=Mode}} ->\n OutFile = filename:join(DestDir, Dest),\n {ok, B} = file:read_file(Src),\n {ok, S, _} = regexp:gsub(binary_to_list(B), skel(), Name),\n ok = file:write_file(OutFile, list_to_binary(S)),\n ok = file:write_file_info(OutFile, #file_info{mode=Mode}),\n io:format(\" ~s~n\", [filename:basename(Src)]),\n ok;\n {ok, _} ->\n io:format(\"ignored source file: ~p~n\", [Src]),\n ok\n end.\n\nensuredir(Dir) ->\n case file:make_dir(Dir) of\n ok ->\n ok;\n {error, eexist} ->\n ok;\n E ->\n E\n end.\n","avg_line_length":33.5050505051,"max_line_length":85,"alphanum_fraction":0.5278866446} +{"size":7381,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%------------------------------------------------------------\n%%\n%% Implementation stub file\n%% \n%% Target: CosNotifyFilter_FilterAdmin\n%% Source: \/net\/isildur\/ldisk\/daily_build\/r15b03_prebuild_opu_o.2012-12-06_18\/otp_src_R15B03\/lib\/cosNotification\/src\/CosNotifyFilter.idl\n%% IC vsn: 4.2.31\n%% \n%% This file is automatically generated. DO NOT EDIT IT.\n%%\n%%------------------------------------------------------------\n\n-module('CosNotifyFilter_FilterAdmin').\n-ic_compiled(\"4_2_31\").\n\n\n%% Interface functions\n-export([add_filter\/2, add_filter\/3, remove_filter\/2]).\n-export([remove_filter\/3, get_filter\/2, get_filter\/3]).\n-export([get_all_filters\/1, get_all_filters\/2, remove_all_filters\/1]).\n-export([remove_all_filters\/2]).\n\n%% Type identification function\n-export([typeID\/0]).\n\n%% Used to start server\n-export([oe_create\/0, oe_create_link\/0, oe_create\/1]).\n-export([oe_create_link\/1, oe_create\/2, oe_create_link\/2]).\n\n%% TypeCode Functions and inheritance\n-export([oe_tc\/1, oe_is_a\/1, oe_get_interface\/0]).\n\n%% gen server export stuff\n-behaviour(gen_server).\n-export([init\/1, terminate\/2, handle_call\/3]).\n-export([handle_cast\/2, handle_info\/2, code_change\/3]).\n\n-include_lib(\"orber\/include\/corba.hrl\").\n\n\n%%------------------------------------------------------------\n%%\n%% Object interface functions.\n%%\n%%------------------------------------------------------------\n\n\n\n%%%% Operation: add_filter\n%% \n%% Returns: RetVal\n%%\nadd_filter(OE_THIS, New_filter) ->\n corba:call(OE_THIS, add_filter, [New_filter], ?MODULE).\n\nadd_filter(OE_THIS, OE_Options, New_filter) ->\n corba:call(OE_THIS, add_filter, [New_filter], ?MODULE, OE_Options).\n\n%%%% Operation: remove_filter\n%% \n%% Returns: RetVal\n%% Raises: CosNotifyFilter::FilterNotFound\n%%\nremove_filter(OE_THIS, Filter) ->\n corba:call(OE_THIS, remove_filter, [Filter], ?MODULE).\n\nremove_filter(OE_THIS, OE_Options, Filter) ->\n corba:call(OE_THIS, remove_filter, [Filter], ?MODULE, OE_Options).\n\n%%%% Operation: get_filter\n%% \n%% Returns: RetVal\n%% Raises: CosNotifyFilter::FilterNotFound\n%%\nget_filter(OE_THIS, Filter) ->\n corba:call(OE_THIS, get_filter, [Filter], ?MODULE).\n\nget_filter(OE_THIS, OE_Options, Filter) ->\n corba:call(OE_THIS, get_filter, [Filter], ?MODULE, OE_Options).\n\n%%%% Operation: get_all_filters\n%% \n%% Returns: RetVal\n%%\nget_all_filters(OE_THIS) ->\n corba:call(OE_THIS, get_all_filters, [], ?MODULE).\n\nget_all_filters(OE_THIS, OE_Options) ->\n corba:call(OE_THIS, get_all_filters, [], ?MODULE, OE_Options).\n\n%%%% Operation: remove_all_filters\n%% \n%% Returns: RetVal\n%%\nremove_all_filters(OE_THIS) ->\n corba:call(OE_THIS, remove_all_filters, [], ?MODULE).\n\nremove_all_filters(OE_THIS, OE_Options) ->\n corba:call(OE_THIS, remove_all_filters, [], ?MODULE, OE_Options).\n\n%%------------------------------------------------------------\n%%\n%% Inherited Interfaces\n%%\n%%------------------------------------------------------------\noe_is_a(\"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\") -> true;\noe_is_a(_) -> false.\n\n%%------------------------------------------------------------\n%%\n%% Interface TypeCode\n%%\n%%------------------------------------------------------------\noe_tc(add_filter) -> \n\t{tk_long,[{tk_objref,\"IDL:omg.org\/CosNotifyFilter\/Filter:1.0\",\n \"Filter\"}],\n []};\noe_tc(remove_filter) -> \n\t{tk_void,[tk_long],[]};\noe_tc(get_filter) -> \n\t{{tk_objref,\"IDL:omg.org\/CosNotifyFilter\/Filter:1.0\",\"Filter\"},\n [tk_long],\n []};\noe_tc(get_all_filters) -> \n\t{{tk_sequence,tk_long,0},[],[]};\noe_tc(remove_all_filters) -> \n\t{tk_void,[],[]};\noe_tc(_) -> undefined.\n\noe_get_interface() -> \n\t[{\"remove_all_filters\", oe_tc(remove_all_filters)},\n\t{\"get_all_filters\", oe_tc(get_all_filters)},\n\t{\"get_filter\", oe_tc(get_filter)},\n\t{\"remove_filter\", oe_tc(remove_filter)},\n\t{\"add_filter\", oe_tc(add_filter)}].\n\n\n\n\n%%------------------------------------------------------------\n%%\n%% Object server implementation.\n%%\n%%------------------------------------------------------------\n\n\n%%------------------------------------------------------------\n%%\n%% Function for fetching the interface type ID.\n%%\n%%------------------------------------------------------------\n\ntypeID() ->\n \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\".\n\n\n%%------------------------------------------------------------\n%%\n%% Object creation functions.\n%%\n%%------------------------------------------------------------\n\noe_create() ->\n corba:create(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\").\n\noe_create_link() ->\n corba:create_link(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\").\n\noe_create(Env) ->\n corba:create(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\", Env).\n\noe_create_link(Env) ->\n corba:create_link(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\", Env).\n\noe_create(Env, RegName) ->\n corba:create(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\", Env, RegName).\n\noe_create_link(Env, RegName) ->\n corba:create_link(?MODULE, \"IDL:omg.org\/CosNotifyFilter\/FilterAdmin:1.0\", Env, RegName).\n\n%%------------------------------------------------------------\n%%\n%% Init & terminate functions.\n%%\n%%------------------------------------------------------------\n\ninit(Env) ->\n%% Call to implementation init\n corba:handle_init('CosNotifyFilter_FilterAdmin_impl', Env).\n\nterminate(Reason, State) ->\n corba:handle_terminate('CosNotifyFilter_FilterAdmin_impl', Reason, State).\n\n\n%%%% Operation: add_filter\n%% \n%% Returns: RetVal\n%%\nhandle_call({_, OE_Context, add_filter, [New_filter]}, _, OE_State) ->\n corba:handle_call('CosNotifyFilter_FilterAdmin_impl', add_filter, [New_filter], OE_State, OE_Context, false, false);\n\n%%%% Operation: remove_filter\n%% \n%% Returns: RetVal\n%% Raises: CosNotifyFilter::FilterNotFound\n%%\nhandle_call({_, OE_Context, remove_filter, [Filter]}, _, OE_State) ->\n corba:handle_call('CosNotifyFilter_FilterAdmin_impl', remove_filter, [Filter], OE_State, OE_Context, false, false);\n\n%%%% Operation: get_filter\n%% \n%% Returns: RetVal\n%% Raises: CosNotifyFilter::FilterNotFound\n%%\nhandle_call({_, OE_Context, get_filter, [Filter]}, _, OE_State) ->\n corba:handle_call('CosNotifyFilter_FilterAdmin_impl', get_filter, [Filter], OE_State, OE_Context, false, false);\n\n%%%% Operation: get_all_filters\n%% \n%% Returns: RetVal\n%%\nhandle_call({_, OE_Context, get_all_filters, []}, _, OE_State) ->\n corba:handle_call('CosNotifyFilter_FilterAdmin_impl', get_all_filters, [], OE_State, OE_Context, false, false);\n\n%%%% Operation: remove_all_filters\n%% \n%% Returns: RetVal\n%%\nhandle_call({_, OE_Context, remove_all_filters, []}, _, OE_State) ->\n corba:handle_call('CosNotifyFilter_FilterAdmin_impl', remove_all_filters, [], OE_State, OE_Context, false, false);\n\n\n\n%%%% Standard gen_server call handle\n%%\nhandle_call(stop, _, State) ->\n {stop, normal, ok, State};\n\nhandle_call(_, _, State) ->\n {reply, catch corba:raise(#'BAD_OPERATION'{minor=1163001857, completion_status='COMPLETED_NO'}), State}.\n\n\n%%%% Standard gen_server cast handle\n%%\nhandle_cast(stop, State) ->\n {stop, normal, State};\n\nhandle_cast(_, State) ->\n {noreply, State}.\n\n\n%%%% Standard gen_server handles\n%%\nhandle_info(_, State) ->\n {noreply, State}.\n\n\ncode_change(OldVsn, State, Extra) ->\n corba:handle_code_change('CosNotifyFilter_FilterAdmin_impl', OldVsn, State, Extra).\n\n","avg_line_length":28.2796934866,"max_line_length":136,"alphanum_fraction":0.608860588} +{"size":33750,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% ==========================================================================================================\n%% Syn - A global Process Registry and Process Group manager.\n%%\n%% The MIT License (MIT)\n%%\n%% Copyright (c) 2015-2019 Roberto Ostinelli and Neato Robotics, Inc.\n%%\n%% Permission is hereby granted, free of charge, to any person obtaining a copy\n%% of this software and associated documentation files (the \"Software\"), to deal\n%% in the Software without restriction, including without limitation the rights\n%% to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n%% copies of the Software, and to permit persons to whom the Software is\n%% furnished to do so, subject to the following conditions:\n%%\n%% The above copyright notice and this permission notice shall be included in\n%% all copies or substantial portions of the Software.\n%%\n%% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n%% THE SOFTWARE.\n%% ==========================================================================================================\n-module(syn_registry).\n-behaviour(gen_server).\n\n%% API\n-export([start_link\/0]).\n-export([register\/2, register\/3]).\n-export([unregister_and_register\/2, unregister_and_register\/3]).\n-export([unregister\/1]).\n-export([whereis\/1, whereis\/2]).\n-export([count\/0, count\/1]).\n\n%% sync API\n-export([sync_register\/6, sync_unregister\/3]).\n-export([sync_demonitor_and_kill_on_node\/5]).\n-export([sync_get_local_registry_tuples\/1]).\n-export([force_cluster_sync\/0]).\n-export([add_to_local_table\/5, remove_from_local_table\/2]).\n-export([find_monitor_for_pid\/1]).\n\n%% internal\n-export([multicast_loop\/0]).\n\n%% gen_server callbacks\n-export([init\/1, handle_call\/3, handle_cast\/2, handle_info\/2, terminate\/2, code_change\/3]).\n\n%% records\n-record(state, {\n custom_event_handler :: undefined | module(),\n anti_entropy_interval_ms :: undefined | non_neg_integer(),\n anti_entropy_interval_max_deviation_ms :: undefined | non_neg_integer(),\n multicast_pid :: undefined | pid()\n}).\n\n%% includes\n-include(\"syn.hrl\").\n\n%% ===================================================================\n%% API\n%% ===================================================================\n-spec start_link() -> {ok, pid()} | {error, any()}.\nstart_link() ->\n Options = [],\n gen_server:start_link({local, ?MODULE}, ?MODULE, [], Options).\n\n-spec register(Name :: any(), Pid :: pid()) -> ok | {error, Reason :: any()}.\nregister(Name, Pid) ->\n register(Name, Pid, undefined).\n\n-spec register(Name :: any(), Pid :: pid(), Meta :: any()) -> ok | {error, Reason :: any()}.\nregister(Name, Pid, Meta) when is_pid(Pid) ->\n Node = node(Pid),\n gen_server:call({?MODULE, Node}, {register_on_node, Name, Pid, Meta, false}).\n\n-spec unregister_and_register(Name :: any(), Pid :: pid()) -> ok | {error, Reason :: any()}.\nunregister_and_register(Name, Pid) ->\n unregister_and_register(Name, Pid, undefined).\n\n-spec unregister_and_register(Name :: any(), Pid :: pid(), Meta :: any()) -> ok | {error, Reason :: any()}.\nunregister_and_register(Name, Pid, Meta) when is_pid(Pid) ->\n Node = node(Pid),\n gen_server:call({?MODULE, Node}, {register_on_node, Name, Pid, Meta, true}).\n\n-spec unregister(Name :: any()) -> ok | {error, Reason :: any()}.\nunregister(Name) ->\n % get process' node\n case find_registry_tuple_by_name(Name) of\n undefined ->\n {error, undefined};\n {Name, Pid, _, _} ->\n Node = node(Pid),\n gen_server:call({?MODULE, Node}, {unregister_on_node, Name})\n end.\n\n-spec whereis(Name :: any()) -> pid() | undefined.\nwhereis(Name) ->\n case find_registry_tuple_by_name(Name) of\n undefined -> undefined;\n {Name, Pid, _, _} -> Pid\n end.\n\n-spec whereis(Name :: any(), with_meta) -> {pid(), Meta :: any()} | undefined.\nwhereis(Name, with_meta) ->\n case find_registry_tuple_by_name(Name) of\n undefined -> undefined;\n {Name, Pid, Meta, _} -> {Pid, Meta}\n end.\n\n-spec count() -> non_neg_integer().\ncount() ->\n ets:info(syn_registry_by_name, size).\n\n-spec count(Node :: node()) -> non_neg_integer().\ncount(Node) ->\n ets:select_count(syn_registry_by_name, [{\n {{'_', '_'}, '_', '_', '_', Node},\n [],\n [true]\n }]).\n\n-spec sync_register(\n RemoteNode :: node(),\n Name :: any(),\n RemotePid :: pid(),\n RemoteMeta :: any(),\n RemoteTime :: integer(),\n Force :: boolean()\n) ->\n ok.\nsync_register(RemoteNode, Name, RemotePid, RemoteMeta, RemoteTime, Force) ->\n gen_server:cast({?MODULE, RemoteNode}, {sync_register, Name, RemotePid, RemoteMeta, RemoteTime, Force}).\n\n-spec sync_unregister(RemoteNode :: node(), Name :: any(), Pid :: pid()) -> ok.\nsync_unregister(RemoteNode, Name, Pid) ->\n gen_server:cast({?MODULE, RemoteNode}, {sync_unregister, Name, Pid}).\n\n-spec sync_demonitor_and_kill_on_node(\n Name :: any(),\n Pid :: pid(),\n Meta :: any(),\n MonitorRef :: reference(),\n Kill :: boolean()\n) -> ok.\nsync_demonitor_and_kill_on_node(Name, Pid, Meta, MonitorRef, Kill) ->\n RemoteNode = node(Pid),\n gen_server:cast({?MODULE, RemoteNode}, {sync_demonitor_and_kill_on_node, Name, Pid, Meta, MonitorRef, Kill}).\n\n-spec sync_get_local_registry_tuples(FromNode :: node()) -> [syn_registry_tuple()].\nsync_get_local_registry_tuples(FromNode) ->\n error_logger:info_msg(\"Syn(~p): Received request of local registry tuples from remote node ~p~n\", [node(), FromNode]),\n get_registry_tuples_for_node(node()).\n\n-spec force_cluster_sync() -> ok.\nforce_cluster_sync() ->\n lists:foreach(fun(RemoteNode) ->\n gen_server:cast({?MODULE, RemoteNode}, force_cluster_sync)\n end, [node() | nodes()]).\n\n%% ===================================================================\n%% Callbacks\n%% ===================================================================\n\n%% ----------------------------------------------------------------------------------------------------------\n%% Init\n%% ----------------------------------------------------------------------------------------------------------\n-spec init([]) ->\n {ok, #state{}} |\n {ok, #state{}, Timeout :: non_neg_integer()} |\n ignore |\n {stop, Reason :: any()}.\ninit([]) ->\n %% monitor nodes\n ok = net_kernel:monitor_nodes(true),\n %% rebuild monitors (if coming after a crash)\n rebuild_monitors(),\n %% start multicast process\n MulticastPid = spawn_link(?MODULE, multicast_loop, []),\n %% get handler\n CustomEventHandler = syn_backbone:get_event_handler_module(),\n %% get anti-entropy interval\n {AntiEntropyIntervalMs, AntiEntropyIntervalMaxDeviationMs} = syn_backbone:get_anti_entropy_settings(registry),\n %% build state\n State = #state{\n custom_event_handler = CustomEventHandler,\n anti_entropy_interval_ms = AntiEntropyIntervalMs,\n anti_entropy_interval_max_deviation_ms = AntiEntropyIntervalMaxDeviationMs,\n multicast_pid = MulticastPid\n },\n %% send message to initiate full cluster sync\n timer:send_after(0, self(), sync_from_full_cluster),\n %% start anti-entropy\n set_timer_for_anti_entropy(State),\n %% init\n {ok, State}.\n\n%% ----------------------------------------------------------------------------------------------------------\n%% Call messages\n%% ----------------------------------------------------------------------------------------------------------\n-spec handle_call(Request :: any(), From :: any(), #state{}) ->\n {reply, Reply :: any(), #state{}} |\n {reply, Reply :: any(), #state{}, Timeout :: non_neg_integer()} |\n {noreply, #state{}} |\n {noreply, #state{}, Timeout :: non_neg_integer()} |\n {stop, Reason :: any(), Reply :: any(), #state{}} |\n {stop, Reason :: any(), #state{}}.\n\nhandle_call({register_on_node, Name, Pid, Meta, Force}, _From, State) ->\n %% check if pid is alive\n case is_process_alive(Pid) of\n true ->\n %% check if name available\n case find_registry_tuple_by_name(Name) of\n undefined ->\n %% available\n {ok, Time} = register_on_node(Name, Pid, Meta),\n %% multicast\n multicast_register(Name, Pid, Meta, Time, false, State),\n %% return\n {reply, ok, State};\n\n {Name, Pid, _, _} ->\n % same pid, overwrite\n {ok, Time} = register_on_node(Name, Pid, Meta),\n %% multicast\n multicast_register(Name, Pid, Meta, Time, false, State),\n %% return\n {reply, ok, State};\n\n {Name, TablePid, _, _} ->\n %% same name, different pid\n case Force of\n true ->\n demonitor_if_local(TablePid),\n %% force register\n {ok, Time} = register_on_node(Name, Pid, Meta),\n %% multicast\n multicast_register(Name, Pid, Meta, Time, true, State),\n %% return\n {reply, ok, State};\n\n _ ->\n {reply, {error, taken}, State}\n end\n end;\n _ ->\n {reply, {error, not_alive}, State}\n end;\n\nhandle_call({unregister_on_node, Name}, _From, State) ->\n case unregister_on_node(Name) of\n {ok, RemovedPid} ->\n multicast_unregister(Name, RemovedPid, State),\n %% return\n {reply, ok, State};\n {error, Reason} ->\n %% return\n {reply, {error, Reason}, State}\n end;\n\nhandle_call(Request, From, State) ->\n error_logger:warning_msg(\"Syn(~p): Received from ~p an unknown call message: ~p~n\", [node(), Request, From]),\n {reply, undefined, State}.\n\n%% ----------------------------------------------------------------------------------------------------------\n%% Cast messages\n%% ----------------------------------------------------------------------------------------------------------\n-spec handle_cast(Msg :: any(), #state{}) ->\n {noreply, #state{}} |\n {noreply, #state{}, Timeout :: non_neg_integer()} |\n {stop, Reason :: any(), #state{}}.\n\nhandle_cast({sync_register, Name, RemotePid, RemoteMeta, RemoteTime, Force}, State) ->\n %% check for conflicts\n case find_registry_tuple_by_name(Name) of\n undefined ->\n %% no conflict\n add_to_local_table(Name, RemotePid, RemoteMeta, RemoteTime, undefined);\n\n {Name, RemotePid, _, _} ->\n %% same process, no conflict, overwrite\n add_to_local_table(Name, RemotePid, RemoteMeta, RemoteTime, undefined);\n\n {Name, TablePid, _, _} when Force =:= true ->\n demonitor_if_local(TablePid),\n %% overwrite\n add_to_local_table(Name, RemotePid, RemoteMeta, RemoteTime, undefined);\n\n {Name, TablePid, TableMeta, TableTime} when Force =:= false ->\n %% different pid, we have a conflict\n global:trans({{?MODULE, {inconsistent_name, Name}}, self()},\n fun() ->\n error_logger:warning_msg(\n \"Syn(~p): REGISTRY INCONSISTENCY (name: ~p for ~p and ~p) ----> Received from remote node ~p~n\",\n [node(), Name, {TablePid, TableMeta, TableTime}, {RemotePid, RemoteMeta, RemoteTime}, node(RemotePid)]\n ),\n\n case resolve_conflict(Name, {TablePid, TableMeta, TableTime}, {RemotePid, RemoteMeta, RemoteTime}, State) of\n {TablePid, KillOtherPid} ->\n %% keep table\n %% demonitor\n MonitorRef = rpc:call(node(RemotePid), syn_registry, find_monitor_for_pid, [RemotePid]),\n sync_demonitor_and_kill_on_node(Name, RemotePid, RemoteMeta, MonitorRef, KillOtherPid),\n %% overwrite local data to all remote nodes, except TablePid's node\n NodesExceptLocalAndTablePidNode = nodes() -- [node(TablePid)],\n lists:foreach(fun(RNode) ->\n ok = rpc:call(RNode,\n syn_registry, add_to_local_table,\n [Name, TablePid, TableMeta, TableTime, undefined]\n )\n end, NodesExceptLocalAndTablePidNode);\n\n {RemotePid, KillOtherPid} ->\n %% keep remote\n %% demonitor\n MonitorRef = rpc:call(node(TablePid), syn_registry, find_monitor_for_pid, [TablePid]),\n sync_demonitor_and_kill_on_node(Name, TablePid, TableMeta, MonitorRef, KillOtherPid),\n %% overwrite remote data to all other nodes (including local), except RemotePid's node\n NodesExceptRemoteNode = [node() | nodes()] -- [node(RemotePid)],\n lists:foreach(fun(RNode) ->\n ok = rpc:call(RNode,\n syn_registry, add_to_local_table,\n [Name, RemotePid, RemoteMeta, RemoteTime, undefined]\n )\n end, NodesExceptRemoteNode);\n\n undefined ->\n AllNodes = [node() | nodes()],\n %% both are dead, remove from all nodes\n lists:foreach(fun(RNode) ->\n ok = rpc:call(RNode, syn_registry, remove_from_local_table, [Name, RemotePid])\n end, AllNodes)\n end,\n\n error_logger:info_msg(\n \"Syn(~p): REGISTRY INCONSISTENCY (name: ~p) <---- Done on all cluster~n\",\n [node(), Name]\n )\n end\n )\n end,\n %% return\n {noreply, State};\n\nhandle_cast({sync_unregister, Name, Pid}, State) ->\n %% remove\n remove_from_local_table(Name, Pid),\n %% return\n {noreply, State};\n\nhandle_cast(force_cluster_sync, State) ->\n error_logger:info_msg(\"Syn(~p): Initiating full cluster FORCED registry sync for nodes: ~p~n\", [node(), nodes()]),\n do_sync_from_full_cluster(State),\n {noreply, State};\n\nhandle_cast({sync_demonitor_and_kill_on_node, Name, Pid, Meta, MonitorRef, Kill}, State) ->\n error_logger:info_msg(\"Syn(~p): Sync demonitoring pid ~p~n\", [node(), Pid]),\n %% demonitor\n catch erlang:demonitor(MonitorRef, [flush]),\n %% kill\n case Kill of\n true ->\n exit(Pid, {syn_resolve_kill, Name, Meta});\n\n _ ->\n ok\n end,\n {noreply, State};\n\nhandle_cast(Msg, State) ->\n error_logger:warning_msg(\"Syn(~p): Received an unknown cast message: ~p~n\", [node(), Msg]),\n {noreply, State}.\n\n%% ----------------------------------------------------------------------------------------------------------\n%% All non Call \/ Cast messages\n%% ----------------------------------------------------------------------------------------------------------\n-spec handle_info(Info :: any(), #state{}) ->\n {noreply, #state{}} |\n {noreply, #state{}, Timeout :: non_neg_integer()} |\n {stop, Reason :: any(), #state{}}.\n\nhandle_info({'DOWN', _MonitorRef, process, Pid, Reason}, State) ->\n case find_registry_tuples_by_pid(Pid) of\n [] ->\n %% handle\n handle_process_down(undefined, Pid, undefined, Reason, State);\n\n Entries ->\n lists:foreach(fun({Name, _Pid, Meta, _Time}) ->\n %% handle\n handle_process_down(Name, Pid, Meta, Reason, State),\n %% remove from table\n remove_from_local_table(Name, Pid),\n %% multicast\n multicast_unregister(Name, Pid, State)\n end, Entries)\n end,\n %% return\n {noreply, State};\n\nhandle_info({nodeup, RemoteNode}, State) ->\n error_logger:info_msg(\"Syn(~p): Node ~p has joined the cluster~n\", [node(), RemoteNode]),\n registry_automerge(RemoteNode, State),\n %% resume\n {noreply, State};\n\nhandle_info({nodedown, RemoteNode}, State) ->\n error_logger:warning_msg(\"Syn(~p): Node ~p has left the cluster, removing registry entries on local~n\", [node(), RemoteNode]),\n raw_purge_registry_entries_for_remote_node(RemoteNode),\n {noreply, State};\n\nhandle_info(sync_from_full_cluster, State) ->\n error_logger:info_msg(\"Syn(~p): Initiating full cluster registry sync for nodes: ~p~n\", [node(), nodes()]),\n do_sync_from_full_cluster(State),\n {noreply, State};\n\nhandle_info(sync_anti_entropy, State) ->\n %% sync\n RemoteNodes = nodes(),\n case length(RemoteNodes) > 0 of\n true ->\n RandomRemoteNode = lists:nth(rand:uniform(length(RemoteNodes)), RemoteNodes),\n error_logger:info_msg(\"Syn(~p): Initiating anti-entropy sync for node ~p~n\", [node(), RandomRemoteNode]),\n registry_automerge(RandomRemoteNode, State);\n\n _ ->\n ok\n end,\n %% set timer\n set_timer_for_anti_entropy(State),\n %% return\n {noreply, State};\n\nhandle_info(Info, State) ->\n error_logger:warning_msg(\"Syn(~p): Received an unknown info message: ~p~n\", [node(), Info]),\n {noreply, State}.\n\n%% ----------------------------------------------------------------------------------------------------------\n%% Terminate\n%% ----------------------------------------------------------------------------------------------------------\n-spec terminate(Reason :: any(), #state{}) -> terminated.\nterminate(Reason, #state{\n multicast_pid = MulticastPid\n}) ->\n error_logger:info_msg(\"Syn(~p): Terminating with reason: ~p~n\", [node(), Reason]),\n MulticastPid ! terminate,\n terminated.\n\n%% ----------------------------------------------------------------------------------------------------------\n%% Convert process state when code is changed.\n%% ----------------------------------------------------------------------------------------------------------\n-spec code_change(OldVsn :: any(), #state{}, Extra :: any()) -> {ok, #state{}}.\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\n%% ===================================================================\n%% Internal\n%% ===================================================================\n-spec multicast_register(\n Name :: any(),\n Pid :: pid(),\n Meta :: any(),\n Time :: integer(),\n Force :: boolean(),\n #state{}\n) -> any().\nmulticast_register(Name, Pid, Meta, Time, Force, #state{\n multicast_pid = MulticastPid\n}) ->\n MulticastPid ! {multicast_register, Name, Pid, Meta, Time, Force}.\n\n-spec multicast_unregister(Name :: any(), Pid :: pid(), #state{}) -> any().\nmulticast_unregister(Name, Pid, #state{\n multicast_pid = MulticastPid\n}) ->\n MulticastPid ! {multicast_unregister, Name, Pid}.\n\n-spec register_on_node(Name :: any(), Pid :: pid(), Meta :: any()) -> {ok, Time :: integer()}.\nregister_on_node(Name, Pid, Meta) ->\n MonitorRef = case find_monitor_for_pid(Pid) of\n undefined ->\n %% process is not monitored yet, add\n erlang:monitor(process, Pid);\n\n MRef ->\n MRef\n end,\n %% add to table\n Time = erlang:system_time(),\n add_to_local_table(Name, Pid, Meta, Time, MonitorRef),\n {ok, Time}.\n\n-spec unregister_on_node(Name :: any()) -> {ok, RemovedPid :: pid()} | {error, Reason :: any()}.\nunregister_on_node(Name) ->\n case find_registry_entry_by_name(Name) of\n undefined ->\n {error, undefined};\n\n {{Name, Pid}, _Meta, _Clock, MonitorRef, _Node} when MonitorRef =\/= undefined ->\n %% demonitor if the process is not registered under other names\n maybe_demonitor(Pid),\n %% remove from table\n remove_from_local_table(Name, Pid),\n %% return\n {ok, Pid};\n\n {{Name, Pid}, _Meta, _Clock, _MonitorRef, Node} = RegistryEntry when Node =:= node() ->\n error_logger:error_msg(\n \"Syn(~p): INTERNAL ERROR | Registry entry ~p has no monitor but it's running on node~n\",\n [node(), RegistryEntry]\n ),\n %% remove from table\n remove_from_local_table(Name, Pid),\n %% return\n {ok, Pid};\n\n RegistryEntry ->\n %% race condition: un-registration request but entry in table is not a local pid (has no monitor)\n %% sync messages will take care of it\n error_logger:info_msg(\n \"Syn(~p): Registry entry ~p is not monitored and it's not running on node~n\",\n [node(), RegistryEntry]\n ),\n {error, remote_pid}\n end.\n\n-spec maybe_demonitor(Pid :: pid()) -> ok.\nmaybe_demonitor(Pid) ->\n %% try to retrieve 2 items\n %% if only 1 is returned it means that no other aliases exist for the Pid\n case ets:select(syn_registry_by_pid, [{\n {{Pid, '_'}, '_', '_', '$5', '_'},\n [],\n ['$5']\n }], 2) of\n {[MonitorRef], _} ->\n %% no other aliases, demonitor\n erlang:demonitor(MonitorRef, [flush]),\n ok;\n _ ->\n ok\n end.\n\n-spec add_to_local_table(\n Name :: any(),\n Pid :: pid(),\n Meta :: any(),\n Time :: integer(),\n MonitorRef :: undefined | reference()\n) -> ok.\nadd_to_local_table(Name, Pid, Meta, Time, MonitorRef) ->\n %% remove entry if previous exists\n case find_registry_tuple_by_name(Name) of\n undefined ->\n undefined;\n\n {Name, PreviousPid, _, _} ->\n remove_from_local_table(Name, PreviousPid)\n end,\n %% overwrite & add\n ets:insert(syn_registry_by_name, {{Name, Pid}, Meta, Time, MonitorRef, node(Pid)}),\n ets:insert(syn_registry_by_pid, {{Pid, Name}, Meta, Time, MonitorRef, node(Pid)}),\n ok.\n\n-spec remove_from_local_table(Name :: any(), Pid :: pid()) -> ok.\nremove_from_local_table(Name, Pid) ->\n ets:delete(syn_registry_by_name, {Name, Pid}),\n ets:delete(syn_registry_by_pid, {Pid, Name}),\n ok.\n\n-spec find_registry_tuple_by_name(Name :: any()) -> RegistryTuple :: syn_registry_tuple() | undefined.\nfind_registry_tuple_by_name(Name) ->\n case ets:select(syn_registry_by_name, [{\n {{Name, '$2'}, '$3', '$4', '_', '_'},\n [],\n [{{{const, Name}, '$2', '$3', '$4'}}]\n }]) of\n [RegistryTuple] -> RegistryTuple;\n _ -> undefined\n end.\n\n-spec find_registry_entry_by_name(Name :: any()) -> Entry :: syn_registry_entry() | undefined.\nfind_registry_entry_by_name(Name) ->\n case ets:select(syn_registry_by_name, [{\n {{Name, '$2'}, '$3', '_', '_', '_'},\n [],\n ['$_']\n }]) of\n [RegistryTuple] -> RegistryTuple;\n _ -> undefined\n end.\n\n-spec find_monitor_for_pid(Pid :: pid()) -> reference() | undefined.\nfind_monitor_for_pid(Pid) when is_pid(Pid) ->\n case ets:select(syn_registry_by_pid, [{\n {{Pid, '_'}, '_', '_', '$5', '_'},\n [],\n ['$5']\n }], 1) of\n {[MonitorRef], _} -> MonitorRef;\n _ -> undefined\n end.\n\n-spec find_registry_tuples_by_pid(Pid :: pid()) -> RegistryTuples :: [syn_registry_tuple()].\nfind_registry_tuples_by_pid(Pid) when is_pid(Pid) ->\n ets:select(syn_registry_by_pid, [{\n {{Pid, '$2'}, '$3', '$4', '_', '_'},\n [],\n [{{'$2', Pid, '$3', '$4'}}]\n }]).\n\n-spec get_registry_tuples_for_node(Node :: node()) -> [syn_registry_tuple()].\nget_registry_tuples_for_node(Node) ->\n ets:select(syn_registry_by_name, [{\n {{'$1', '$2'}, '$3', '$4', '_', Node},\n [],\n [{{'$1', '$2', '$3', '$4'}}]\n }]).\n\n-spec handle_process_down(Name :: any(), Pid :: pid(), Meta :: any(), Reason :: any(), #state{}) -> ok.\nhandle_process_down(Name, Pid, Meta, Reason, #state{\n custom_event_handler = CustomEventHandler\n}) ->\n case Name of\n undefined ->\n case Reason of\n {syn_resolve_kill, KillName, KillMeta} ->\n syn_event_handler:do_on_process_exit(KillName, Pid, KillMeta, syn_resolve_kill, CustomEventHandler);\n\n _ ->\n error_logger:warning_msg(\n \"Syn(~p): Received a DOWN message from an unregistered process ~p with reason: ~p~n\",\n [node(), Pid, Reason]\n )\n end;\n\n _ ->\n syn_event_handler:do_on_process_exit(Name, Pid, Meta, Reason, CustomEventHandler)\n end.\n\n-spec registry_automerge(RemoteNode :: node(), #state{}) -> ok.\nregistry_automerge(RemoteNode, State) ->\n global:trans({{?MODULE, auto_merge_registry}, self()},\n fun() ->\n error_logger:info_msg(\"Syn(~p): REGISTRY AUTOMERGE ----> Initiating for remote node ~p~n\", [node(), RemoteNode]),\n %% get registry tuples from remote node\n case rpc:call(RemoteNode, ?MODULE, sync_get_local_registry_tuples, [node()]) of\n {badrpc, _} ->\n error_logger:info_msg(\n \"Syn(~p): REGISTRY AUTOMERGE <---- Syn not ready on remote node ~p, postponing~n\",\n [node(), RemoteNode]\n );\n\n RegistryTuples ->\n error_logger:info_msg(\n \"Syn(~p): Received ~p registry tuple(s) from remote node ~p~n\",\n [node(), length(RegistryTuples), RemoteNode]\n ),\n %% ensure that registry doesn't have any joining node's entries (here again for race conditions)\n raw_purge_registry_entries_for_remote_node(RemoteNode),\n %% loop\n F = fun({Name, RemotePid, RemoteMeta, RemoteTime}) ->\n resolve_tuple_in_automerge(Name, RemotePid, RemoteMeta, RemoteTime, State)\n end,\n %% add to table\n lists:foreach(F, RegistryTuples),\n %% exit\n error_logger:info_msg(\"Syn(~p): REGISTRY AUTOMERGE <---- Done for remote node ~p~n\", [node(), RemoteNode])\n end\n end\n ).\n\n-spec resolve_tuple_in_automerge(\n Name :: any(),\n RemotePid :: pid(),\n RemoteMeta :: any(),\n RemoteTime :: integer(),\n #state{}\n) -> any().\nresolve_tuple_in_automerge(Name, RemotePid, RemoteMeta, RemoteTime, State) ->\n %% check if same name is registered\n case find_registry_tuple_by_name(Name) of\n undefined ->\n %% no conflict\n add_to_local_table(Name, RemotePid, RemoteMeta, RemoteTime, undefined);\n\n {Name, TablePid, TableMeta, TableTime} ->\n error_logger:warning_msg(\n \"Syn(~p): Conflicting name in auto merge for: ~p, processes are ~p, ~p~n\",\n [node(), Name, {TablePid, TableMeta, TableTime}, {RemotePid, RemoteMeta, RemoteTime}]\n ),\n\n case resolve_conflict(Name, {TablePid, TableMeta, TableTime}, {RemotePid, RemoteMeta, RemoteTime}, State) of\n {TablePid, KillOtherPid} ->\n %% keep local\n %% demonitor\n MonitorRef = rpc:call(node(RemotePid), syn_registry, find_monitor_for_pid, [RemotePid]),\n sync_demonitor_and_kill_on_node(Name, RemotePid, RemoteMeta, MonitorRef, KillOtherPid),\n %% remote data still on remote node, remove there\n ok = rpc:call(node(RemotePid), syn_registry, remove_from_local_table, [Name, RemotePid]);\n\n {RemotePid, KillOtherPid} ->\n %% keep remote\n %% demonitor\n MonitorRef = rpc:call(node(TablePid), syn_registry, find_monitor_for_pid, [TablePid]),\n sync_demonitor_and_kill_on_node(Name, TablePid, TableMeta, MonitorRef, KillOtherPid),\n %% overwrite remote data to local\n add_to_local_table(Name, RemotePid, RemoteMeta, RemoteTime, undefined);\n\n undefined ->\n %% both are dead, remove from local & remote\n remove_from_local_table(Name, TablePid),\n ok = rpc:call(node(RemotePid), syn_registry, remove_from_local_table, [Name, RemotePid])\n end\n end.\n\n-spec resolve_conflict(\n Name :: any(),\n {TablePid :: pid(), TableMeta :: any(), TableTime :: integer()},\n {RemotePid :: pid(), RemoteMeta :: any(), RemoteTime :: integer()},\n #state{}\n) -> {PidToKeep :: pid(), KillOtherPid :: boolean() | undefined} | undefined.\nresolve_conflict(\n Name,\n {TablePid, TableMeta, TableTime},\n {RemotePid, RemoteMeta, RemoteTime},\n #state{custom_event_handler = CustomEventHandler}\n) ->\n TablePidAlive = rpc:call(node(TablePid), erlang, is_process_alive, [TablePid]),\n RemotePidAlive = rpc:call(node(RemotePid), erlang, is_process_alive, [RemotePid]),\n\n %% check if pids are alive (race conditions if pid dies during resolution)\n {PidToKeep, KillOtherPid} = case {TablePidAlive, RemotePidAlive} of\n {true, true} ->\n %% call conflict resolution\n syn_event_handler:do_resolve_registry_conflict(\n Name,\n {TablePid, TableMeta, TableTime},\n {RemotePid, RemoteMeta, RemoteTime},\n CustomEventHandler\n );\n\n {true, false} ->\n %% keep only alive process\n {TablePid, false};\n\n {false, true} ->\n %% keep only alive process\n {RemotePid, false};\n\n {false, false} ->\n %% remove both\n {undefined, false}\n end,\n\n %% keep chosen one\n case PidToKeep of\n TablePid ->\n %% keep local\n error_logger:info_msg(\n \"Syn(~p): Keeping process in table ~p over remote process ~p~n\",\n [node(), TablePid, RemotePid]\n ),\n {TablePid, KillOtherPid};\n\n RemotePid ->\n %% keep remote\n error_logger:info_msg(\n \"Syn(~p): Keeping remote process ~p over process in table ~p~n\",\n [node(), RemotePid, TablePid]\n ),\n {RemotePid, KillOtherPid};\n\n undefined ->\n error_logger:info_msg(\n \"Syn(~p): Removing both processes' ~p and ~p data from local and remote tables~n\",\n [node(), RemotePid, TablePid]\n ),\n undefined;\n\n Other ->\n error_logger:error_msg(\n \"Syn(~p): Custom handler returned ~p, valid options were ~p and ~p, removing both~n\",\n [node(), Other, TablePid, RemotePid]\n ),\n undefined\n end.\n\n-spec do_sync_from_full_cluster(#state{}) -> ok.\ndo_sync_from_full_cluster(State) ->\n lists:foreach(fun(RemoteNode) ->\n registry_automerge(RemoteNode, State)\n end, nodes()).\n\n-spec raw_purge_registry_entries_for_remote_node(Node :: atom()) -> ok.\nraw_purge_registry_entries_for_remote_node(Node) when Node =\/= node() ->\n %% NB: no demonitoring is done, this is why it's raw\n ets:match_delete(syn_registry_by_name, {{'_', '_'}, '_', '_', '_', Node}),\n ets:match_delete(syn_registry_by_pid, {{'_', '_'}, '_', '_', '_', Node}),\n ok.\n\n-spec rebuild_monitors() -> ok.\nrebuild_monitors() ->\n RegistryTuples = get_registry_tuples_for_node(node()),\n lists:foreach(fun({Name, Pid, Meta, Time}) ->\n case is_process_alive(Pid) of\n true ->\n MonitorRef = erlang:monitor(process, Pid),\n %% overwrite\n add_to_local_table(Name, Pid, Meta, Time, MonitorRef);\n _ ->\n remove_from_local_table(Name, Pid)\n end\n end, RegistryTuples).\n\n-spec set_timer_for_anti_entropy(#state{}) -> ok.\nset_timer_for_anti_entropy(#state{anti_entropy_interval_ms = undefined}) -> ok;\nset_timer_for_anti_entropy(#state{\n anti_entropy_interval_ms = AntiEntropyIntervalMs,\n anti_entropy_interval_max_deviation_ms = AntiEntropyIntervalMaxDeviationMs\n}) ->\n IntervalMs = round(AntiEntropyIntervalMs + rand:uniform() * AntiEntropyIntervalMaxDeviationMs),\n {ok, _} = timer:send_after(IntervalMs, self(), sync_anti_entropy),\n ok.\n\n-spec demonitor_if_local(pid()) -> ok.\ndemonitor_if_local(Pid) ->\n case node(Pid) =:= node() of\n true ->\n %% demonitor\n MonitorRef = syn_registry:find_monitor_for_pid(Pid),\n catch erlang:demonitor(MonitorRef, [flush]),\n ok;\n\n _ ->\n ok\n end.\n\n-spec multicast_loop() -> terminated.\nmulticast_loop() ->\n receive\n {multicast_register, Name, Pid, Meta, Time, Force} ->\n lists:foreach(fun(RemoteNode) ->\n sync_register(RemoteNode, Name, Pid, Meta, Time, Force)\n end, nodes()),\n multicast_loop();\n\n {multicast_unregister, Name, Pid} ->\n lists:foreach(fun(RemoteNode) ->\n sync_unregister(RemoteNode, Name, Pid)\n end, nodes()),\n multicast_loop();\n\n terminate ->\n terminated\n end.\n","avg_line_length":39.2441860465,"max_line_length":130,"alphanum_fraction":0.5453037037} +{"size":1132,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"-module(hasler_sup).\n-behaviour(supervisor).\n\n%% API\n-export([start_link\/0]).\n\n%% Supervisor callbacks\n-export([init\/1]).\n\n%% Helper macro for declaring children of supervisor\n-define(CHILD(I, Type, Timeout), {I, {I, start_link, []}, permanent, Timeout, Type, [I]}).\n\n%% ===================================================================\n%% API functions\n%% ===================================================================\n\nstart_link() ->\n supervisor:start_link({local, ?MODULE}, ?MODULE, []).\n\n%% ===================================================================\n%% Supervisor callbacks\n%% ===================================================================\n\ninit([]) ->\n VMaster = {hasler_vnode_master,\n {riak_core_vnode_master, start_link, [hasler_vnode]},\n permanent, 5000, worker, [riak_core_vnode_master]},\n\n Command_sup = ?CHILD(hasler_command_sup, supervisor, 5000),\n\n Storage_sup = ?CHILD(hasler_storage_sup, supervisor, 20000),\n\n Root_sup = ?CHILD(hasler_root_sup, supervisor, 20000),\n\n {ok,\n {{one_for_one, 5, 10},\n [VMaster, Command_sup, Root_sup, Storage_sup]}}.","avg_line_length":30.5945945946,"max_line_length":90,"alphanum_fraction":0.5035335689} +{"size":4499,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%% Copyright 2009, Joe Williams \n%%\n%% Permission is hereby granted, free of charge, to any person\n%% obtaining a copy of this software and associated documentation\n%% files (the \"Software\"), to deal in the Software without\n%% restriction, including without limitation the rights to use,\n%% copy, modify, merge, publish, distribute, sublicense, and\/or sell\n%% copies of the Software, and to permit persons to whom the\n%% Software is furnished to do so, subject to the following\n%% conditions:\n%%\n%% The above copyright notice and this permission notice shall be\n%% included in all copies or substantial portions of the Software.\n%%\n%% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n%% OTHER DEALINGS IN THE SOFTWARE.\n%%\n%% @author Joseph Williams \n%% @copyright 2009 Joseph Williams\n%% @version pre 0.1\n%% @seealso http:\/\/www.last.fm\/api\n%% @doc A Last.fm API Library for Erlang.\n%%\n%% This code is available as Open Source Software under the MIT license.\n%%\n%% Updates at http:\/\/github.com\/joewilliams\/fermal\/\n\n\n-module(fermal).\n\n-behaviour(gen_server).\n\n\n-define(SERVER, ?MODULE).\n-define(API_KEY, \"81ea54e9ad93005af93da6d65e25e7d1\").\n-define(API_URL, \"http:\/\/ws.audioscrobbler.com\/2.0\/?method=\").\n-define(FORMAT, \"&format=json\").\n-define(LIMIT, \"&limit=3\").\n\n%% API\n-export([start\/0, artist_info\/1, artist_similar\/1, tasteometer\/2, album_info\/2,\n\t\ttrack_info\/2, venue_search\/1]).\n\n-export([check\/0]).\n\n%% gen_server callbacks\n-export([init\/1, handle_call\/3, handle_cast\/2, handle_info\/2,\n\t terminate\/2, code_change\/3]).\n\n-record(state, {}).\n\n\nstart_link() ->\n gen_server:start_link({local, ?SERVER}, ?MODULE, [], []),\n inets:start().\n\ninit([]) ->\n {ok, #state{}}.\n\n\nhandle_call({artist_info, {Artist}}, _From, State) ->\n Reply = fermal_artist:get_artist_info(?API_URL ++ \"artist.getinfo&artist=\" ++ Artist ++ \"&api_key=\" ++ ?API_KEY ++ ?FORMAT),\n {reply, Reply, State};\n\nhandle_call({artist_similar, {Artist}}, _From, State) ->\n\tReply = fermal_artist:get_artist_similar(?API_URL ++ \"artist.getsimilar&artist=\" ++ Artist ++ \"&api_key=\" ++ ?API_KEY ++ ?FORMAT),\n {reply, Reply, State};\n\t\nhandle_call({tasteometer, {User1, User2}}, _From, State) ->\n Reply = fermal_tasteometer:get_tasteometer(?API_URL ++ \"tasteometer.compare&type1=user&type2=user&value1=\" ++ User1\n \t++ \"&value2=\" ++ User2 ++ \"&api_key=\" ++ ?API_KEY ++ ?FORMAT),\n {reply, Reply, State};\n\nhandle_call({album_info, {Artist, Album}}, _From, State) ->\n Reply = fermal_album:get_album_info(?API_URL ++ \"album.getinfo&artist=\" ++ Artist ++ \"&album=\" ++ Album ++\"&api_key=\" ++ ?API_KEY ++ ?FORMAT),\n {reply, Reply, State};\n\nhandle_call({track_info, {Artist, Track}}, _From, State) ->\n Reply = fermal_track:get_track_info(?API_URL ++ \"track.getinfo&artist=\" ++ Artist ++ \"&track=\" ++ Track ++\"&api_key=\" ++ ?API_KEY ++ ?FORMAT),\n {reply, Reply, State};\n\nhandle_call({venue_search, {Venue}}, _From, State) ->\n Reply = fermal_venue:get_venue_search(?API_URL ++ \"venue.search&venue=\" ++ Venue ++\"&api_key=\" ++ ?API_KEY ++ ?FORMAT ++ ?LIMIT),\n {reply, Reply, State}.\n\nhandle_cast(_Msg, State) ->\n {noreply, State}.\n\nhandle_info(_Info, State) ->\n {noreply, State}.\n\n\nterminate(_Reason, _State) ->\n ok.\n\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\n%% @doc start gen_server\nstart() ->\n\tstart_link().\n\ncheck() ->\n\tstart(),\n\tRx = artist_similar(\"radiohead\").\n%% @doc gets info about an artist\nartist_info(Artist) ->\n\tgen_server:call(?SERVER, {artist_info, {Artist}}).\n\n%% @doc get similar artists\nartist_similar(Artist) ->\n\tgen_server:call(?SERVER, {artist_similar, {Artist}}).\n\n%% @doc compares two users for similar tastes\ntasteometer(User1, User2) ->\n\tgen_server:call(?SERVER, {tasteometer, {User1, User2}}).\n\n%% @doc gets info about an album\nalbum_info(Artist, Album) ->\n\tgen_server:call(?SERVER, {album_info, {Artist, Album}}).\n\n%% @doc search for a venue\nvenue_search(Venue) ->\n\tgen_server:call(?SERVER, {venue_search, {Venue}}).\n\n%% @doc get track info\ntrack_info(Artist, Track) ->\n\tgen_server:call(?SERVER, {track_info, {Artist, Track}}).\n","avg_line_length":33.3259259259,"max_line_length":146,"alphanum_fraction":0.6917092687} +{"size":758,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%-------------------------------------------------------------------\n%% @doc fullpass public API\n%% @end\n%%%-------------------------------------------------------------------\n\n-module(fullpass_app).\n\n-behaviour(application).\n\n%% Application callbacks\n-export([start\/2, stop\/1]).\n\n%%====================================================================\n%% API\n%%====================================================================\n\nstart(_StartType, _StartArgs) ->\n fullpass_sup:start_link().\n\n%%--------------------------------------------------------------------\nstop(_State) ->\n ok.\n\n%%====================================================================\n%% Internal functions\n%%====================================================================\n","avg_line_length":28.0740740741,"max_line_length":70,"alphanum_fraction":0.2335092348} +{"size":765,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"-module(calc).\n-behaviour(gen_server).\n\n-export([start\/1, stop\/0, eval\/1, print\/1]).\n-export([handle_call\/3, handle_cast\/2, init\/1, terminate\/2]).\n\nstart(Env) ->\n gen_server:start_link({local, ?MODULE}, ?MODULE, Env, []).\n\nprint(Expr) ->\n gen_server:cast(?MODULE, {print, Expr}).\neval(Expr) ->\n gen_server:call(?MODULE, {eval, Expr}).\n\nstop() ->\n gen_server:cast(?MODULE, stop). \n\nhandle_call({eval, Expr}, _From, Env) ->\n {reply, expr:eval(Env, Expr), Env}.\n\n\nhandle_cast({print, Expr}, Env) ->\n Str = expr:print(Expr),\n io:format(\"~s~n\",[Str]),\n {noreply, Env};\n\nhandle_cast(stop, Env) ->\n {stop, normal, Env}.\n\ninit(Env) ->\n io:format(\"Starting...~n\"),\n {ok, Env}.\n\nterminate(_Reason, _Env) ->\n io:format(\"Terminating...~n\").\n","avg_line_length":21.25,"max_line_length":62,"alphanum_fraction":0.6065359477} +{"size":223831,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%% Generated by the Erlang ASN.1 BER-compiler version, utilizing bit-syntax:1.6.16\n%% Purpose: encoder and decoder to the types in mod megaco_per_bin_drv_media_gateway_control_v3\n\n-module('megaco_per_bin_drv_media_gateway_control_v3').\n-include(\"megaco_per_bin_drv_media_gateway_control_v3.hrl\").\n-define('RT_PER',asn1rt_per_bin_rt2ct).\n-asn1_info([{vsn,'1.6.16'},\n {module,'megaco_per_bin_drv_media_gateway_control_v3'},\n {options,[warnings,per_bin,errors,{cwd,[47,110,101,116,47,105,115,105,108,100,117,114,47,108,100,105,115,107,47,100,97,105,108,121,95,98,117,105,108,100,47,114,49,52,98,48,50,95,112,114,101,98,117,105,108,100,95,111,112,117,95,111,46,50,48,49,49,45,48,51,45,49,52,95,50,48,47,111,116,112,95,115,114,99,95,82,49,52,66,48,50,47,108,105,98,47,109,101,103,97,99,111,47,115,114,99,47,98,105,110,97,114,121]},{outdir,[47,110,101,116,47,105,115,105,108,100,117,114,47,108,100,105,115,107,47,100,97,105,108,121,95,98,117,105,108,100,47,114,49,52,98,48,50,95,112,114,101,98,117,105,108,100,95,111,112,117,95,111,46,50,48,49,49,45,48,51,45,49,52,95,50,48,47,111,116,112,95,115,114,99,95,82,49,52,66,48,50,47,108,105,98,47,109,101,103,97,99,111,47,115,114,99,47,98,105,110,97,114,121]},optimize,noobj,{i,[46]},{i,[47,110,101,116,47,105,115,105,108,100,117,114,47,108,100,105,115,107,47,100,97,105,108,121,95,98,117,105,108,100,47,114,49,52,98,48,50,95,112,114,101,98,117,105,108,100,95,111,112,117,95,111,46,50,48,49,49,45,48,51,45,49,52,95,50,48,47,111,116,112,95,115,114,99,95,82,49,52,66,48,50,47,108,105,98,47,109,101,103,97,99,111,47,115,114,99,47,98,105,110,97,114,121]}]}]).\n\n-export([encoding_rule\/0]).\n-export([\n'enc_Value'\/1,\n'enc_TimeNotation'\/1,\n'enc_H221NonStandard'\/1,\n'enc_NonStandardIdentifier'\/1,\n'enc_NonStandardData'\/1,\n'enc_StatisticsParameter'\/1,\n'enc_StatisticsDescriptor'\/1,\n'enc_PackagesItem'\/1,\n'enc_PackagesDescriptor'\/1,\n'enc_ServiceChangeProfile'\/1,\n'enc_ServiceChangeMethod'\/1,\n'enc_ServiceChangeResParm'\/1,\n'enc_ServiceChangeAddress'\/1,\n'enc_ServiceChangeParm'\/1,\n'enc_DigitMapValue'\/1,\n'enc_DigitMapName'\/1,\n'enc_DigitMapDescriptor'\/1,\n'enc_ModemType'\/1,\n'enc_ModemDescriptor'\/1,\n'enc_RequestID'\/1,\n'enc_SigParameter'\/1,\n'enc_NotifyCompletion'\/1,\n'enc_SignalName'\/1,\n'enc_SignalDirection'\/1,\n'enc_SignalType'\/1,\n'enc_Signal'\/1,\n'enc_SeqSigList'\/1,\n'enc_SignalRequest'\/1,\n'enc_SignalsDescriptor'\/1,\n'enc_EventSpec'\/1,\n'enc_EventBufferDescriptor'\/1,\n'enc_SecondRequestedActions'\/1,\n'enc_SecondRequestedEvent'\/1,\n'enc_SecondEventsDescriptor'\/1,\n'enc_EventDM'\/1,\n'enc_RequestedActions'\/1,\n'enc_NotifyBehaviour'\/1,\n'enc_RegulatedEmbeddedDescriptor'\/1,\n'enc_RequestedEvent'\/1,\n'enc_EventsDescriptor'\/1,\n'enc_StreamID'\/1,\n'enc_MuxType'\/1,\n'enc_MuxDescriptor'\/1,\n'enc_ServiceState'\/1,\n'enc_EventBufferControl'\/1,\n'enc_TerminationStateDescriptor'\/1,\n'enc_PropertyGroup'\/1,\n'enc_LocalRemoteDescriptor'\/1,\n'enc_Relation'\/1,\n'enc_PkgdName'\/1,\n'enc_Name'\/1,\n'enc_PropertyParm'\/1,\n'enc_StreamMode'\/1,\n'enc_LocalControlDescriptor'\/1,\n'enc_StreamParms'\/1,\n'enc_StreamDescriptor'\/1,\n'enc_MediaDescriptor'\/1,\n'enc_TerminationIDList'\/1,\n'enc_TerminationID'\/1,\n'enc_WildcardField'\/1,\n'enc_ServiceChangeResult'\/1,\n'enc_ServiceChangeReply'\/1,\n'enc_ServiceChangeRequest'\/1,\n'enc_EventParameter'\/1,\n'enc_EventName'\/1,\n'enc_ObservedEvent'\/1,\n'enc_ObservedEventsDescriptor'\/1,\n'enc_NotifyReply'\/1,\n'enc_NotifyRequest'\/1,\n'enc_IndAudPackagesDescriptor'\/1,\n'enc_IndAudStatisticsDescriptor'\/1,\n'enc_IndAudDigitMapDescriptor'\/1,\n'enc_IndAudSignal'\/1,\n'enc_IndAudSeqSigList'\/1,\n'enc_IndAudSignalsDescriptor'\/1,\n'enc_IndAudEventBufferDescriptor'\/1,\n'enc_IndAudEventsDescriptor'\/1,\n'enc_IndAudTerminationStateDescriptor'\/1,\n'enc_IndAudPropertyGroup'\/1,\n'enc_IndAudLocalRemoteDescriptor'\/1,\n'enc_IndAudPropertyParm'\/1,\n'enc_IndAudLocalControlDescriptor'\/1,\n'enc_IndAudStreamParms'\/1,\n'enc_IndAudStreamDescriptor'\/1,\n'enc_IndAudMediaDescriptor'\/1,\n'enc_IndAuditParameter'\/1,\n'enc_AuditDescriptor'\/1,\n'enc_AuditReturnParameter'\/1,\n'enc_TerminationAudit'\/1,\n'enc_TermListAuditResult'\/1,\n'enc_AuditResult'\/1,\n'enc_AuditReply'\/1,\n'enc_AuditRequest'\/1,\n'enc_SubtractRequest'\/1,\n'enc_AmmsReply'\/1,\n'enc_AmmDescriptor'\/1,\n'enc_AmmRequest'\/1,\n'enc_TopologyRequest'\/1,\n'enc_CommandReply'\/1,\n'enc_Command'\/1,\n'enc_CommandRequest'\/1,\n'enc_SelectLogic'\/1,\n'enc_ContextAttrAuditRequest'\/1,\n'enc_ContextRequest'\/1,\n'enc_ActionReply'\/1,\n'enc_ActionRequest'\/1,\n'enc_ContextID'\/1,\n'enc_ErrorText'\/1,\n'enc_ErrorCode'\/1,\n'enc_ErrorDescriptor'\/1,\n'enc_TransactionAck'\/1,\n'enc_TransactionResponseAck'\/1,\n'enc_SegmentNumber'\/1,\n'enc_SegmentReply'\/1,\n'enc_TransactionReply'\/1,\n'enc_TransactionPending'\/1,\n'enc_TransactionRequest'\/1,\n'enc_TransactionId'\/1,\n'enc_Transaction'\/1,\n'enc_PathName'\/1,\n'enc_IP6Address'\/1,\n'enc_IP4Address'\/1,\n'enc_DomainName'\/1,\n'enc_MId'\/1,\n'enc_Message'\/1,\n'enc_AuthData'\/1,\n'enc_SequenceNum'\/1,\n'enc_SecurityParmIndex'\/1,\n'enc_AuthenticationHeader'\/1,\n'enc_MegacoMessage'\/1\n]).\n\n-export([\n'dec_Value'\/2,\n'dec_TimeNotation'\/2,\n'dec_H221NonStandard'\/2,\n'dec_NonStandardIdentifier'\/2,\n'dec_NonStandardData'\/2,\n'dec_StatisticsParameter'\/2,\n'dec_StatisticsDescriptor'\/2,\n'dec_PackagesItem'\/2,\n'dec_PackagesDescriptor'\/2,\n'dec_ServiceChangeProfile'\/2,\n'dec_ServiceChangeMethod'\/2,\n'dec_ServiceChangeResParm'\/2,\n'dec_ServiceChangeAddress'\/2,\n'dec_ServiceChangeParm'\/2,\n'dec_DigitMapValue'\/2,\n'dec_DigitMapName'\/2,\n'dec_DigitMapDescriptor'\/2,\n'dec_ModemType'\/2,\n'dec_ModemDescriptor'\/2,\n'dec_RequestID'\/2,\n'dec_SigParameter'\/2,\n'dec_NotifyCompletion'\/2,\n'dec_SignalName'\/2,\n'dec_SignalDirection'\/2,\n'dec_SignalType'\/2,\n'dec_Signal'\/2,\n'dec_SeqSigList'\/2,\n'dec_SignalRequest'\/2,\n'dec_SignalsDescriptor'\/2,\n'dec_EventSpec'\/2,\n'dec_EventBufferDescriptor'\/2,\n'dec_SecondRequestedActions'\/2,\n'dec_SecondRequestedEvent'\/2,\n'dec_SecondEventsDescriptor'\/2,\n'dec_EventDM'\/2,\n'dec_RequestedActions'\/2,\n'dec_NotifyBehaviour'\/2,\n'dec_RegulatedEmbeddedDescriptor'\/2,\n'dec_RequestedEvent'\/2,\n'dec_EventsDescriptor'\/2,\n'dec_StreamID'\/2,\n'dec_MuxType'\/2,\n'dec_MuxDescriptor'\/2,\n'dec_ServiceState'\/2,\n'dec_EventBufferControl'\/2,\n'dec_TerminationStateDescriptor'\/2,\n'dec_PropertyGroup'\/2,\n'dec_LocalRemoteDescriptor'\/2,\n'dec_Relation'\/2,\n'dec_PkgdName'\/2,\n'dec_Name'\/2,\n'dec_PropertyParm'\/2,\n'dec_StreamMode'\/2,\n'dec_LocalControlDescriptor'\/2,\n'dec_StreamParms'\/2,\n'dec_StreamDescriptor'\/2,\n'dec_MediaDescriptor'\/2,\n'dec_TerminationIDList'\/2,\n'dec_TerminationID'\/2,\n'dec_WildcardField'\/2,\n'dec_ServiceChangeResult'\/2,\n'dec_ServiceChangeReply'\/2,\n'dec_ServiceChangeRequest'\/2,\n'dec_EventParameter'\/2,\n'dec_EventName'\/2,\n'dec_ObservedEvent'\/2,\n'dec_ObservedEventsDescriptor'\/2,\n'dec_NotifyReply'\/2,\n'dec_NotifyRequest'\/2,\n'dec_IndAudPackagesDescriptor'\/2,\n'dec_IndAudStatisticsDescriptor'\/2,\n'dec_IndAudDigitMapDescriptor'\/2,\n'dec_IndAudSignal'\/2,\n'dec_IndAudSeqSigList'\/2,\n'dec_IndAudSignalsDescriptor'\/2,\n'dec_IndAudEventBufferDescriptor'\/2,\n'dec_IndAudEventsDescriptor'\/2,\n'dec_IndAudTerminationStateDescriptor'\/2,\n'dec_IndAudPropertyGroup'\/2,\n'dec_IndAudLocalRemoteDescriptor'\/2,\n'dec_IndAudPropertyParm'\/2,\n'dec_IndAudLocalControlDescriptor'\/2,\n'dec_IndAudStreamParms'\/2,\n'dec_IndAudStreamDescriptor'\/2,\n'dec_IndAudMediaDescriptor'\/2,\n'dec_IndAuditParameter'\/2,\n'dec_AuditDescriptor'\/2,\n'dec_AuditReturnParameter'\/2,\n'dec_TerminationAudit'\/2,\n'dec_TermListAuditResult'\/2,\n'dec_AuditResult'\/2,\n'dec_AuditReply'\/2,\n'dec_AuditRequest'\/2,\n'dec_SubtractRequest'\/2,\n'dec_AmmsReply'\/2,\n'dec_AmmDescriptor'\/2,\n'dec_AmmRequest'\/2,\n'dec_TopologyRequest'\/2,\n'dec_CommandReply'\/2,\n'dec_Command'\/2,\n'dec_CommandRequest'\/2,\n'dec_SelectLogic'\/2,\n'dec_ContextAttrAuditRequest'\/2,\n'dec_ContextRequest'\/2,\n'dec_ActionReply'\/2,\n'dec_ActionRequest'\/2,\n'dec_ContextID'\/2,\n'dec_ErrorText'\/2,\n'dec_ErrorCode'\/2,\n'dec_ErrorDescriptor'\/2,\n'dec_TransactionAck'\/2,\n'dec_TransactionResponseAck'\/2,\n'dec_SegmentNumber'\/2,\n'dec_SegmentReply'\/2,\n'dec_TransactionReply'\/2,\n'dec_TransactionPending'\/2,\n'dec_TransactionRequest'\/2,\n'dec_TransactionId'\/2,\n'dec_Transaction'\/2,\n'dec_PathName'\/2,\n'dec_IP6Address'\/2,\n'dec_IP4Address'\/2,\n'dec_DomainName'\/2,\n'dec_MId'\/2,\n'dec_Message'\/2,\n'dec_AuthData'\/2,\n'dec_SequenceNum'\/2,\n'dec_SecurityParmIndex'\/2,\n'dec_AuthenticationHeader'\/2,\n'dec_MegacoMessage'\/2\n]).\n\n-export([info\/0]).\n\n\n-export([encode\/2,decode\/2,encode_disp\/2,decode_disp\/2]).\n\nencoding_rule() ->\n per_bin.\n\nencode(Type,Data) ->\ncase catch ?RT_PER:complete(encode_disp(Type,Data)) of\n {'EXIT',{error,Reason}} ->\n {error,Reason};\n {'EXIT',Reason} ->\n {error,{asn1,Reason}};\n {Bytes,_Len} ->\n {ok,Bytes};\n Bytes ->\n {ok,Bytes}\nend.\n\ndecode(Type,Data) ->\ncase catch decode_disp(Type,Data) of\n {'EXIT',{error,Reason}} ->\n {error,Reason};\n {'EXIT',Reason} ->\n {error,{asn1,Reason}};\n {X,_Rest} ->\n {ok,X};\n {X,_Rest,_Len} ->\n {ok,X}\nend.\n\nencode_disp('Value',Data) -> 'enc_Value'(Data);\nencode_disp('TimeNotation',Data) -> 'enc_TimeNotation'(Data);\nencode_disp('H221NonStandard',Data) -> 'enc_H221NonStandard'(Data);\nencode_disp('NonStandardIdentifier',Data) -> 'enc_NonStandardIdentifier'(Data);\nencode_disp('NonStandardData',Data) -> 'enc_NonStandardData'(Data);\nencode_disp('StatisticsParameter',Data) -> 'enc_StatisticsParameter'(Data);\nencode_disp('StatisticsDescriptor',Data) -> 'enc_StatisticsDescriptor'(Data);\nencode_disp('PackagesItem',Data) -> 'enc_PackagesItem'(Data);\nencode_disp('PackagesDescriptor',Data) -> 'enc_PackagesDescriptor'(Data);\nencode_disp('ServiceChangeProfile',Data) -> 'enc_ServiceChangeProfile'(Data);\nencode_disp('ServiceChangeMethod',Data) -> 'enc_ServiceChangeMethod'(Data);\nencode_disp('ServiceChangeResParm',Data) -> 'enc_ServiceChangeResParm'(Data);\nencode_disp('ServiceChangeAddress',Data) -> 'enc_ServiceChangeAddress'(Data);\nencode_disp('ServiceChangeParm',Data) -> 'enc_ServiceChangeParm'(Data);\nencode_disp('DigitMapValue',Data) -> 'enc_DigitMapValue'(Data);\nencode_disp('DigitMapName',Data) -> 'enc_DigitMapName'(Data);\nencode_disp('DigitMapDescriptor',Data) -> 'enc_DigitMapDescriptor'(Data);\nencode_disp('ModemType',Data) -> 'enc_ModemType'(Data);\nencode_disp('ModemDescriptor',Data) -> 'enc_ModemDescriptor'(Data);\nencode_disp('RequestID',Data) -> 'enc_RequestID'(Data);\nencode_disp('SigParameter',Data) -> 'enc_SigParameter'(Data);\nencode_disp('NotifyCompletion',Data) -> 'enc_NotifyCompletion'(Data);\nencode_disp('SignalName',Data) -> 'enc_SignalName'(Data);\nencode_disp('SignalDirection',Data) -> 'enc_SignalDirection'(Data);\nencode_disp('SignalType',Data) -> 'enc_SignalType'(Data);\nencode_disp('Signal',Data) -> 'enc_Signal'(Data);\nencode_disp('SeqSigList',Data) -> 'enc_SeqSigList'(Data);\nencode_disp('SignalRequest',Data) -> 'enc_SignalRequest'(Data);\nencode_disp('SignalsDescriptor',Data) -> 'enc_SignalsDescriptor'(Data);\nencode_disp('EventSpec',Data) -> 'enc_EventSpec'(Data);\nencode_disp('EventBufferDescriptor',Data) -> 'enc_EventBufferDescriptor'(Data);\nencode_disp('SecondRequestedActions',Data) -> 'enc_SecondRequestedActions'(Data);\nencode_disp('SecondRequestedEvent',Data) -> 'enc_SecondRequestedEvent'(Data);\nencode_disp('SecondEventsDescriptor',Data) -> 'enc_SecondEventsDescriptor'(Data);\nencode_disp('EventDM',Data) -> 'enc_EventDM'(Data);\nencode_disp('RequestedActions',Data) -> 'enc_RequestedActions'(Data);\nencode_disp('NotifyBehaviour',Data) -> 'enc_NotifyBehaviour'(Data);\nencode_disp('RegulatedEmbeddedDescriptor',Data) -> 'enc_RegulatedEmbeddedDescriptor'(Data);\nencode_disp('RequestedEvent',Data) -> 'enc_RequestedEvent'(Data);\nencode_disp('EventsDescriptor',Data) -> 'enc_EventsDescriptor'(Data);\nencode_disp('StreamID',Data) -> 'enc_StreamID'(Data);\nencode_disp('MuxType',Data) -> 'enc_MuxType'(Data);\nencode_disp('MuxDescriptor',Data) -> 'enc_MuxDescriptor'(Data);\nencode_disp('ServiceState',Data) -> 'enc_ServiceState'(Data);\nencode_disp('EventBufferControl',Data) -> 'enc_EventBufferControl'(Data);\nencode_disp('TerminationStateDescriptor',Data) -> 'enc_TerminationStateDescriptor'(Data);\nencode_disp('PropertyGroup',Data) -> 'enc_PropertyGroup'(Data);\nencode_disp('LocalRemoteDescriptor',Data) -> 'enc_LocalRemoteDescriptor'(Data);\nencode_disp('Relation',Data) -> 'enc_Relation'(Data);\nencode_disp('PkgdName',Data) -> 'enc_PkgdName'(Data);\nencode_disp('Name',Data) -> 'enc_Name'(Data);\nencode_disp('PropertyParm',Data) -> 'enc_PropertyParm'(Data);\nencode_disp('StreamMode',Data) -> 'enc_StreamMode'(Data);\nencode_disp('LocalControlDescriptor',Data) -> 'enc_LocalControlDescriptor'(Data);\nencode_disp('StreamParms',Data) -> 'enc_StreamParms'(Data);\nencode_disp('StreamDescriptor',Data) -> 'enc_StreamDescriptor'(Data);\nencode_disp('MediaDescriptor',Data) -> 'enc_MediaDescriptor'(Data);\nencode_disp('TerminationIDList',Data) -> 'enc_TerminationIDList'(Data);\nencode_disp('TerminationID',Data) -> 'enc_TerminationID'(Data);\nencode_disp('WildcardField',Data) -> 'enc_WildcardField'(Data);\nencode_disp('ServiceChangeResult',Data) -> 'enc_ServiceChangeResult'(Data);\nencode_disp('ServiceChangeReply',Data) -> 'enc_ServiceChangeReply'(Data);\nencode_disp('ServiceChangeRequest',Data) -> 'enc_ServiceChangeRequest'(Data);\nencode_disp('EventParameter',Data) -> 'enc_EventParameter'(Data);\nencode_disp('EventName',Data) -> 'enc_EventName'(Data);\nencode_disp('ObservedEvent',Data) -> 'enc_ObservedEvent'(Data);\nencode_disp('ObservedEventsDescriptor',Data) -> 'enc_ObservedEventsDescriptor'(Data);\nencode_disp('NotifyReply',Data) -> 'enc_NotifyReply'(Data);\nencode_disp('NotifyRequest',Data) -> 'enc_NotifyRequest'(Data);\nencode_disp('IndAudPackagesDescriptor',Data) -> 'enc_IndAudPackagesDescriptor'(Data);\nencode_disp('IndAudStatisticsDescriptor',Data) -> 'enc_IndAudStatisticsDescriptor'(Data);\nencode_disp('IndAudDigitMapDescriptor',Data) -> 'enc_IndAudDigitMapDescriptor'(Data);\nencode_disp('IndAudSignal',Data) -> 'enc_IndAudSignal'(Data);\nencode_disp('IndAudSeqSigList',Data) -> 'enc_IndAudSeqSigList'(Data);\nencode_disp('IndAudSignalsDescriptor',Data) -> 'enc_IndAudSignalsDescriptor'(Data);\nencode_disp('IndAudEventBufferDescriptor',Data) -> 'enc_IndAudEventBufferDescriptor'(Data);\nencode_disp('IndAudEventsDescriptor',Data) -> 'enc_IndAudEventsDescriptor'(Data);\nencode_disp('IndAudTerminationStateDescriptor',Data) -> 'enc_IndAudTerminationStateDescriptor'(Data);\nencode_disp('IndAudPropertyGroup',Data) -> 'enc_IndAudPropertyGroup'(Data);\nencode_disp('IndAudLocalRemoteDescriptor',Data) -> 'enc_IndAudLocalRemoteDescriptor'(Data);\nencode_disp('IndAudPropertyParm',Data) -> 'enc_IndAudPropertyParm'(Data);\nencode_disp('IndAudLocalControlDescriptor',Data) -> 'enc_IndAudLocalControlDescriptor'(Data);\nencode_disp('IndAudStreamParms',Data) -> 'enc_IndAudStreamParms'(Data);\nencode_disp('IndAudStreamDescriptor',Data) -> 'enc_IndAudStreamDescriptor'(Data);\nencode_disp('IndAudMediaDescriptor',Data) -> 'enc_IndAudMediaDescriptor'(Data);\nencode_disp('IndAuditParameter',Data) -> 'enc_IndAuditParameter'(Data);\nencode_disp('AuditDescriptor',Data) -> 'enc_AuditDescriptor'(Data);\nencode_disp('AuditReturnParameter',Data) -> 'enc_AuditReturnParameter'(Data);\nencode_disp('TerminationAudit',Data) -> 'enc_TerminationAudit'(Data);\nencode_disp('TermListAuditResult',Data) -> 'enc_TermListAuditResult'(Data);\nencode_disp('AuditResult',Data) -> 'enc_AuditResult'(Data);\nencode_disp('AuditReply',Data) -> 'enc_AuditReply'(Data);\nencode_disp('AuditRequest',Data) -> 'enc_AuditRequest'(Data);\nencode_disp('SubtractRequest',Data) -> 'enc_SubtractRequest'(Data);\nencode_disp('AmmsReply',Data) -> 'enc_AmmsReply'(Data);\nencode_disp('AmmDescriptor',Data) -> 'enc_AmmDescriptor'(Data);\nencode_disp('AmmRequest',Data) -> 'enc_AmmRequest'(Data);\nencode_disp('TopologyRequest',Data) -> 'enc_TopologyRequest'(Data);\nencode_disp('CommandReply',Data) -> 'enc_CommandReply'(Data);\nencode_disp('Command',Data) -> 'enc_Command'(Data);\nencode_disp('CommandRequest',Data) -> 'enc_CommandRequest'(Data);\nencode_disp('SelectLogic',Data) -> 'enc_SelectLogic'(Data);\nencode_disp('ContextAttrAuditRequest',Data) -> 'enc_ContextAttrAuditRequest'(Data);\nencode_disp('ContextRequest',Data) -> 'enc_ContextRequest'(Data);\nencode_disp('ActionReply',Data) -> 'enc_ActionReply'(Data);\nencode_disp('ActionRequest',Data) -> 'enc_ActionRequest'(Data);\nencode_disp('ContextID',Data) -> 'enc_ContextID'(Data);\nencode_disp('ErrorText',Data) -> 'enc_ErrorText'(Data);\nencode_disp('ErrorCode',Data) -> 'enc_ErrorCode'(Data);\nencode_disp('ErrorDescriptor',Data) -> 'enc_ErrorDescriptor'(Data);\nencode_disp('TransactionAck',Data) -> 'enc_TransactionAck'(Data);\nencode_disp('TransactionResponseAck',Data) -> 'enc_TransactionResponseAck'(Data);\nencode_disp('SegmentNumber',Data) -> 'enc_SegmentNumber'(Data);\nencode_disp('SegmentReply',Data) -> 'enc_SegmentReply'(Data);\nencode_disp('TransactionReply',Data) -> 'enc_TransactionReply'(Data);\nencode_disp('TransactionPending',Data) -> 'enc_TransactionPending'(Data);\nencode_disp('TransactionRequest',Data) -> 'enc_TransactionRequest'(Data);\nencode_disp('TransactionId',Data) -> 'enc_TransactionId'(Data);\nencode_disp('Transaction',Data) -> 'enc_Transaction'(Data);\nencode_disp('PathName',Data) -> 'enc_PathName'(Data);\nencode_disp('IP6Address',Data) -> 'enc_IP6Address'(Data);\nencode_disp('IP4Address',Data) -> 'enc_IP4Address'(Data);\nencode_disp('DomainName',Data) -> 'enc_DomainName'(Data);\nencode_disp('MId',Data) -> 'enc_MId'(Data);\nencode_disp('Message',Data) -> 'enc_Message'(Data);\nencode_disp('AuthData',Data) -> 'enc_AuthData'(Data);\nencode_disp('SequenceNum',Data) -> 'enc_SequenceNum'(Data);\nencode_disp('SecurityParmIndex',Data) -> 'enc_SecurityParmIndex'(Data);\nencode_disp('AuthenticationHeader',Data) -> 'enc_AuthenticationHeader'(Data);\nencode_disp('MegacoMessage',Data) -> 'enc_MegacoMessage'(Data);\nencode_disp(Type,_Data) -> exit({error,{asn1,{undefined_type,Type}}}).\n\n\ndecode_disp('Value',Data) -> 'dec_Value'(Data,mandatory);\ndecode_disp('TimeNotation',Data) -> 'dec_TimeNotation'(Data,mandatory);\ndecode_disp('H221NonStandard',Data) -> 'dec_H221NonStandard'(Data,mandatory);\ndecode_disp('NonStandardIdentifier',Data) -> 'dec_NonStandardIdentifier'(Data,mandatory);\ndecode_disp('NonStandardData',Data) -> 'dec_NonStandardData'(Data,mandatory);\ndecode_disp('StatisticsParameter',Data) -> 'dec_StatisticsParameter'(Data,mandatory);\ndecode_disp('StatisticsDescriptor',Data) -> 'dec_StatisticsDescriptor'(Data,mandatory);\ndecode_disp('PackagesItem',Data) -> 'dec_PackagesItem'(Data,mandatory);\ndecode_disp('PackagesDescriptor',Data) -> 'dec_PackagesDescriptor'(Data,mandatory);\ndecode_disp('ServiceChangeProfile',Data) -> 'dec_ServiceChangeProfile'(Data,mandatory);\ndecode_disp('ServiceChangeMethod',Data) -> 'dec_ServiceChangeMethod'(Data,mandatory);\ndecode_disp('ServiceChangeResParm',Data) -> 'dec_ServiceChangeResParm'(Data,mandatory);\ndecode_disp('ServiceChangeAddress',Data) -> 'dec_ServiceChangeAddress'(Data,mandatory);\ndecode_disp('ServiceChangeParm',Data) -> 'dec_ServiceChangeParm'(Data,mandatory);\ndecode_disp('DigitMapValue',Data) -> 'dec_DigitMapValue'(Data,mandatory);\ndecode_disp('DigitMapName',Data) -> 'dec_DigitMapName'(Data,mandatory);\ndecode_disp('DigitMapDescriptor',Data) -> 'dec_DigitMapDescriptor'(Data,mandatory);\ndecode_disp('ModemType',Data) -> 'dec_ModemType'(Data,mandatory);\ndecode_disp('ModemDescriptor',Data) -> 'dec_ModemDescriptor'(Data,mandatory);\ndecode_disp('RequestID',Data) -> 'dec_RequestID'(Data,mandatory);\ndecode_disp('SigParameter',Data) -> 'dec_SigParameter'(Data,mandatory);\ndecode_disp('NotifyCompletion',Data) -> 'dec_NotifyCompletion'(Data,mandatory);\ndecode_disp('SignalName',Data) -> 'dec_SignalName'(Data,mandatory);\ndecode_disp('SignalDirection',Data) -> 'dec_SignalDirection'(Data,mandatory);\ndecode_disp('SignalType',Data) -> 'dec_SignalType'(Data,mandatory);\ndecode_disp('Signal',Data) -> 'dec_Signal'(Data,mandatory);\ndecode_disp('SeqSigList',Data) -> 'dec_SeqSigList'(Data,mandatory);\ndecode_disp('SignalRequest',Data) -> 'dec_SignalRequest'(Data,mandatory);\ndecode_disp('SignalsDescriptor',Data) -> 'dec_SignalsDescriptor'(Data,mandatory);\ndecode_disp('EventSpec',Data) -> 'dec_EventSpec'(Data,mandatory);\ndecode_disp('EventBufferDescriptor',Data) -> 'dec_EventBufferDescriptor'(Data,mandatory);\ndecode_disp('SecondRequestedActions',Data) -> 'dec_SecondRequestedActions'(Data,mandatory);\ndecode_disp('SecondRequestedEvent',Data) -> 'dec_SecondRequestedEvent'(Data,mandatory);\ndecode_disp('SecondEventsDescriptor',Data) -> 'dec_SecondEventsDescriptor'(Data,mandatory);\ndecode_disp('EventDM',Data) -> 'dec_EventDM'(Data,mandatory);\ndecode_disp('RequestedActions',Data) -> 'dec_RequestedActions'(Data,mandatory);\ndecode_disp('NotifyBehaviour',Data) -> 'dec_NotifyBehaviour'(Data,mandatory);\ndecode_disp('RegulatedEmbeddedDescriptor',Data) -> 'dec_RegulatedEmbeddedDescriptor'(Data,mandatory);\ndecode_disp('RequestedEvent',Data) -> 'dec_RequestedEvent'(Data,mandatory);\ndecode_disp('EventsDescriptor',Data) -> 'dec_EventsDescriptor'(Data,mandatory);\ndecode_disp('StreamID',Data) -> 'dec_StreamID'(Data,mandatory);\ndecode_disp('MuxType',Data) -> 'dec_MuxType'(Data,mandatory);\ndecode_disp('MuxDescriptor',Data) -> 'dec_MuxDescriptor'(Data,mandatory);\ndecode_disp('ServiceState',Data) -> 'dec_ServiceState'(Data,mandatory);\ndecode_disp('EventBufferControl',Data) -> 'dec_EventBufferControl'(Data,mandatory);\ndecode_disp('TerminationStateDescriptor',Data) -> 'dec_TerminationStateDescriptor'(Data,mandatory);\ndecode_disp('PropertyGroup',Data) -> 'dec_PropertyGroup'(Data,mandatory);\ndecode_disp('LocalRemoteDescriptor',Data) -> 'dec_LocalRemoteDescriptor'(Data,mandatory);\ndecode_disp('Relation',Data) -> 'dec_Relation'(Data,mandatory);\ndecode_disp('PkgdName',Data) -> 'dec_PkgdName'(Data,mandatory);\ndecode_disp('Name',Data) -> 'dec_Name'(Data,mandatory);\ndecode_disp('PropertyParm',Data) -> 'dec_PropertyParm'(Data,mandatory);\ndecode_disp('StreamMode',Data) -> 'dec_StreamMode'(Data,mandatory);\ndecode_disp('LocalControlDescriptor',Data) -> 'dec_LocalControlDescriptor'(Data,mandatory);\ndecode_disp('StreamParms',Data) -> 'dec_StreamParms'(Data,mandatory);\ndecode_disp('StreamDescriptor',Data) -> 'dec_StreamDescriptor'(Data,mandatory);\ndecode_disp('MediaDescriptor',Data) -> 'dec_MediaDescriptor'(Data,mandatory);\ndecode_disp('TerminationIDList',Data) -> 'dec_TerminationIDList'(Data,mandatory);\ndecode_disp('TerminationID',Data) -> 'dec_TerminationID'(Data,mandatory);\ndecode_disp('WildcardField',Data) -> 'dec_WildcardField'(Data,mandatory);\ndecode_disp('ServiceChangeResult',Data) -> 'dec_ServiceChangeResult'(Data,mandatory);\ndecode_disp('ServiceChangeReply',Data) -> 'dec_ServiceChangeReply'(Data,mandatory);\ndecode_disp('ServiceChangeRequest',Data) -> 'dec_ServiceChangeRequest'(Data,mandatory);\ndecode_disp('EventParameter',Data) -> 'dec_EventParameter'(Data,mandatory);\ndecode_disp('EventName',Data) -> 'dec_EventName'(Data,mandatory);\ndecode_disp('ObservedEvent',Data) -> 'dec_ObservedEvent'(Data,mandatory);\ndecode_disp('ObservedEventsDescriptor',Data) -> 'dec_ObservedEventsDescriptor'(Data,mandatory);\ndecode_disp('NotifyReply',Data) -> 'dec_NotifyReply'(Data,mandatory);\ndecode_disp('NotifyRequest',Data) -> 'dec_NotifyRequest'(Data,mandatory);\ndecode_disp('IndAudPackagesDescriptor',Data) -> 'dec_IndAudPackagesDescriptor'(Data,mandatory);\ndecode_disp('IndAudStatisticsDescriptor',Data) -> 'dec_IndAudStatisticsDescriptor'(Data,mandatory);\ndecode_disp('IndAudDigitMapDescriptor',Data) -> 'dec_IndAudDigitMapDescriptor'(Data,mandatory);\ndecode_disp('IndAudSignal',Data) -> 'dec_IndAudSignal'(Data,mandatory);\ndecode_disp('IndAudSeqSigList',Data) -> 'dec_IndAudSeqSigList'(Data,mandatory);\ndecode_disp('IndAudSignalsDescriptor',Data) -> 'dec_IndAudSignalsDescriptor'(Data,mandatory);\ndecode_disp('IndAudEventBufferDescriptor',Data) -> 'dec_IndAudEventBufferDescriptor'(Data,mandatory);\ndecode_disp('IndAudEventsDescriptor',Data) -> 'dec_IndAudEventsDescriptor'(Data,mandatory);\ndecode_disp('IndAudTerminationStateDescriptor',Data) -> 'dec_IndAudTerminationStateDescriptor'(Data,mandatory);\ndecode_disp('IndAudPropertyGroup',Data) -> 'dec_IndAudPropertyGroup'(Data,mandatory);\ndecode_disp('IndAudLocalRemoteDescriptor',Data) -> 'dec_IndAudLocalRemoteDescriptor'(Data,mandatory);\ndecode_disp('IndAudPropertyParm',Data) -> 'dec_IndAudPropertyParm'(Data,mandatory);\ndecode_disp('IndAudLocalControlDescriptor',Data) -> 'dec_IndAudLocalControlDescriptor'(Data,mandatory);\ndecode_disp('IndAudStreamParms',Data) -> 'dec_IndAudStreamParms'(Data,mandatory);\ndecode_disp('IndAudStreamDescriptor',Data) -> 'dec_IndAudStreamDescriptor'(Data,mandatory);\ndecode_disp('IndAudMediaDescriptor',Data) -> 'dec_IndAudMediaDescriptor'(Data,mandatory);\ndecode_disp('IndAuditParameter',Data) -> 'dec_IndAuditParameter'(Data,mandatory);\ndecode_disp('AuditDescriptor',Data) -> 'dec_AuditDescriptor'(Data,mandatory);\ndecode_disp('AuditReturnParameter',Data) -> 'dec_AuditReturnParameter'(Data,mandatory);\ndecode_disp('TerminationAudit',Data) -> 'dec_TerminationAudit'(Data,mandatory);\ndecode_disp('TermListAuditResult',Data) -> 'dec_TermListAuditResult'(Data,mandatory);\ndecode_disp('AuditResult',Data) -> 'dec_AuditResult'(Data,mandatory);\ndecode_disp('AuditReply',Data) -> 'dec_AuditReply'(Data,mandatory);\ndecode_disp('AuditRequest',Data) -> 'dec_AuditRequest'(Data,mandatory);\ndecode_disp('SubtractRequest',Data) -> 'dec_SubtractRequest'(Data,mandatory);\ndecode_disp('AmmsReply',Data) -> 'dec_AmmsReply'(Data,mandatory);\ndecode_disp('AmmDescriptor',Data) -> 'dec_AmmDescriptor'(Data,mandatory);\ndecode_disp('AmmRequest',Data) -> 'dec_AmmRequest'(Data,mandatory);\ndecode_disp('TopologyRequest',Data) -> 'dec_TopologyRequest'(Data,mandatory);\ndecode_disp('CommandReply',Data) -> 'dec_CommandReply'(Data,mandatory);\ndecode_disp('Command',Data) -> 'dec_Command'(Data,mandatory);\ndecode_disp('CommandRequest',Data) -> 'dec_CommandRequest'(Data,mandatory);\ndecode_disp('SelectLogic',Data) -> 'dec_SelectLogic'(Data,mandatory);\ndecode_disp('ContextAttrAuditRequest',Data) -> 'dec_ContextAttrAuditRequest'(Data,mandatory);\ndecode_disp('ContextRequest',Data) -> 'dec_ContextRequest'(Data,mandatory);\ndecode_disp('ActionReply',Data) -> 'dec_ActionReply'(Data,mandatory);\ndecode_disp('ActionRequest',Data) -> 'dec_ActionRequest'(Data,mandatory);\ndecode_disp('ContextID',Data) -> 'dec_ContextID'(Data,mandatory);\ndecode_disp('ErrorText',Data) -> 'dec_ErrorText'(Data,mandatory);\ndecode_disp('ErrorCode',Data) -> 'dec_ErrorCode'(Data,mandatory);\ndecode_disp('ErrorDescriptor',Data) -> 'dec_ErrorDescriptor'(Data,mandatory);\ndecode_disp('TransactionAck',Data) -> 'dec_TransactionAck'(Data,mandatory);\ndecode_disp('TransactionResponseAck',Data) -> 'dec_TransactionResponseAck'(Data,mandatory);\ndecode_disp('SegmentNumber',Data) -> 'dec_SegmentNumber'(Data,mandatory);\ndecode_disp('SegmentReply',Data) -> 'dec_SegmentReply'(Data,mandatory);\ndecode_disp('TransactionReply',Data) -> 'dec_TransactionReply'(Data,mandatory);\ndecode_disp('TransactionPending',Data) -> 'dec_TransactionPending'(Data,mandatory);\ndecode_disp('TransactionRequest',Data) -> 'dec_TransactionRequest'(Data,mandatory);\ndecode_disp('TransactionId',Data) -> 'dec_TransactionId'(Data,mandatory);\ndecode_disp('Transaction',Data) -> 'dec_Transaction'(Data,mandatory);\ndecode_disp('PathName',Data) -> 'dec_PathName'(Data,mandatory);\ndecode_disp('IP6Address',Data) -> 'dec_IP6Address'(Data,mandatory);\ndecode_disp('IP4Address',Data) -> 'dec_IP4Address'(Data,mandatory);\ndecode_disp('DomainName',Data) -> 'dec_DomainName'(Data,mandatory);\ndecode_disp('MId',Data) -> 'dec_MId'(Data,mandatory);\ndecode_disp('Message',Data) -> 'dec_Message'(Data,mandatory);\ndecode_disp('AuthData',Data) -> 'dec_AuthData'(Data,mandatory);\ndecode_disp('SequenceNum',Data) -> 'dec_SequenceNum'(Data,mandatory);\ndecode_disp('SecurityParmIndex',Data) -> 'dec_SecurityParmIndex'(Data,mandatory);\ndecode_disp('AuthenticationHeader',Data) -> 'dec_AuthenticationHeader'(Data,mandatory);\ndecode_disp('MegacoMessage',Data) -> 'dec_MegacoMessage'(Data,mandatory);\ndecode_disp(Type,_Data) -> exit({error,{asn1,{undefined_type,Type}}}).\n\n\n\n\n\ninfo() ->\n case ?MODULE:module_info() of\n MI when is_list(MI) ->\n case lists:keysearch(attributes,1,MI) of\n {value,{_,Attributes}} when is_list(Attributes) ->\n case lists:keysearch(asn1_info,1,Attributes) of\n {value,{_,Info}} when is_list(Info) ->\n Info;\n _ ->\n []\n end;\n _ ->\n []\n end\n end.\n\n'enc_Value'({'Value',Val}) ->\n'enc_Value'(Val);\n\n'enc_Value'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_Value_components'(Val, [])\n].\n'enc_Value_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_Value_components'([H|T], Acc) ->\n'enc_Value_components'(T, [ ?RT_PER:encode_octet_string(no,false,H)\n | Acc]).\n\n\n'dec_Value'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_Value_components'(Num, Bytes1, telltype, []).\n'dec_Value_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_Value_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = ?RT_PER:decode_octet_string(Bytes,no,false)\n,\n 'dec_Value_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_TimeNotation'(Val) ->\nVal1 = ?RT_PER:list_to_record('TimeNotation', Val),\n[\n\n%% attribute number 1 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',8,8,{0,127,notab},element(2,Val1)),\n\n%% attribute number 2 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',8,8,{0,127,notab},element(3,Val1))].\n\n\n'dec_TimeNotation'(Bytes,_) ->\n\n%% attribute number 1 with type IA5String\n{Term1,Bytes1} = ?RT_PER:decode_known_multiplier_string('IA5String',8,8,{0,127,notab},Bytes),\n\n%% attribute number 2 with type IA5String\n{Term2,Bytes2} = ?RT_PER:decode_known_multiplier_string('IA5String',8,8,{0,127,notab},Bytes1),\n{{'TimeNotation',Term1,Term2},Bytes2}.\n\n'enc_H221NonStandard'(Val) ->\nVal1 = ?RT_PER:list_to_record('H221NonStandard', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,255},256,{octets,1}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<255,Tmpval2>=0 ->\n [20,1,Tmpval2- 0];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,255},256,{octets,1}}]\n begin\n Tmpval3=element(3,Val1),\n case Tmpval3 of\n Tmpval4 when Tmpval4=<255,Tmpval4>=0 ->\n [20,1,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end,\n\n%% attribute number 3 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,255},256,{octets,1}}]\n begin\n Tmpval5=element(4,Val1),\n case Tmpval5 of\n Tmpval6 when Tmpval6=<255,Tmpval6>=0 ->\n [20,1,Tmpval6- 0];\n Tmpval6 ->\n exit({error,{value_out_of_bounds,Tmpval6}})\n end\n\n end,\n\n%% attribute number 4 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval7=element(5,Val1),\n case Tmpval7 of\n Tmpval8 when Tmpval8=<65535,Tmpval8>=0 ->\n [20,2,<<(Tmpval8- 0):16>>];\n Tmpval8 ->\n exit({error,{value_out_of_bounds,Tmpval8}})\n end\n\n end].\n\n\n'dec_H221NonStandard'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes1,1),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = begin\n {Tmpterm2,Tmpremain2}=?RT_PER:getoctets(Bytes2,1),\n {Tmpterm2+0,Tmpremain2}\n end,\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes4} = begin\n {Tmpterm3,Tmpremain3}=?RT_PER:getoctets(Bytes3,1),\n {Tmpterm3+0,Tmpremain3}\n end,\n\n%% attribute number 4 with type INTEGER\n{Term4,Bytes5} = begin\n {Tmpterm4,Tmpremain4}=?RT_PER:getoctets(Bytes4,2),\n {Tmpterm4+0,Tmpremain4}\n end,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'H221NonStandard',Term1,Term2,Term3,Term4},Bytes7}.\n\n\n'enc_NonStandardIdentifier'({'NonStandardIdentifier',Val}) ->\n'enc_NonStandardIdentifier'(Val);\n\n'enc_NonStandardIdentifier'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[object,h221NonStandard,experimental],[]}, {3,0}),\ncase element(1,Val) of\nobject ->\n?RT_PER:encode_object_identifier(element(2,Val));\nh221NonStandard ->\n'enc_H221NonStandard'(element(2,Val));\nexperimental ->\n?RT_PER:encode_known_multiplier_string('IA5String',8,8,{0,127,notab},element(2,Val))\nend\n].\n\n\n'dec_NonStandardIdentifier'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,3,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*3 of\n0 -> {object,\n?RT_PER:decode_object_identifier(Bytes2)};\n1 -> {h221NonStandard,\n'dec_H221NonStandard'(Bytes2,telltype)};\n2 -> {experimental,\n?RT_PER:decode_known_multiplier_string('IA5String',8,8,{0,127,notab},Bytes2)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_NonStandardData'(Val) ->\nVal1 = ?RT_PER:list_to_record('NonStandardData', Val),\n[\n\n%% attribute number 1 with type Externaltypereference1038megaco_per_bin_drv_media_gateway_control_v3NonStandardIdentifier\n'enc_NonStandardIdentifier'(element(2,Val1)),\n\n%% attribute number 2 with type OCTET STRING\n ?RT_PER:encode_octet_string(no,false,element(3,Val1))\n].\n\n\n'dec_NonStandardData'(Bytes,_) ->\n\n%% attribute number 1 with type NonStandardIdentifier\n{Term1,Bytes1} = 'dec_NonStandardIdentifier'(Bytes,telltype),\n\n%% attribute number 2 with type OCTET STRING\n{Term2,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,no,false)\n,\n{{'NonStandardData',Term1,Term2},Bytes2}.\n\n'enc_StatisticsParameter'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type Externaltypereference1030megaco_per_bin_drv_media_gateway_control_v3Value\n'enc_Value'(Tmpval2)\nend].\n\n\n'dec_StatisticsParameter'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,4,false)\n,\n\n%% attribute number 2 with type Value\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_Value'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'StatisticsParameter',Term1,Term2},Bytes3}.\n\n\n'enc_StatisticsDescriptor'({'StatisticsDescriptor',Val}) ->\n'enc_StatisticsDescriptor'(Val);\n\n'enc_StatisticsDescriptor'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_StatisticsDescriptor_components'(Val, [])\n].\n'enc_StatisticsDescriptor_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_StatisticsDescriptor_components'([H|T], Acc) ->\n'enc_StatisticsDescriptor_components'(T, ['enc_StatisticsParameter'(H)\n\n | Acc]).\n\n\n'dec_StatisticsDescriptor'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_StatisticsDescriptor_components'(Num, Bytes1, telltype, []).\n'dec_StatisticsDescriptor_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_StatisticsDescriptor_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_StatisticsParameter'(Bytes,telltype),\n 'dec_StatisticsDescriptor_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_PackagesItem'(Val) ->\nVal1 = ?RT_PER:list_to_record('PackagesItem', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval1,Tmpval2] = element(2,Val1),\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end,\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n Tmpval3=element(3,Val1),\n case Tmpval3 of\n Tmpval4 when Tmpval4=<99,Tmpval4>=0 ->\n [10,7,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end].\n\n\n'dec_PackagesItem'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,2,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes2,7),\n {Tmpterm1+0,Tmpremain1}\n end,\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'PackagesItem',Term1,Term2},Bytes5}.\n\n\n'enc_PackagesDescriptor'({'PackagesDescriptor',Val}) ->\n'enc_PackagesDescriptor'(Val);\n\n'enc_PackagesDescriptor'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_PackagesDescriptor_components'(Val, [])\n].\n'enc_PackagesDescriptor_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_PackagesDescriptor_components'([H|T], Acc) ->\n'enc_PackagesDescriptor_components'(T, ['enc_PackagesItem'(H)\n\n | Acc]).\n\n\n'dec_PackagesDescriptor'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_PackagesDescriptor_components'(Num, Bytes1, telltype, []).\n'dec_PackagesDescriptor_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_PackagesDescriptor_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PackagesItem'(Bytes,telltype),\n 'dec_PackagesDescriptor_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_ServiceChangeProfile'(Val) ->\nVal1 = ?RT_PER:list_to_record('ServiceChangeProfile', Val),\n[\n\n%% attribute number 1 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',{1,67},8,{0,127,notab},element(2,Val1))].\n\n\n'dec_ServiceChangeProfile'(Bytes,_) ->\n\n%% attribute number 1 with type IA5String\n{Term1,Bytes1} = ?RT_PER:decode_known_multiplier_string('IA5String',{1,67},8,{0,127,notab},Bytes),\n{{'ServiceChangeProfile',Term1},Bytes1}.\n\n\n'enc_ServiceChangeMethod'({'ServiceChangeMethod',Val}) ->\n'enc_ServiceChangeMethod'(Val);\n\n'enc_ServiceChangeMethod'(Val) ->\ncase Val of\n'failover' -> [0,10,3,0];\n'forced' -> [0,10,3,1];\n'graceful' -> [0,10,3,2];\n'restart' -> [0,10,3,3];\n'disconnected' -> [0,10,3,4];\n'handOff' -> [0,10,3,5];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_ServiceChangeMethod'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,5}}],{{failover,forced,graceful,restart,disconnected,handOff},{}}).\n\n'enc_ServiceChangeResParm'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4,5,6],5,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3MId\n'enc_MId'(Tmpval1)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3ServiceChangeAddress\n'enc_ServiceChangeAddress'(Tmpval2)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<99,Tmpval4>=0 ->\n [10,7,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\nend,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereference993megaco_per_bin_drv_media_gateway_control_v3ServiceChangeProfile\n'enc_ServiceChangeProfile'(Tmpval5)\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 5 with type Externaltypereference994megaco_per_bin_drv_media_gateway_control_v3TimeNotation\n'enc_TimeNotation'(Tmpval6)\nend].\n\n\n'dec_ServiceChangeResParm'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,5), \n%% attribute number 1 with type MId\n{Term1,Bytes3} = case Opt band (1 bsl 4) of\n _Opt1 when _Opt1 > 0 ->'dec_MId'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type ServiceChangeAddress\n{Term2,Bytes4} = case Opt band (1 bsl 3) of\n _Opt2 when _Opt2 > 0 ->'dec_ServiceChangeAddress'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes5} = case Opt band (1 bsl 2) of\n _Opt3 when _Opt3 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes4,7),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type ServiceChangeProfile\n{Term4,Bytes6} = case Opt band (1 bsl 1) of\n _Opt4 when _Opt4 > 0 ->'dec_ServiceChangeProfile'(Bytes5,telltype);\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n\n%% attribute number 5 with type TimeNotation\n{Term5,Bytes7} = case Opt band (1 bsl 0) of\n _Opt5 when _Opt5 > 0 ->'dec_TimeNotation'(Bytes6,telltype);\n0 ->{asn1_NOVALUE,Bytes6}\n\nend,\n{Extensions,Bytes8} = ?RT_PER:getextension(Ext,Bytes7),\nBytes9= ?RT_PER:skipextensions(Bytes8,1,Extensions)\n,\n{{'ServiceChangeResParm',Term1,Term2,Term3,Term4,Term5},Bytes9}.\n\n\n'enc_ServiceChangeAddress'({'ServiceChangeAddress',Val}) ->\n'enc_ServiceChangeAddress'(Val);\n\n'enc_ServiceChangeAddress'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[portNumber,ip4Address,ip6Address,domainName,deviceName,mtpAddress],[]}, {6,0}),\ncase element(1,Val) of\nportNumber ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n case element(2,Val) of \n Tmpval1 when Tmpval1=<65535,Tmpval1>=0 ->\n [20,2,<<(Tmpval1- 0):16>>];\n Tmpval1 ->\n exit({error,{value_out_of_bounds,Tmpval1}})\n end\n;\nip4Address ->\n'enc_IP4Address'(element(2,Val));\nip6Address ->\n'enc_IP6Address'(element(2,Val));\ndomainName ->\n'enc_DomainName'(element(2,Val));\ndeviceName ->\n?RT_PER:encode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},element(2,Val));\nmtpAddress ->\n ?RT_PER:encode_octet_string({2,4},false,element(2,Val))\n\nend\n].\n\n\n'dec_ServiceChangeAddress'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,6,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*6 of\n0 -> {portNumber,\n begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes2,2),\n {Tmpterm1+0,Tmpremain1}\n end};\n1 -> {ip4Address,\n'dec_IP4Address'(Bytes2,telltype)};\n2 -> {ip6Address,\n'dec_IP6Address'(Bytes2,telltype)};\n3 -> {domainName,\n'dec_DomainName'(Bytes2,telltype)};\n4 -> {deviceName,\n?RT_PER:decode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},Bytes2)};\n5 -> {mtpAddress,\n ?RT_PER:decode_octet_string(Bytes2,{2,4},false)\n};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_ServiceChangeParm'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4,5,7,8,9,10],7,Val),\nExtensions = ?RT_PER:fixextensions({ext,10,2},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\n\n%% attribute number 1 with type ENUMERATED\ncase element(2,Val1) of\n'failover' -> [0,10,3,0];\n'forced' -> [0,10,3,1];\n'graceful' -> [0,10,3,2];\n'restart' -> [0,10,3,3];\n'disconnected' -> [0,10,3,4];\n'handOff' -> [0,10,3,5];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type Externaltypereference953megaco_per_bin_drv_media_gateway_control_v3ServiceChangeAddress\n'enc_ServiceChangeAddress'(Tmpval2)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<99,Tmpval4>=0 ->\n [10,7,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\nend,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereference955megaco_per_bin_drv_media_gateway_control_v3ServiceChangeProfile\n'enc_ServiceChangeProfile'(Tmpval5)\nend,\n\n%% attribute number 5 with type Externaltypereference956megaco_per_bin_drv_media_gateway_control_v3Value\n'enc_Value'(element(6,Val1)),\ncase element(7,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 6 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval6)\nend,\ncase element(8,Val1) of\nasn1_NOVALUE -> [];\nTmpval7 ->\n\n%% attribute number 7 with type Externaltypereference969megaco_per_bin_drv_media_gateway_control_v3MId\n'enc_MId'(Tmpval7)\nend,\ncase element(9,Val1) of\nasn1_NOVALUE -> [];\nTmpval8 ->\n\n%% attribute number 8 with type Externaltypereference970megaco_per_bin_drv_media_gateway_control_v3TimeNotation\n'enc_TimeNotation'(Tmpval8)\nend,\ncase element(10,Val1) of\nasn1_NOVALUE -> [];\nTmpval9 ->\n\n%% attribute number 9 with type Externaltypereference971megaco_per_bin_drv_media_gateway_control_v3NonStandardData\n'enc_NonStandardData'(Tmpval9)\nend\n,Extensions\n,\ncase element(11,Val1) of\nasn1_NOVALUE -> [];\nTmpval10 ->\n\n%% attribute number 10 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3AuditDescriptor\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_AuditDescriptor'(Tmpval10)))\nend,\ncase element(12,Val1) of\nasn1_NOVALUE -> [];\nTmpval11 ->\n\n%% attribute number 11 with type NULL\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(?RT_PER:encode_null(Tmpval11)))\nend].\n\n\n'dec_ServiceChangeParm'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,7), \n%% attribute number 1 with type ENUMERATED\n{Term1,Bytes3} = ?RT_PER:decode_enumerated(Bytes2,[{'ValueRange',{0,5}}],{{failover,forced,graceful,restart,disconnected,handOff},{}}),\n\n%% attribute number 2 with type ServiceChangeAddress\n{Term2,Bytes4} = case Opt band (1 bsl 6) of\n _Opt2 when _Opt2 > 0 ->'dec_ServiceChangeAddress'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes5} = case Opt band (1 bsl 5) of\n _Opt3 when _Opt3 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes4,7),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type ServiceChangeProfile\n{Term4,Bytes6} = case Opt band (1 bsl 4) of\n _Opt4 when _Opt4 > 0 ->'dec_ServiceChangeProfile'(Bytes5,telltype);\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n\n%% attribute number 5 with type Value\n{Term5,Bytes7} = 'dec_Value'(Bytes6,telltype),\n\n%% attribute number 6 with type INTEGER\n{Term6,Bytes8} = case Opt band (1 bsl 3) of\n _Opt6 when _Opt6 > 0 ->?RT_PER:decode_constrained_number(Bytes7,{0,4294967295},4294967296);\n0 ->{asn1_NOVALUE,Bytes7}\n\nend,\n\n%% attribute number 7 with type MId\n{Term7,Bytes9} = case Opt band (1 bsl 2) of\n _Opt7 when _Opt7 > 0 ->'dec_MId'(Bytes8,telltype);\n0 ->{asn1_NOVALUE,Bytes8}\n\nend,\n\n%% attribute number 8 with type TimeNotation\n{Term8,Bytes10} = case Opt band (1 bsl 1) of\n _Opt8 when _Opt8 > 0 ->'dec_TimeNotation'(Bytes9,telltype);\n0 ->{asn1_NOVALUE,Bytes9}\n\nend,\n\n%% attribute number 9 with type NonStandardData\n{Term9,Bytes11} = case Opt band (1 bsl 0) of\n _Opt9 when _Opt9 > 0 ->'dec_NonStandardData'(Bytes10,telltype);\n0 ->{asn1_NOVALUE,Bytes10}\n\nend,\n{Extensions,Bytes12} = ?RT_PER:getextension(Ext,Bytes11),\n\n%% attribute number 10 with type AuditDescriptor\n{Term10,Bytes13} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal10,Trem10}=?RT_PER:decode_open_type(Bytes12,[]),\n{TmpValx10,_}='dec_AuditDescriptor'(TmpVal10,telltype), {TmpValx10,Trem10}\nend;\n_ ->\n{asn1_NOVALUE,Bytes12}\n\nend,\n\n%% attribute number 11 with type NULL\n{Term11,Bytes14} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal11,Trem11}=?RT_PER:decode_open_type(Bytes13,[]),\n{TmpValx11,_}=?RT_PER:decode_null(TmpVal11), {TmpValx11,Trem11}\nend;\n_ ->\n{asn1_NOVALUE,Bytes13}\n\nend,\nBytes15= ?RT_PER:skipextensions(Bytes14,3,Extensions)\n,\n{{'ServiceChangeParm',Term1,Term2,Term3,Term4,Term5,Term6,Term7,Term8,Term9,Term10,Term11},Bytes15}.\n\n'enc_DigitMapValue'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,5,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<99,Tmpval3>=0 ->\n [10,7,Tmpval3- 0];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval4 of\n Tmpval5 when Tmpval5=<99,Tmpval5>=0 ->\n [10,7,Tmpval5- 0];\n Tmpval5 ->\n exit({error,{value_out_of_bounds,Tmpval5}})\n end\n\n end\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 3 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval6 of\n Tmpval7 when Tmpval7=<99,Tmpval7>=0 ->\n [10,7,Tmpval7- 0];\n Tmpval7 ->\n exit({error,{value_out_of_bounds,Tmpval7}})\n end\n\n end\nend,\n\n%% attribute number 4 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',no,8,{0,127,notab},element(5,Val1))\n,Extensions\n,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval8 ->\n\n%% attribute number 5 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n case Tmpval8 of\n Tmpval9 when Tmpval9=<99,Tmpval9>=0 ->\n [10,7,Tmpval9- 0];\n Tmpval9 ->\n exit({error,{value_out_of_bounds,Tmpval9}})\n end\n\n end))\nend].\n\n\n'dec_DigitMapValue'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes2,7),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm2,Tmpremain2}=?RT_PER:getbits(Bytes3,7),\n {Tmpterm2+0,Tmpremain2}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 -> begin\n {Tmpterm3,Tmpremain3}=?RT_PER:getbits(Bytes4,7),\n {Tmpterm3+0,Tmpremain3}\n end;\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type IA5String\n{Term4,Bytes6} = ?RT_PER:decode_known_multiplier_string('IA5String',no,8,{0,127,notab},Bytes5),\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\n\n%% attribute number 5 with type INTEGER\n{Term5,Bytes8} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}= begin\n {Tmpterm4,Tmpremain4}=?RT_PER:getbits(TmpVal5,7),\n {Tmpterm4+0,Tmpremain4}\n end, {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\nBytes9= ?RT_PER:skipextensions(Bytes8,2,Extensions)\n,\n{{'DigitMapValue',Term1,Term2,Term3,Term4,Term5},Bytes9}.\n\n\n'enc_DigitMapName'({'DigitMapName',Val}) ->\n'enc_DigitMapName'(Val);\n\n'enc_DigitMapName'(Val) ->\n begin\n [Tmpval1,Tmpval2] = Val,\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end.\n\n\n'dec_DigitMapName'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,2,false)\n.\n\n'enc_DigitMapDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3],2,Val),\n[\nOpt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval2,Tmpval3] = Tmpval1,\n [[10,8,Tmpval2],[10,8,Tmpval3]]\n end\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 2 with type Externaltypereference930megaco_per_bin_drv_media_gateway_control_v3DigitMapValue\n'enc_DigitMapValue'(Tmpval4)\nend].\n\n\n'dec_DigitMapDescriptor'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,2), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = case Opt band (1 bsl 1) of\n _Opt1 when _Opt1 > 0 -> ?RT_PER:decode_octet_string(Bytes1,2,false)\n;\n0 ->{asn1_NOVALUE,Bytes1}\n\nend,\n\n%% attribute number 2 with type DigitMapValue\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_DigitMapValue'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'DigitMapDescriptor',Term1,Term2},Bytes3}.\n\n\n'enc_ModemType'({'ModemType',Val}) ->\n'enc_ModemType'(Val);\n\n'enc_ModemType'(Val) ->\ncase Val of\n'v18' -> [0,10,4,0];\n'v22' -> [0,10,4,1];\n'v22bis' -> [0,10,4,2];\n'v32' -> [0,10,4,3];\n'v32bis' -> [0,10,4,4];\n'v34' -> [0,10,4,5];\n'v90' -> [0,10,4,6];\n'v91' -> [0,10,4,7];\n'synchISDN' -> [0,10,4,8];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_ModemType'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,8}}],{{v18,v22,v22bis,v32,v32bis,v34,v90,v91,synchISDN},{}}).\n\n'enc_ModemDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type SEQUENCE OF\n'enc_ModemDescriptor_mtl'(element(2,Val1)),\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_ModemDescriptor_mpl'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 3 with type Externaltypereference910megaco_per_bin_drv_media_gateway_control_v3NonStandardData\n'enc_NonStandardData'(Tmpval1)\nend].\n\n'enc_ModemDescriptor_mtl'({'ModemDescriptor_mtl',Val}) ->\n'enc_ModemDescriptor_mtl'(Val);\n\n'enc_ModemDescriptor_mtl'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ModemDescriptor_mtl_components'(Val, [])\n].\n'enc_ModemDescriptor_mtl_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ModemDescriptor_mtl_components'([H|T], Acc) ->\n'enc_ModemDescriptor_mtl_components'(T, [case H of\n'v18' -> [0,10,4,0];\n'v22' -> [0,10,4,1];\n'v22bis' -> [0,10,4,2];\n'v32' -> [0,10,4,3];\n'v32bis' -> [0,10,4,4];\n'v34' -> [0,10,4,5];\n'v90' -> [0,10,4,6];\n'v91' -> [0,10,4,7];\n'synchISDN' -> [0,10,4,8];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend | Acc]).\n\n'dec_ModemDescriptor_mtl'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ModemDescriptor_mtl_components'(Num, Bytes1, telltype, []).\n'dec_ModemDescriptor_mtl_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ModemDescriptor_mtl_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = ?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,8}}],{{v18,v22,v22bis,v32,v32bis,v34,v90,v91,synchISDN},{}}),\n 'dec_ModemDescriptor_mtl_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'enc_ModemDescriptor_mpl'({'ModemDescriptor_mpl',Val}) ->\n'enc_ModemDescriptor_mpl'(Val);\n\n'enc_ModemDescriptor_mpl'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ModemDescriptor_mpl_components'(Val, [])\n].\n'enc_ModemDescriptor_mpl_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ModemDescriptor_mpl_components'([H|T], Acc) ->\n'enc_ModemDescriptor_mpl_components'(T, ['enc_PropertyParm'(H)\n\n | Acc]).\n\n'dec_ModemDescriptor_mpl'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ModemDescriptor_mpl_components'(Num, Bytes1, telltype, []).\n'dec_ModemDescriptor_mpl_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ModemDescriptor_mpl_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyParm'(Bytes,telltype),\n 'dec_ModemDescriptor_mpl_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ModemDescriptor'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type SEQUENCE OF\n{Term1,Bytes2} = 'dec_ModemDescriptor_mtl'(Bytes1, telltype),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes3} = 'dec_ModemDescriptor_mpl'(Bytes2, telltype),\n\n%% attribute number 3 with type NonStandardData\n{Term3,Bytes4} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_NonStandardData'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{{'ModemDescriptor',Term1,Term2,Term3},Bytes4}.\n\n\n'enc_RequestID'({'RequestID',Val}) ->\n'enc_RequestID'(Val);\n\n'enc_RequestID'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Val).\n\n\n'dec_RequestID'(Bytes,_) ->\n?RT_PER:decode_constrained_number(Bytes,{0,4294967295},4294967296).\n\n'enc_SigParameter'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval1,Tmpval2] = element(2,Val1),\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end,\n\n%% attribute number 2 with type Externaltypereference891megaco_per_bin_drv_media_gateway_control_v3Value\n'enc_Value'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type CHOICE\n'enc_SigParameter_extraInfo'(Tmpval3)\nend].\n\n'enc_SigParameter_extraInfo'({'SigParameter_extraInfo',Val}) ->\n'enc_SigParameter_extraInfo'(Val);\n\n'enc_SigParameter_extraInfo'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[relation,range,sublist], 3),\ncase element(1,Val) of\nrelation ->\ncase element(2,Val) of\n'greaterThan' -> [0,10,2,0];\n'smallerThan' -> [0,10,2,1];\n'unequalTo' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend;\nrange ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend;\nsublist ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend\nend\n].\n\n'dec_SigParameter_extraInfo'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,3, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {relation,\n?RT_PER:decode_enumerated(Bytes1,[{'ValueRange',{0,2}}],{{greaterThan,smallerThan,unequalTo},{}})};\n1 -> {range,\n?RT_PER:decode_boolean(Bytes1)};\n2 -> {sublist,\n?RT_PER:decode_boolean(Bytes1)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_SigParameter'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,2,false)\n,\n\n%% attribute number 2 with type Value\n{Term2,Bytes4} = 'dec_Value'(Bytes3,telltype),\n\n%% attribute number 3 with type CHOICE\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_SigParameter_extraInfo'(Bytes4, telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'SigParameter',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_NotifyCompletion'({'NotifyCompletion',Val}) ->\n'enc_NotifyCompletion'(Val);\n\n'enc_NotifyCompletion'(Val) ->\n?RT_PER:encode_bit_string(no,Val,[{onTimeOut,0},{onInterruptByEvent,1},{onInterruptByNewSignalDescr,2},{otherReason,3},{onIteration,4}]).\n\n\n'dec_NotifyCompletion'(Bytes,_) ->\n?RT_PER:decode_bit_string(Bytes,[],[{onTimeOut,0},{onInterruptByEvent,1},{onInterruptByNewSignalDescr,2},{otherReason,3},{onIteration,4}]).\n\n\n'enc_SignalName'({'SignalName',Val}) ->\n'enc_SignalName'(Val);\n\n'enc_SignalName'(Val) ->\n begin\n case length(Val) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,Val];\n _ -> exit({error,{value_out_of_bounds,Val}})\n end\n end.\n\n\n'dec_SignalName'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,4,false)\n.\n\n\n'enc_SignalDirection'({'SignalDirection',Val}) ->\n'enc_SignalDirection'(Val);\n\n'enc_SignalDirection'(Val) ->\ncase Val of\n'internal' -> [0,10,2,0];\n'external' -> [0,10,2,1];\n'both' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_SignalDirection'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,2}}],{{internal,external,both},{}}).\n\n\n'enc_SignalType'({'SignalType',Val}) ->\n'enc_SignalType'(Val);\n\n'enc_SignalType'(Val) ->\ncase Val of\n'brief' -> [0,10,2,0];\n'onOff' -> [0,10,2,1];\n'timeOut' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_SignalType'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,2}}],{{brief,onOff,timeOut},{}}).\n\n'enc_Signal'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4,5,6,7],5,Val),\nExtensions = ?RT_PER:fixextensions({ext,8,3},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval2 when Tmpval2 == 4 -> [2,20,Tmpval2,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<65535,Tmpval4>=0 ->\n [20,2,<<(Tmpval4- 0):16>>];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 3 with type ENUMERATED\ncase Tmpval5 of\n'brief' -> [0,10,2,0];\n'onOff' -> [0,10,2,1];\n'timeOut' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend\nend,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 4 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval6 of\n Tmpval7 when Tmpval7=<65535,Tmpval7>=0 ->\n [20,2,<<(Tmpval7- 0):16>>];\n Tmpval7 ->\n exit({error,{value_out_of_bounds,Tmpval7}})\n end\n\n end\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval8 ->\n\n%% attribute number 5 with type BIT STRING\n?RT_PER:encode_bit_string(no,Tmpval8,[{onTimeOut,0},{onInterruptByEvent,1},{onInterruptByNewSignalDescr,2},{otherReason,3},{onIteration,4}])\nend,\ncase element(7,Val1) of\nasn1_NOVALUE -> [];\nTmpval9 ->\n\n%% attribute number 6 with type BOOLEAN\ncase Tmpval9 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval9}}})\nend\nend,\n\n%% attribute number 7 with type SEQUENCE OF\n'enc_Signal_sigParList'(element(8,Val1))\n,Extensions\n,\ncase element(9,Val1) of\nasn1_NOVALUE -> [];\nTmpval10 ->\n\n%% attribute number 8 with type ENUMERATED\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval10 of\n'internal' -> [0,10,2,0];\n'external' -> [0,10,2,1];\n'both' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend))\nend,\ncase element(10,Val1) of\nasn1_NOVALUE -> [];\nTmpval11 ->\n\n%% attribute number 9 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval11)))\nend,\ncase element(11,Val1) of\nasn1_NOVALUE -> [];\nTmpval12 ->\n\n%% attribute number 10 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval12 of\n Tmpval13 when Tmpval13=<65535,Tmpval13>=0 ->\n [20,2,<<(Tmpval13- 0):16>>];\n Tmpval13 ->\n exit({error,{value_out_of_bounds,Tmpval13}})\n end\n\n end))\nend].\n\n'enc_Signal_sigParList'({'Signal_sigParList',Val}) ->\n'enc_Signal_sigParList'(Val);\n\n'enc_Signal_sigParList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_Signal_sigParList_components'(Val, [])\n].\n'enc_Signal_sigParList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_Signal_sigParList_components'([H|T], Acc) ->\n'enc_Signal_sigParList_components'(T, ['enc_SigParameter'(H)\n\n | Acc]).\n\n'dec_Signal_sigParList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_Signal_sigParList_components'(Num, Bytes1, telltype, []).\n'dec_Signal_sigParList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_Signal_sigParList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_SigParameter'(Bytes,telltype),\n 'dec_Signal_sigParList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_Signal'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,5), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 4) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type ENUMERATED\n{Term3,Bytes5} = case Opt band (1 bsl 3) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_enumerated(Bytes4,[{'ValueRange',{0,2}}],{{brief,onOff,timeOut},{}});\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type INTEGER\n{Term4,Bytes6} = case Opt band (1 bsl 2) of\n _Opt4 when _Opt4 > 0 -> begin\n {Tmpterm2,Tmpremain2}=?RT_PER:getoctets(Bytes5,2),\n {Tmpterm2+0,Tmpremain2}\n end;\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n\n%% attribute number 5 with type BIT STRING\n{Term5,Bytes7} = case Opt band (1 bsl 1) of\n _Opt5 when _Opt5 > 0 ->?RT_PER:decode_bit_string(Bytes6,[],[{onTimeOut,0},{onInterruptByEvent,1},{onInterruptByNewSignalDescr,2},{otherReason,3},{onIteration,4}]);\n0 ->{asn1_NOVALUE,Bytes6}\n\nend,\n\n%% attribute number 6 with type BOOLEAN\n{Term6,Bytes8} = case Opt band (1 bsl 0) of\n _Opt6 when _Opt6 > 0 ->?RT_PER:decode_boolean(Bytes7);\n0 ->{asn1_NOVALUE,Bytes7}\n\nend,\n\n%% attribute number 7 with type SEQUENCE OF\n{Term7,Bytes9} = 'dec_Signal_sigParList'(Bytes8, telltype),\n{Extensions,Bytes10} = ?RT_PER:getextension(Ext,Bytes9),\n\n%% attribute number 8 with type ENUMERATED\n{Term8,Bytes11} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal8,Trem8}=?RT_PER:decode_open_type(Bytes10,[]),\n{TmpValx8,_}=?RT_PER:decode_enumerated(TmpVal8,[{'ValueRange',{0,2}}],{{internal,external,both},{}}), {TmpValx8,Trem8}\nend;\n_ ->\n{asn1_NOVALUE,Bytes10}\n\nend,\n\n%% attribute number 9 with type INTEGER\n{Term9,Bytes12} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal9,Trem9}=?RT_PER:decode_open_type(Bytes11,[]),\n{TmpValx9,_}=?RT_PER:decode_constrained_number(TmpVal9,{0,4294967295},4294967296), {TmpValx9,Trem9}\nend;\n_ ->\n{asn1_NOVALUE,Bytes11}\n\nend,\n\n%% attribute number 10 with type INTEGER\n{Term10,Bytes13} = case Extensions of\n <<_:2,1:1,_\/bitstring>> when bit_size(Extensions) >= 3 ->\nbegin\n{TmpVal10,Trem10}=?RT_PER:decode_open_type(Bytes12,[]),\n{TmpValx10,_}= begin\n {Tmpterm3,Tmpremain3}=?RT_PER:getoctets(TmpVal10,2),\n {Tmpterm3+0,Tmpremain3}\n end, {TmpValx10,Trem10}\nend;\n_ ->\n{asn1_NOVALUE,Bytes12}\n\nend,\nBytes14= ?RT_PER:skipextensions(Bytes13,4,Extensions)\n,\n{{'Signal',Term1,Term2,Term3,Term4,Term5,Term6,Term7,Term8,Term9,Term10},Bytes14}.\n\n'enc_SeqSigList'(Val) ->\nVal1 = ?RT_PER:list_to_record('SeqSigList', Val),\n[\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_SeqSigList_signalList'(element(3,Val1))].\n\n'enc_SeqSigList_signalList'({'SeqSigList_signalList',Val}) ->\n'enc_SeqSigList_signalList'(Val);\n\n'enc_SeqSigList_signalList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_SeqSigList_signalList_components'(Val, [])\n].\n'enc_SeqSigList_signalList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_SeqSigList_signalList_components'([H|T], Acc) ->\n'enc_SeqSigList_signalList_components'(T, ['enc_Signal'(H)\n\n | Acc]).\n\n'dec_SeqSigList_signalList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_SeqSigList_signalList_components'(Num, Bytes1, telltype, []).\n'dec_SeqSigList_signalList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_SeqSigList_signalList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_Signal'(Bytes,telltype),\n 'dec_SeqSigList_signalList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_SeqSigList'(Bytes,_) ->\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes1} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes2} = 'dec_SeqSigList_signalList'(Bytes1, telltype),\n{{'SeqSigList',Term1,Term2},Bytes2}.\n\n\n'enc_SignalRequest'({'SignalRequest',Val}) ->\n'enc_SignalRequest'(Val);\n\n'enc_SignalRequest'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[signal,seqSigList],[]}, {2,0}),\ncase element(1,Val) of\nsignal ->\n'enc_Signal'(element(2,Val));\nseqSigList ->\n'enc_SeqSigList'(element(2,Val))\nend\n].\n\n\n'dec_SignalRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,2,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*2 of\n0 -> {signal,\n'dec_Signal'(Bytes2,telltype)};\n1 -> {seqSigList,\n'dec_SeqSigList'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n\n'enc_SignalsDescriptor'({'SignalsDescriptor',Val}) ->\n'enc_SignalsDescriptor'(Val);\n\n'enc_SignalsDescriptor'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_SignalsDescriptor_components'(Val, [])\n].\n'enc_SignalsDescriptor_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_SignalsDescriptor_components'([H|T], Acc) ->\n'enc_SignalsDescriptor_components'(T, ['enc_SignalRequest'(H)\n\n | Acc]).\n\n\n'dec_SignalsDescriptor'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_SignalsDescriptor_components'(Num, Bytes1, telltype, []).\n'dec_SignalsDescriptor_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_SignalsDescriptor_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_SignalRequest'(Bytes,telltype),\n 'dec_SignalsDescriptor_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_EventSpec'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\n\n%% attribute number 3 with type SEQUENCE OF\n'enc_EventSpec_eventParList'(element(4,Val1))].\n\n'enc_EventSpec_eventParList'({'EventSpec_eventParList',Val}) ->\n'enc_EventSpec_eventParList'(Val);\n\n'enc_EventSpec_eventParList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_EventSpec_eventParList_components'(Val, [])\n].\n'enc_EventSpec_eventParList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_EventSpec_eventParList_components'([H|T], Acc) ->\n'enc_EventSpec_eventParList_components'(T, ['enc_EventParameter'(H)\n\n | Acc]).\n\n'dec_EventSpec_eventParList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_EventSpec_eventParList_components'(Num, Bytes1, telltype, []).\n'dec_EventSpec_eventParList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_EventSpec_eventParList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_EventParameter'(Bytes,telltype),\n 'dec_EventSpec_eventParList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_EventSpec'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SEQUENCE OF\n{Term3,Bytes5} = 'dec_EventSpec_eventParList'(Bytes4, telltype),\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'EventSpec',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_EventBufferDescriptor'({'EventBufferDescriptor',Val}) ->\n'enc_EventBufferDescriptor'(Val);\n\n'enc_EventBufferDescriptor'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_EventBufferDescriptor_components'(Val, [])\n].\n'enc_EventBufferDescriptor_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_EventBufferDescriptor_components'([H|T], Acc) ->\n'enc_EventBufferDescriptor_components'(T, ['enc_EventSpec'(H)\n\n | Acc]).\n\n\n'dec_EventBufferDescriptor'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_EventBufferDescriptor_components'(Num, Bytes1, telltype, []).\n'dec_EventBufferDescriptor_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_EventBufferDescriptor_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_EventSpec'(Bytes,telltype),\n 'dec_EventBufferDescriptor_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_SecondRequestedActions'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,2},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type BOOLEAN\ncase Tmpval2 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval2}}})\nend\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3EventDM\n'enc_EventDM'(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereference817megaco_per_bin_drv_media_gateway_control_v3SignalsDescriptor\n'enc_SignalsDescriptor'(Tmpval4)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3NotifyBehaviour\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_NotifyBehaviour'(Tmpval5)))\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 5 with type NULL\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(?RT_PER:encode_null(Tmpval6)))\nend].\n\n\n'dec_SecondRequestedActions'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type BOOLEAN\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_boolean(Bytes2);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type EventDM\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->'dec_EventDM'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SignalsDescriptor\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_SignalsDescriptor'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type NotifyBehaviour\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}='dec_NotifyBehaviour'(TmpVal4,telltype), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\n\n%% attribute number 5 with type NULL\n{Term5,Bytes8} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}=?RT_PER:decode_null(TmpVal5), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\nBytes9= ?RT_PER:skipextensions(Bytes8,3,Extensions)\n,\n{{'SecondRequestedActions',Term1,Term2,Term3,Term4,Term5},Bytes9}.\n\n'enc_SecondRequestedEvent'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3SecondRequestedActions\n'enc_SecondRequestedActions'(Tmpval4)\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_SecondRequestedEvent_evParList'(element(5,Val1))].\n\n'enc_SecondRequestedEvent_evParList'({'SecondRequestedEvent_evParList',Val}) ->\n'enc_SecondRequestedEvent_evParList'(Val);\n\n'enc_SecondRequestedEvent_evParList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_SecondRequestedEvent_evParList_components'(Val, [])\n].\n'enc_SecondRequestedEvent_evParList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_SecondRequestedEvent_evParList_components'([H|T], Acc) ->\n'enc_SecondRequestedEvent_evParList_components'(T, ['enc_EventParameter'(H)\n\n | Acc]).\n\n'dec_SecondRequestedEvent_evParList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_SecondRequestedEvent_evParList_components'(Num, Bytes1, telltype, []).\n'dec_SecondRequestedEvent_evParList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_SecondRequestedEvent_evParList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_EventParameter'(Bytes,telltype),\n 'dec_SecondRequestedEvent_evParList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_SecondRequestedEvent'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SecondRequestedActions\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_SecondRequestedActions'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes6} = 'dec_SecondRequestedEvent_evParList'(Bytes5, telltype),\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\nBytes8= ?RT_PER:skipextensions(Bytes7,1,Extensions)\n,\n{{'SecondRequestedEvent',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_SecondEventsDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval1)\nend,\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_SecondEventsDescriptor_eventList'(element(3,Val1))].\n\n'enc_SecondEventsDescriptor_eventList'({'SecondEventsDescriptor_eventList',Val}) ->\n'enc_SecondEventsDescriptor_eventList'(Val);\n\n'enc_SecondEventsDescriptor_eventList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_SecondEventsDescriptor_eventList_components'(Val, [])\n].\n'enc_SecondEventsDescriptor_eventList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_SecondEventsDescriptor_eventList_components'([H|T], Acc) ->\n'enc_SecondEventsDescriptor_eventList_components'(T, ['enc_SecondRequestedEvent'(H)\n\n | Acc]).\n\n'dec_SecondEventsDescriptor_eventList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_SecondEventsDescriptor_eventList_components'(Num, Bytes1, telltype, []).\n'dec_SecondEventsDescriptor_eventList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_SecondEventsDescriptor_eventList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_SecondRequestedEvent'(Bytes,telltype),\n 'dec_SecondEventsDescriptor_eventList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_SecondEventsDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes4} = 'dec_SecondEventsDescriptor_eventList'(Bytes3, telltype),\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'SecondEventsDescriptor',Term1,Term2},Bytes6}.\n\n\n'enc_EventDM'({'EventDM',Val}) ->\n'enc_EventDM'(Val);\n\n'enc_EventDM'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[digitMapName,digitMapValue], 2),\ncase element(1,Val) of\ndigitMapName ->\n begin\n [Tmpval1,Tmpval2] = element(2,Val),\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end;\ndigitMapValue ->\n'enc_DigitMapValue'(element(2,Val))\nend\n].\n\n\n'dec_EventDM'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {digitMapName,\n ?RT_PER:decode_octet_string(Bytes1,2,false)\n};\n1 -> {digitMapValue,\n'dec_DigitMapValue'(Bytes1,telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_RequestedActions'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4,5],4,Val),\nExtensions = ?RT_PER:fixextensions({ext,5,2},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type BOOLEAN\ncase Tmpval2 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval2}}})\nend\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereference783megaco_per_bin_drv_media_gateway_control_v3EventDM\n'enc_EventDM'(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereference784megaco_per_bin_drv_media_gateway_control_v3SecondEventsDescriptor\n'enc_SecondEventsDescriptor'(Tmpval4)\nend,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereference785megaco_per_bin_drv_media_gateway_control_v3SignalsDescriptor\n'enc_SignalsDescriptor'(Tmpval5)\nend\n,Extensions\n,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 5 with type Externaltypereference787megaco_per_bin_drv_media_gateway_control_v3NotifyBehaviour\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_NotifyBehaviour'(Tmpval6)))\nend,\ncase element(7,Val1) of\nasn1_NOVALUE -> [];\nTmpval7 ->\n\n%% attribute number 6 with type NULL\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(?RT_PER:encode_null(Tmpval7)))\nend].\n\n\n'dec_RequestedActions'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,4), \n%% attribute number 1 with type BOOLEAN\n{Term1,Bytes3} = case Opt band (1 bsl 3) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_boolean(Bytes2);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type EventDM\n{Term2,Bytes4} = case Opt band (1 bsl 2) of\n _Opt2 when _Opt2 > 0 ->'dec_EventDM'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SecondEventsDescriptor\n{Term3,Bytes5} = case Opt band (1 bsl 1) of\n _Opt3 when _Opt3 > 0 ->'dec_SecondEventsDescriptor'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type SignalsDescriptor\n{Term4,Bytes6} = case Opt band (1 bsl 0) of\n _Opt4 when _Opt4 > 0 ->'dec_SignalsDescriptor'(Bytes5,telltype);\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\n\n%% attribute number 5 with type NotifyBehaviour\n{Term5,Bytes8} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}='dec_NotifyBehaviour'(TmpVal5,telltype), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\n\n%% attribute number 6 with type NULL\n{Term6,Bytes9} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal6,Trem6}=?RT_PER:decode_open_type(Bytes8,[]),\n{TmpValx6,_}=?RT_PER:decode_null(TmpVal6), {TmpValx6,Trem6}\nend;\n_ ->\n{asn1_NOVALUE,Bytes8}\n\nend,\nBytes10= ?RT_PER:skipextensions(Bytes9,3,Extensions)\n,\n{{'RequestedActions',Term1,Term2,Term3,Term4,Term5,Term6},Bytes10}.\n\n\n'enc_NotifyBehaviour'({'NotifyBehaviour',Val}) ->\n'enc_NotifyBehaviour'(Val);\n\n'enc_NotifyBehaviour'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[notifyImmediate,notifyRegulated,neverNotify],[]}, {3,0}),\ncase element(1,Val) of\nnotifyImmediate ->\n?RT_PER:encode_null(element(2,Val));\nnotifyRegulated ->\n'enc_RegulatedEmbeddedDescriptor'(element(2,Val));\nneverNotify ->\n?RT_PER:encode_null(element(2,Val))\nend\n].\n\n\n'dec_NotifyBehaviour'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,3,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*3 of\n0 -> {notifyImmediate,\n?RT_PER:decode_null(Bytes2)};\n1 -> {notifyRegulated,\n'dec_RegulatedEmbeddedDescriptor'(Bytes2,telltype)};\n2 -> {neverNotify,\n?RT_PER:decode_null(Bytes2)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_RegulatedEmbeddedDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3],2,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3SecondEventsDescriptor\n'enc_SecondEventsDescriptor'(Tmpval1)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type Externaltypereference768megaco_per_bin_drv_media_gateway_control_v3SignalsDescriptor\n'enc_SignalsDescriptor'(Tmpval2)\nend].\n\n\n'dec_RegulatedEmbeddedDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type SecondEventsDescriptor\n{Term1,Bytes3} = case Opt band (1 bsl 1) of\n _Opt1 when _Opt1 > 0 ->'dec_SecondEventsDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type SignalsDescriptor\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_SignalsDescriptor'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'RegulatedEmbeddedDescriptor',Term1,Term2},Bytes6}.\n\n'enc_RequestedEvent'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereference760megaco_per_bin_drv_media_gateway_control_v3RequestedActions\n'enc_RequestedActions'(Tmpval4)\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_RequestedEvent_evParList'(element(5,Val1))].\n\n'enc_RequestedEvent_evParList'({'RequestedEvent_evParList',Val}) ->\n'enc_RequestedEvent_evParList'(Val);\n\n'enc_RequestedEvent_evParList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_RequestedEvent_evParList_components'(Val, [])\n].\n'enc_RequestedEvent_evParList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_RequestedEvent_evParList_components'([H|T], Acc) ->\n'enc_RequestedEvent_evParList_components'(T, ['enc_EventParameter'(H)\n\n | Acc]).\n\n'dec_RequestedEvent_evParList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_RequestedEvent_evParList_components'(Num, Bytes1, telltype, []).\n'dec_RequestedEvent_evParList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_RequestedEvent_evParList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_EventParameter'(Bytes,telltype),\n 'dec_RequestedEvent_evParList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_RequestedEvent'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type RequestedActions\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_RequestedActions'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes6} = 'dec_RequestedEvent_evParList'(Bytes5, telltype),\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\nBytes8= ?RT_PER:skipextensions(Bytes7,1,Extensions)\n,\n{{'RequestedEvent',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_EventsDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval1)\nend,\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_EventsDescriptor_eventList'(element(3,Val1))].\n\n'enc_EventsDescriptor_eventList'({'EventsDescriptor_eventList',Val}) ->\n'enc_EventsDescriptor_eventList'(Val);\n\n'enc_EventsDescriptor_eventList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_EventsDescriptor_eventList_components'(Val, [])\n].\n'enc_EventsDescriptor_eventList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_EventsDescriptor_eventList_components'([H|T], Acc) ->\n'enc_EventsDescriptor_eventList_components'(T, ['enc_RequestedEvent'(H)\n\n | Acc]).\n\n'dec_EventsDescriptor_eventList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_EventsDescriptor_eventList_components'(Num, Bytes1, telltype, []).\n'dec_EventsDescriptor_eventList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_EventsDescriptor_eventList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_RequestedEvent'(Bytes,telltype),\n 'dec_EventsDescriptor_eventList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_EventsDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes4} = 'dec_EventsDescriptor_eventList'(Bytes3, telltype),\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'EventsDescriptor',Term1,Term2},Bytes6}.\n\n\n'enc_StreamID'({'StreamID',Val}) ->\n'enc_StreamID'(Val);\n\n'enc_StreamID'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n case Val of \n Tmpval1 when Tmpval1=<65535,Tmpval1>=0 ->\n [20,2,<<(Tmpval1- 0):16>>];\n Tmpval1 ->\n exit({error,{value_out_of_bounds,Tmpval1}})\n end\n.\n\n\n'dec_StreamID'(Bytes,_) ->\n begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end.\n\n\n'enc_MuxType'({'MuxType',Val}) ->\n'enc_MuxType'(Val);\n\n'enc_MuxType'(Val) ->\ncase Val of\n'h221' -> [0,10,2,0];\n'h223' -> [0,10,2,1];\n'h226' -> [0,10,2,2];\n'v76' -> [0,10,2,3];\n'nx64k' -> [1,?RT_PER:encode_small_number(0)];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_MuxType'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,3}}],{{h221,h223,h226,v76},{nx64k}}).\n\n'enc_MuxDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type ENUMERATED\ncase element(2,Val1) of\n'h221' -> [0,10,2,0];\n'h223' -> [0,10,2,1];\n'h226' -> [0,10,2,2];\n'v76' -> [0,10,2,3];\n'nx64k' -> [1,?RT_PER:encode_small_number(0)];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend,\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_MuxDescriptor_termList'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 3 with type Externaltypereference731megaco_per_bin_drv_media_gateway_control_v3NonStandardData\n'enc_NonStandardData'(Tmpval1)\nend].\n\n'enc_MuxDescriptor_termList'({'MuxDescriptor_termList',Val}) ->\n'enc_MuxDescriptor_termList'(Val);\n\n'enc_MuxDescriptor_termList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_MuxDescriptor_termList_components'(Val, [])\n].\n'enc_MuxDescriptor_termList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_MuxDescriptor_termList_components'([H|T], Acc) ->\n'enc_MuxDescriptor_termList_components'(T, ['enc_TerminationID'(H)\n\n | Acc]).\n\n'dec_MuxDescriptor_termList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_MuxDescriptor_termList_components'(Num, Bytes1, telltype, []).\n'dec_MuxDescriptor_termList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_MuxDescriptor_termList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_TerminationID'(Bytes,telltype),\n 'dec_MuxDescriptor_termList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_MuxDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type ENUMERATED\n{Term1,Bytes3} = ?RT_PER:decode_enumerated(Bytes2,[{'ValueRange',{0,3}}],{{h221,h223,h226,v76},{nx64k}}),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes4} = 'dec_MuxDescriptor_termList'(Bytes3, telltype),\n\n%% attribute number 3 with type NonStandardData\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_NonStandardData'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'MuxDescriptor',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_ServiceState'({'ServiceState',Val}) ->\n'enc_ServiceState'(Val);\n\n'enc_ServiceState'(Val) ->\ncase Val of\n'test' -> [0,10,2,0];\n'outOfSvc' -> [0,10,2,1];\n'inSvc' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_ServiceState'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,2}}],{{test,outOfSvc,inSvc},{}}).\n\n\n'enc_EventBufferControl'({'EventBufferControl',Val}) ->\n'enc_EventBufferControl'(Val);\n\n'enc_EventBufferControl'(Val) ->\ncase Val of\n'off' -> [0,0];\n'lockStep' -> [0,1];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_EventBufferControl'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,1}}],{{off,lockStep},{}}).\n\n'enc_TerminationStateDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type SEQUENCE OF\n'enc_TerminationStateDescriptor_propertyParms'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type ENUMERATED\ncase Tmpval1 of\n'off' -> [0,0];\n'lockStep' -> [0,1];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type ENUMERATED\ncase Tmpval2 of\n'test' -> [0,10,2,0];\n'outOfSvc' -> [0,10,2,1];\n'inSvc' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend\nend].\n\n'enc_TerminationStateDescriptor_propertyParms'({'TerminationStateDescriptor_propertyParms',Val}) ->\n'enc_TerminationStateDescriptor_propertyParms'(Val);\n\n'enc_TerminationStateDescriptor_propertyParms'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TerminationStateDescriptor_propertyParms_components'(Val, [])\n].\n'enc_TerminationStateDescriptor_propertyParms_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TerminationStateDescriptor_propertyParms_components'([H|T], Acc) ->\n'enc_TerminationStateDescriptor_propertyParms_components'(T, ['enc_PropertyParm'(H)\n\n | Acc]).\n\n'dec_TerminationStateDescriptor_propertyParms'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TerminationStateDescriptor_propertyParms_components'(Num, Bytes1, telltype, []).\n'dec_TerminationStateDescriptor_propertyParms_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TerminationStateDescriptor_propertyParms_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyParm'(Bytes,telltype),\n 'dec_TerminationStateDescriptor_propertyParms_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_TerminationStateDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type SEQUENCE OF\n{Term1,Bytes3} = 'dec_TerminationStateDescriptor_propertyParms'(Bytes2, telltype),\n\n%% attribute number 2 with type ENUMERATED\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_enumerated(Bytes3,[{'ValueRange',{0,1}}],{{off,lockStep},{}});\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type ENUMERATED\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_enumerated(Bytes4,[{'ValueRange',{0,2}}],{{test,outOfSvc,inSvc},{}});\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'TerminationStateDescriptor',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_PropertyGroup'({'PropertyGroup',Val}) ->\n'enc_PropertyGroup'(Val);\n\n'enc_PropertyGroup'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_PropertyGroup_components'(Val, [])\n].\n'enc_PropertyGroup_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_PropertyGroup_components'([H|T], Acc) ->\n'enc_PropertyGroup_components'(T, ['enc_PropertyParm'(H)\n\n | Acc]).\n\n\n'dec_PropertyGroup'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_PropertyGroup_components'(Num, Bytes1, telltype, []).\n'dec_PropertyGroup_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_PropertyGroup_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyParm'(Bytes,telltype),\n 'dec_PropertyGroup_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_LocalRemoteDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('LocalRemoteDescriptor', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type SEQUENCE OF\n'enc_LocalRemoteDescriptor_propGrps'(element(2,Val1))].\n\n'enc_LocalRemoteDescriptor_propGrps'({'LocalRemoteDescriptor_propGrps',Val}) ->\n'enc_LocalRemoteDescriptor_propGrps'(Val);\n\n'enc_LocalRemoteDescriptor_propGrps'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_LocalRemoteDescriptor_propGrps_components'(Val, [])\n].\n'enc_LocalRemoteDescriptor_propGrps_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_LocalRemoteDescriptor_propGrps_components'([H|T], Acc) ->\n'enc_LocalRemoteDescriptor_propGrps_components'(T, ['enc_PropertyGroup'(H)\n\n | Acc]).\n\n'dec_LocalRemoteDescriptor_propGrps'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_LocalRemoteDescriptor_propGrps_components'(Num, Bytes1, telltype, []).\n'dec_LocalRemoteDescriptor_propGrps_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_LocalRemoteDescriptor_propGrps_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyGroup'(Bytes,telltype),\n 'dec_LocalRemoteDescriptor_propGrps_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_LocalRemoteDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type SEQUENCE OF\n{Term1,Bytes2} = 'dec_LocalRemoteDescriptor_propGrps'(Bytes1, telltype),\n{Extensions,Bytes3} = ?RT_PER:getextension(Ext,Bytes2),\nBytes4= ?RT_PER:skipextensions(Bytes3,1,Extensions)\n,\n{{'LocalRemoteDescriptor',Term1},Bytes4}.\n\n\n'enc_Relation'({'Relation',Val}) ->\n'enc_Relation'(Val);\n\n'enc_Relation'(Val) ->\ncase Val of\n'greaterThan' -> [0,10,2,0];\n'smallerThan' -> [0,10,2,1];\n'unequalTo' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_Relation'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,2}}],{{greaterThan,smallerThan,unequalTo},{}}).\n\n\n'enc_PkgdName'({'PkgdName',Val}) ->\n'enc_PkgdName'(Val);\n\n'enc_PkgdName'(Val) ->\n begin\n case length(Val) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,Val];\n _ -> exit({error,{value_out_of_bounds,Val}})\n end\n end.\n\n\n'dec_PkgdName'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,4,false)\n.\n\n\n'enc_Name'({'Name',Val}) ->\n'enc_Name'(Val);\n\n'enc_Name'(Val) ->\n begin\n [Tmpval1,Tmpval2] = Val,\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end.\n\n\n'dec_Name'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,2,false)\n.\n\n'enc_PropertyParm'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_PropertyParm_value'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type CHOICE\n'enc_PropertyParm_extraInfo'(Tmpval2)\nend].\n\n'enc_PropertyParm_value'({'PropertyParm_value',Val}) ->\n'enc_PropertyParm_value'(Val);\n\n'enc_PropertyParm_value'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_PropertyParm_value_components'(Val, [])\n].\n'enc_PropertyParm_value_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_PropertyParm_value_components'([H|T], Acc) ->\n'enc_PropertyParm_value_components'(T, [ ?RT_PER:encode_octet_string(no,false,H)\n | Acc]).\n\n'dec_PropertyParm_value'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_PropertyParm_value_components'(Num, Bytes1, telltype, []).\n'dec_PropertyParm_value_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_PropertyParm_value_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = ?RT_PER:decode_octet_string(Bytes,no,false)\n,\n 'dec_PropertyParm_value_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'enc_PropertyParm_extraInfo'({'PropertyParm_extraInfo',Val}) ->\n'enc_PropertyParm_extraInfo'(Val);\n\n'enc_PropertyParm_extraInfo'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[relation,range,sublist], 3),\ncase element(1,Val) of\nrelation ->\ncase element(2,Val) of\n'greaterThan' -> [0,10,2,0];\n'smallerThan' -> [0,10,2,1];\n'unequalTo' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend;\nrange ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend;\nsublist ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend\nend\n].\n\n'dec_PropertyParm_extraInfo'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,3, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {relation,\n?RT_PER:decode_enumerated(Bytes1,[{'ValueRange',{0,2}}],{{greaterThan,smallerThan,unequalTo},{}})};\n1 -> {range,\n?RT_PER:decode_boolean(Bytes1)};\n2 -> {sublist,\n?RT_PER:decode_boolean(Bytes1)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_PropertyParm'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes4} = 'dec_PropertyParm_value'(Bytes3, telltype),\n\n%% attribute number 3 with type CHOICE\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_PropertyParm_extraInfo'(Bytes4, telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'PropertyParm',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_StreamMode'({'StreamMode',Val}) ->\n'enc_StreamMode'(Val);\n\n'enc_StreamMode'(Val) ->\ncase Val of\n'sendOnly' -> [0,10,3,0];\n'recvOnly' -> [0,10,3,1];\n'sendRecv' -> [0,10,3,2];\n'inactive' -> [0,10,3,3];\n'loopBack' -> [0,10,3,4];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend.\n\n\n'dec_StreamMode'(Bytes,_) ->\n?RT_PER:decode_enumerated(Bytes,[{'ValueRange',{0,4}}],{{sendOnly,recvOnly,sendRecv,inactive,loopBack},{}}).\n\n'enc_LocalControlDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type ENUMERATED\ncase Tmpval1 of\n'sendOnly' -> [0,10,3,0];\n'recvOnly' -> [0,10,3,1];\n'sendRecv' -> [0,10,3,2];\n'inactive' -> [0,10,3,3];\n'loopBack' -> [0,10,3,4];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type BOOLEAN\ncase Tmpval2 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval2}}})\nend\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type BOOLEAN\ncase Tmpval3 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval3}}})\nend\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_LocalControlDescriptor_propertyParms'(element(5,Val1))].\n\n'enc_LocalControlDescriptor_propertyParms'({'LocalControlDescriptor_propertyParms',Val}) ->\n'enc_LocalControlDescriptor_propertyParms'(Val);\n\n'enc_LocalControlDescriptor_propertyParms'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_LocalControlDescriptor_propertyParms_components'(Val, [])\n].\n'enc_LocalControlDescriptor_propertyParms_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_LocalControlDescriptor_propertyParms_components'([H|T], Acc) ->\n'enc_LocalControlDescriptor_propertyParms_components'(T, ['enc_PropertyParm'(H)\n\n | Acc]).\n\n'dec_LocalControlDescriptor_propertyParms'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_LocalControlDescriptor_propertyParms_components'(Num, Bytes1, telltype, []).\n'dec_LocalControlDescriptor_propertyParms_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_LocalControlDescriptor_propertyParms_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyParm'(Bytes,telltype),\n 'dec_LocalControlDescriptor_propertyParms_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_LocalControlDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type ENUMERATED\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_enumerated(Bytes2,[{'ValueRange',{0,4}}],{{sendOnly,recvOnly,sendRecv,inactive,loopBack},{}});\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type BOOLEAN\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_boolean(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type BOOLEAN\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_boolean(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes6} = 'dec_LocalControlDescriptor_propertyParms'(Bytes5, telltype),\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\nBytes8= ?RT_PER:skipextensions(Bytes7,1,Extensions)\n,\n{{'LocalControlDescriptor',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_StreamParms'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type Externaltypereference613megaco_per_bin_drv_media_gateway_control_v3LocalControlDescriptor\n'enc_LocalControlDescriptor'(Tmpval2)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereference614megaco_per_bin_drv_media_gateway_control_v3LocalRemoteDescriptor\n'enc_LocalRemoteDescriptor'(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereference615megaco_per_bin_drv_media_gateway_control_v3LocalRemoteDescriptor\n'enc_LocalRemoteDescriptor'(Tmpval4)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereference617megaco_per_bin_drv_media_gateway_control_v3StatisticsDescriptor\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_StatisticsDescriptor'(Tmpval5)))\nend].\n\n\n'dec_StreamParms'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type LocalControlDescriptor\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 ->'dec_LocalControlDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type LocalRemoteDescriptor\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->'dec_LocalRemoteDescriptor'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type LocalRemoteDescriptor\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_LocalRemoteDescriptor'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type StatisticsDescriptor\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}='dec_StatisticsDescriptor'(TmpVal4,telltype), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\nBytes8= ?RT_PER:skipextensions(Bytes7,2,Extensions)\n,\n{{'StreamParms',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_StreamDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('StreamDescriptor', Val),\n[\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\n\n%% attribute number 2 with type Externaltypereference608megaco_per_bin_drv_media_gateway_control_v3StreamParms\n'enc_StreamParms'(element(3,Val1))].\n\n\n'dec_StreamDescriptor'(Bytes,_) ->\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes1} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type StreamParms\n{Term2,Bytes2} = 'dec_StreamParms'(Bytes1,telltype),\n{{'StreamDescriptor',Term1,Term2},Bytes2}.\n\n'enc_MediaDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3],2,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type Externaltypereference596megaco_per_bin_drv_media_gateway_control_v3TerminationStateDescriptor\n'enc_TerminationStateDescriptor'(Tmpval1)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type CHOICE\n'enc_MediaDescriptor_streams'(Tmpval2)\nend].\n\n'enc_MediaDescriptor_streams'({'MediaDescriptor_streams',Val}) ->\n'enc_MediaDescriptor_streams'(Val);\n\n'enc_MediaDescriptor_streams'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[oneStream,multiStream], 2),\ncase element(1,Val) of\noneStream ->\n'enc_StreamParms'(element(2,Val));\nmultiStream ->\n'enc_MediaDescriptor_streams_multiStream'(element(2,Val))\nend\n].\n\n'enc_MediaDescriptor_streams_multiStream'({'MediaDescriptor_streams_multiStream',Val}) ->\n'enc_MediaDescriptor_streams_multiStream'(Val);\n\n'enc_MediaDescriptor_streams_multiStream'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_MediaDescriptor_streams_multiStream_components'(Val, [])\n].\n'enc_MediaDescriptor_streams_multiStream_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_MediaDescriptor_streams_multiStream_components'([H|T], Acc) ->\n'enc_MediaDescriptor_streams_multiStream_components'(T, ['enc_StreamDescriptor'(H)\n\n | Acc]).\n\n'dec_MediaDescriptor_streams_multiStream'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_MediaDescriptor_streams_multiStream_components'(Num, Bytes1, telltype, []).\n'dec_MediaDescriptor_streams_multiStream_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_MediaDescriptor_streams_multiStream_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_StreamDescriptor'(Bytes,telltype),\n 'dec_MediaDescriptor_streams_multiStream_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'dec_MediaDescriptor_streams'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {oneStream,\n'dec_StreamParms'(Bytes1,telltype)};\n1 -> {multiStream,\n'dec_MediaDescriptor_streams_multiStream'(Bytes1, telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_MediaDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type TerminationStateDescriptor\n{Term1,Bytes3} = case Opt band (1 bsl 1) of\n _Opt1 when _Opt1 > 0 ->'dec_TerminationStateDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type CHOICE\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_MediaDescriptor_streams'(Bytes3, telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'MediaDescriptor',Term1,Term2},Bytes6}.\n\n\n'enc_TerminationIDList'({'TerminationIDList',Val}) ->\n'enc_TerminationIDList'(Val);\n\n'enc_TerminationIDList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TerminationIDList_components'(Val, [])\n].\n'enc_TerminationIDList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TerminationIDList_components'([H|T], Acc) ->\n'enc_TerminationIDList_components'(T, ['enc_TerminationID'(H)\n\n | Acc]).\n\n\n'dec_TerminationIDList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TerminationIDList_components'(Num, Bytes1, telltype, []).\n'dec_TerminationIDList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TerminationIDList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_TerminationID'(Bytes,telltype),\n 'dec_TerminationIDList_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_TerminationID'(Val) ->\nVal1 = ?RT_PER:list_to_record('TerminationID', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type SEQUENCE OF\n'enc_TerminationID_wildcard'(element(2,Val1)),\n\n%% attribute number 2 with type OCTET STRING\n ?RT_PER:encode_octet_string({1,8},false,element(3,Val1))\n].\n\n'enc_TerminationID_wildcard'({'TerminationID_wildcard',Val}) ->\n'enc_TerminationID_wildcard'(Val);\n\n'enc_TerminationID_wildcard'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TerminationID_wildcard_components'(Val, [])\n].\n'enc_TerminationID_wildcard_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TerminationID_wildcard_components'([H|T], Acc) ->\n'enc_TerminationID_wildcard_components'(T, [ begin\n [Tmpval1] = H,\n [10,8,Tmpval1]\n end | Acc]).\n\n'dec_TerminationID_wildcard'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TerminationID_wildcard_components'(Num, Bytes1, telltype, []).\n'dec_TerminationID_wildcard_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TerminationID_wildcard_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = ?RT_PER:decode_octet_string(Bytes,1,false)\n,\n 'dec_TerminationID_wildcard_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_TerminationID'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type SEQUENCE OF\n{Term1,Bytes2} = 'dec_TerminationID_wildcard'(Bytes1, telltype),\n\n%% attribute number 2 with type OCTET STRING\n{Term2,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,{1,8},false)\n,\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'TerminationID',Term1,Term2},Bytes5}.\n\n\n'enc_WildcardField'({'WildcardField',Val}) ->\n'enc_WildcardField'(Val);\n\n'enc_WildcardField'(Val) ->\n begin\n [Tmpval1] = Val,\n [10,8,Tmpval1]\n end.\n\n\n'dec_WildcardField'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,1,false)\n.\n\n\n'enc_ServiceChangeResult'({'ServiceChangeResult',Val}) ->\n'enc_ServiceChangeResult'(Val);\n\n'enc_ServiceChangeResult'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[errorDescriptor,serviceChangeResParms], 2),\ncase element(1,Val) of\nerrorDescriptor ->\n'enc_ErrorDescriptor'(element(2,Val));\nserviceChangeResParms ->\n'enc_ServiceChangeResParm'(element(2,Val))\nend\n].\n\n\n'dec_ServiceChangeResult'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {errorDescriptor,\n'dec_ErrorDescriptor'(Bytes1,telltype)};\n1 -> {serviceChangeResParms,\n'dec_ServiceChangeResParm'(Bytes1,telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_ServiceChangeReply'(Val) ->\nVal1 = ?RT_PER:list_to_record('ServiceChangeReply', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type Externaltypereference568megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference569megaco_per_bin_drv_media_gateway_control_v3ServiceChangeResult\n'enc_ServiceChangeResult'(element(3,Val1))].\n\n\n'dec_ServiceChangeReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes2} = 'dec_TerminationIDList'(Bytes1,telltype),\n\n%% attribute number 2 with type ServiceChangeResult\n{Term2,Bytes3} = 'dec_ServiceChangeResult'(Bytes2,telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'ServiceChangeReply',Term1,Term2},Bytes5}.\n\n'enc_ServiceChangeRequest'(Val) ->\nVal1 = ?RT_PER:list_to_record('ServiceChangeRequest', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type Externaltypereference561megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference562megaco_per_bin_drv_media_gateway_control_v3ServiceChangeParm\n'enc_ServiceChangeParm'(element(3,Val1))].\n\n\n'dec_ServiceChangeRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes2} = 'dec_TerminationIDList'(Bytes1,telltype),\n\n%% attribute number 2 with type ServiceChangeParm\n{Term2,Bytes3} = 'dec_ServiceChangeParm'(Bytes2,telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'ServiceChangeRequest',Term1,Term2},Bytes5}.\n\n'enc_EventParameter'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval1,Tmpval2] = element(2,Val1),\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end,\n\n%% attribute number 2 with type Externaltypereference547megaco_per_bin_drv_media_gateway_control_v3Value\n'enc_Value'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type CHOICE\n'enc_EventParameter_extraInfo'(Tmpval3)\nend].\n\n'enc_EventParameter_extraInfo'({'EventParameter_extraInfo',Val}) ->\n'enc_EventParameter_extraInfo'(Val);\n\n'enc_EventParameter_extraInfo'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[relation,range,sublist], 3),\ncase element(1,Val) of\nrelation ->\ncase element(2,Val) of\n'greaterThan' -> [0,10,2,0];\n'smallerThan' -> [0,10,2,1];\n'unequalTo' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend;\nrange ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend;\nsublist ->\ncase element(2,Val) of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,element(2,Val)}}})\nend\nend\n].\n\n'dec_EventParameter_extraInfo'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,3, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {relation,\n?RT_PER:decode_enumerated(Bytes1,[{'ValueRange',{0,2}}],{{greaterThan,smallerThan,unequalTo},{}})};\n1 -> {range,\n?RT_PER:decode_boolean(Bytes1)};\n2 -> {sublist,\n?RT_PER:decode_boolean(Bytes1)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_EventParameter'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,2,false)\n,\n\n%% attribute number 2 with type Value\n{Term2,Bytes4} = 'dec_Value'(Bytes3,telltype),\n\n%% attribute number 3 with type CHOICE\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_EventParameter_extraInfo'(Bytes4, telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'EventParameter',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_EventName'({'EventName',Val}) ->\n'enc_EventName'(Val);\n\n'enc_EventName'(Val) ->\n begin\n case length(Val) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,Val];\n _ -> exit({error,{value_out_of_bounds,Val}})\n end\n end.\n\n\n'dec_EventName'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,4,false)\n.\n\n'enc_ObservedEvent'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,5],2,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\n\n%% attribute number 3 with type SEQUENCE OF\n'enc_ObservedEvent_eventParList'(element(4,Val1)),\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 4 with type Externaltypereference538megaco_per_bin_drv_media_gateway_control_v3TimeNotation\n'enc_TimeNotation'(Tmpval4)\nend].\n\n'enc_ObservedEvent_eventParList'({'ObservedEvent_eventParList',Val}) ->\n'enc_ObservedEvent_eventParList'(Val);\n\n'enc_ObservedEvent_eventParList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ObservedEvent_eventParList_components'(Val, [])\n].\n'enc_ObservedEvent_eventParList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ObservedEvent_eventParList_components'([H|T], Acc) ->\n'enc_ObservedEvent_eventParList_components'(T, ['enc_EventParameter'(H)\n\n | Acc]).\n\n'dec_ObservedEvent_eventParList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ObservedEvent_eventParList_components'(Num, Bytes1, telltype, []).\n'dec_ObservedEvent_eventParList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ObservedEvent_eventParList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_EventParameter'(Bytes,telltype),\n 'dec_ObservedEvent_eventParList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ObservedEvent'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SEQUENCE OF\n{Term3,Bytes5} = 'dec_ObservedEvent_eventParList'(Bytes4, telltype),\n\n%% attribute number 4 with type TimeNotation\n{Term4,Bytes6} = case Opt band (1 bsl 0) of\n _Opt4 when _Opt4 > 0 ->'dec_TimeNotation'(Bytes5,telltype);\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\nBytes8= ?RT_PER:skipextensions(Bytes7,1,Extensions)\n,\n{{'ObservedEvent',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_ObservedEventsDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('ObservedEventsDescriptor', Val),\n[\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_ObservedEventsDescriptor_observedEventLst'(element(3,Val1))].\n\n'enc_ObservedEventsDescriptor_observedEventLst'({'ObservedEventsDescriptor_observedEventLst',Val}) ->\n'enc_ObservedEventsDescriptor_observedEventLst'(Val);\n\n'enc_ObservedEventsDescriptor_observedEventLst'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ObservedEventsDescriptor_observedEventLst_components'(Val, [])\n].\n'enc_ObservedEventsDescriptor_observedEventLst_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ObservedEventsDescriptor_observedEventLst_components'([H|T], Acc) ->\n'enc_ObservedEventsDescriptor_observedEventLst_components'(T, ['enc_ObservedEvent'(H)\n\n | Acc]).\n\n'dec_ObservedEventsDescriptor_observedEventLst'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ObservedEventsDescriptor_observedEventLst_components'(Num, Bytes1, telltype, []).\n'dec_ObservedEventsDescriptor_observedEventLst_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ObservedEventsDescriptor_observedEventLst_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_ObservedEvent'(Bytes,telltype),\n 'dec_ObservedEventsDescriptor_observedEventLst_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ObservedEventsDescriptor'(Bytes,_) ->\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes1} = ?RT_PER:decode_constrained_number(Bytes,{0,4294967295},4294967296),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes2} = 'dec_ObservedEventsDescriptor_observedEventLst'(Bytes1, telltype),\n{{'ObservedEventsDescriptor',Term1,Term2},Bytes2}.\n\n'enc_NotifyReply'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type Externaltypereference522megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type Externaltypereference523megaco_per_bin_drv_media_gateway_control_v3ErrorDescriptor\n'enc_ErrorDescriptor'(Tmpval1)\nend].\n\n\n'dec_NotifyReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes3} = 'dec_TerminationIDList'(Bytes2,telltype),\n\n%% attribute number 2 with type ErrorDescriptor\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_ErrorDescriptor'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'NotifyReply',Term1,Term2},Bytes6}.\n\n'enc_NotifyRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type Externaltypereference514megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference515megaco_per_bin_drv_media_gateway_control_v3ObservedEventsDescriptor\n'enc_ObservedEventsDescriptor'(element(3,Val1)),\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 3 with type Externaltypereference516megaco_per_bin_drv_media_gateway_control_v3ErrorDescriptor\n'enc_ErrorDescriptor'(Tmpval1)\nend].\n\n\n'dec_NotifyRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes3} = 'dec_TerminationIDList'(Bytes2,telltype),\n\n%% attribute number 2 with type ObservedEventsDescriptor\n{Term2,Bytes4} = 'dec_ObservedEventsDescriptor'(Bytes3,telltype),\n\n%% attribute number 3 with type ErrorDescriptor\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_ErrorDescriptor'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'NotifyRequest',Term1,Term2,Term3},Bytes7}.\n\n'enc_IndAudPackagesDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('IndAudPackagesDescriptor', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval1,Tmpval2] = element(2,Val1),\n [[10,8,Tmpval1],[10,8,Tmpval2]]\n end,\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n Tmpval3=element(3,Val1),\n case Tmpval3 of\n Tmpval4 when Tmpval4=<99,Tmpval4>=0 ->\n [10,7,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end].\n\n\n'dec_IndAudPackagesDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,2,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes2,7),\n {Tmpterm1+0,Tmpremain1}\n end,\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'IndAudPackagesDescriptor',Term1,Term2},Bytes5}.\n\n'enc_IndAudStatisticsDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('IndAudStatisticsDescriptor', Val),\n[\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end].\n\n\n'dec_IndAudStatisticsDescriptor'(Bytes,_) ->\n\n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes1} = ?RT_PER:decode_octet_string(Bytes,4,false)\n,\n{{'IndAudStatisticsDescriptor',Term1},Bytes1}.\n\n'enc_IndAudDigitMapDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\n[\nOpt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type OCTET STRING\n begin\n [Tmpval2,Tmpval3] = Tmpval1,\n [[10,8,Tmpval2],[10,8,Tmpval3]]\n end\nend].\n\n\n'dec_IndAudDigitMapDescriptor'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 -> ?RT_PER:decode_octet_string(Bytes1,2,false)\n;\n0 ->{asn1_NOVALUE,Bytes1}\n\nend,\n{{'IndAudDigitMapDescriptor',Term1},Bytes2}.\n\n'enc_IndAudSignal'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\nExtensions = ?RT_PER:fixextensions({ext,3,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval2 when Tmpval2 == 4 -> [2,20,Tmpval2,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<65535,Tmpval4>=0 ->\n [20,2,<<(Tmpval4- 0):16>>];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\nend\n,Extensions\n,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 3 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval5)))\nend].\n\n\n'dec_IndAudSignal'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes6} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal3,Trem3}=?RT_PER:decode_open_type(Bytes5,[]),\n{TmpValx3,_}=?RT_PER:decode_constrained_number(TmpVal3,{0,4294967295},4294967296), {TmpValx3,Trem3}\nend;\n_ ->\n{asn1_NOVALUE,Bytes5}\n\nend,\nBytes7= ?RT_PER:skipextensions(Bytes6,2,Extensions)\n,\n{{'IndAudSignal',Term1,Term2,Term3},Bytes7}.\n\n'enc_IndAudSeqSigList'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereference484megaco_per_bin_drv_media_gateway_control_v3IndAudSignal\n'enc_IndAudSignal'(Tmpval3)\nend].\n\n\n'dec_IndAudSeqSigList'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes1,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type IndAudSignal\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_IndAudSignal'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'IndAudSeqSigList',Term1,Term2},Bytes3}.\n\n\n'enc_IndAudSignalsDescriptor'({'IndAudSignalsDescriptor',Val}) ->\n'enc_IndAudSignalsDescriptor'(Val);\n\n'enc_IndAudSignalsDescriptor'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[signal,seqSigList],[]}, {2,0}),\ncase element(1,Val) of\nsignal ->\n'enc_IndAudSignal'(element(2,Val));\nseqSigList ->\n'enc_IndAudSeqSigList'(element(2,Val))\nend\n].\n\n\n'dec_IndAudSignalsDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,2,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*2 of\n0 -> {signal,\n'dec_IndAudSignal'(Bytes2,telltype)};\n1 -> {seqSigList,\n'dec_IndAudSeqSigList'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_IndAudEventBufferDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend].\n\n\n'dec_IndAudEventBufferDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'IndAudEventBufferDescriptor',Term1,Term2},Bytes6}.\n\n'enc_IndAudEventsDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,4],2,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval1)\nend,\n\n%% attribute number 2 with type OCTET STRING\n begin\n case length(element(3,Val1)) of\n Tmpval2 when Tmpval2 == 4 -> [2,20,Tmpval2,element(3,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(3,Val1)}})\n end\n end,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<65535,Tmpval4>=0 ->\n [20,2,<<(Tmpval4- 0):16>>];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\nend].\n\n\n'dec_IndAudEventsDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 1) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type OCTET STRING\n{Term2,Bytes4} = ?RT_PER:decode_octet_string(Bytes3,4,false)\n,\n\n%% attribute number 3 with type INTEGER\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes4,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'IndAudEventsDescriptor',Term1,Term2,Term3},Bytes7}.\n\n'enc_IndAudTerminationStateDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\n\n%% attribute number 1 with type SEQUENCE OF\n'enc_IndAudTerminationStateDescriptor_propertyParms'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type NULL\n?RT_PER:encode_null(Tmpval2)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type NULL\n?RT_PER:encode_null(Tmpval3)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 4 with type ENUMERATED\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval4 of\n'test' -> [0,10,2,0];\n'outOfSvc' -> [0,10,2,1];\n'inSvc' -> [0,10,2,2];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend))\nend].\n\n'enc_IndAudTerminationStateDescriptor_propertyParms'({'IndAudTerminationStateDescriptor_propertyParms',Val}) ->\n'enc_IndAudTerminationStateDescriptor_propertyParms'(Val);\n\n'enc_IndAudTerminationStateDescriptor_propertyParms'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_IndAudTerminationStateDescriptor_propertyParms_components'(Val, [])\n].\n'enc_IndAudTerminationStateDescriptor_propertyParms_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_IndAudTerminationStateDescriptor_propertyParms_components'([H|T], Acc) ->\n'enc_IndAudTerminationStateDescriptor_propertyParms_components'(T, ['enc_IndAudPropertyParm'(H)\n\n | Acc]).\n\n'dec_IndAudTerminationStateDescriptor_propertyParms'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_IndAudTerminationStateDescriptor_propertyParms_components'(Num, Bytes1, telltype, []).\n'dec_IndAudTerminationStateDescriptor_propertyParms_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_IndAudTerminationStateDescriptor_propertyParms_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAudPropertyParm'(Bytes,telltype),\n 'dec_IndAudTerminationStateDescriptor_propertyParms_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_IndAudTerminationStateDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type SEQUENCE OF\n{Term1,Bytes3} = 'dec_IndAudTerminationStateDescriptor_propertyParms'(Bytes2, telltype),\n\n%% attribute number 2 with type NULL\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_null(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type NULL\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_null(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type ENUMERATED\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}=?RT_PER:decode_enumerated(TmpVal4,[{'ValueRange',{0,2}}],{{test,outOfSvc,inSvc},{}}), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\nBytes8= ?RT_PER:skipextensions(Bytes7,2,Extensions)\n,\n{{'IndAudTerminationStateDescriptor',Term1,Term2,Term3,Term4},Bytes8}.\n\n\n'enc_IndAudPropertyGroup'({'IndAudPropertyGroup',Val}) ->\n'enc_IndAudPropertyGroup'(Val);\n\n'enc_IndAudPropertyGroup'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_IndAudPropertyGroup_components'(Val, [])\n].\n'enc_IndAudPropertyGroup_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_IndAudPropertyGroup_components'([H|T], Acc) ->\n'enc_IndAudPropertyGroup_components'(T, ['enc_IndAudPropertyParm'(H)\n\n | Acc]).\n\n\n'dec_IndAudPropertyGroup'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_IndAudPropertyGroup_components'(Num, Bytes1, telltype, []).\n'dec_IndAudPropertyGroup_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_IndAudPropertyGroup_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAudPropertyParm'(Bytes,telltype),\n 'dec_IndAudPropertyGroup_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_IndAudLocalRemoteDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end\nend,\n\n%% attribute number 2 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3IndAudPropertyGroup\n'enc_IndAudPropertyGroup'(element(3,Val1))].\n\n\n'dec_IndAudLocalRemoteDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes2,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type IndAudPropertyGroup\n{Term2,Bytes4} = 'dec_IndAudPropertyGroup'(Bytes3,telltype),\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'IndAudLocalRemoteDescriptor',Term1,Term2},Bytes6}.\n\n'enc_IndAudPropertyParm'(Val) ->\nVal1 = ?RT_PER:list_to_record('IndAudPropertyParm', Val),\nExtensions = ?RT_PER:fixextensions({ext,2,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), \n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval2 when Tmpval2 == 4 -> [2,20,Tmpval2,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end\n,Extensions\n, case element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3PropertyParm\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_PropertyParm'(Tmpval3)))\nend].\n\n\n'dec_IndAudPropertyParm'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,4,false)\n,\n{Extensions,Bytes3} = ?RT_PER:getextension(Ext,Bytes2),\n\n%% attribute number 2 with type PropertyParm\n{Term2,Bytes4} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal2,Trem2}=?RT_PER:decode_open_type(Bytes3,[]),\n{TmpValx2,_}='dec_PropertyParm'(TmpVal2,telltype), {TmpValx2,Trem2}\nend;\n_ ->\n{asn1_NOVALUE,Bytes3}\n\nend,\nBytes5= ?RT_PER:skipextensions(Bytes4,2,Extensions)\n,\n{{'IndAudPropertyParm',Term1,Term2},Bytes5}.\n\n'enc_IndAudLocalControlDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4,5],4,Val),\nExtensions = ?RT_PER:fixextensions({ext,5,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type NULL\n?RT_PER:encode_null(Tmpval2)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type NULL\n?RT_PER:encode_null(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type NULL\n?RT_PER:encode_null(Tmpval4)\nend,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_IndAudLocalControlDescriptor_propertyParms'(Tmpval5)\nend\n,Extensions\n,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 5 with type ENUMERATED\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval6 of\n'sendOnly' -> [0,10,3,0];\n'recvOnly' -> [0,10,3,1];\n'sendRecv' -> [0,10,3,2];\n'inactive' -> [0,10,3,3];\n'loopBack' -> [0,10,3,4];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend))\nend].\n\n'enc_IndAudLocalControlDescriptor_propertyParms'({'IndAudLocalControlDescriptor_propertyParms',Val}) ->\n'enc_IndAudLocalControlDescriptor_propertyParms'(Val);\n\n'enc_IndAudLocalControlDescriptor_propertyParms'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_IndAudLocalControlDescriptor_propertyParms_components'(Val, [])\n].\n'enc_IndAudLocalControlDescriptor_propertyParms_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_IndAudLocalControlDescriptor_propertyParms_components'([H|T], Acc) ->\n'enc_IndAudLocalControlDescriptor_propertyParms_components'(T, ['enc_IndAudPropertyParm'(H)\n\n | Acc]).\n\n'dec_IndAudLocalControlDescriptor_propertyParms'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_IndAudLocalControlDescriptor_propertyParms_components'(Num, Bytes1, telltype, []).\n'dec_IndAudLocalControlDescriptor_propertyParms_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_IndAudLocalControlDescriptor_propertyParms_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAudPropertyParm'(Bytes,telltype),\n 'dec_IndAudLocalControlDescriptor_propertyParms_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_IndAudLocalControlDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,4), \n%% attribute number 1 with type NULL\n{Term1,Bytes3} = case Opt band (1 bsl 3) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_null(Bytes2);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type NULL\n{Term2,Bytes4} = case Opt band (1 bsl 2) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_null(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type NULL\n{Term3,Bytes5} = case Opt band (1 bsl 1) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_null(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes6} = case Opt band (1 bsl 0) of\n _Opt4 when _Opt4 > 0 ->'dec_IndAudLocalControlDescriptor_propertyParms'(Bytes5, telltype);\n0 ->{asn1_NOVALUE,Bytes5}\n\nend,\n{Extensions,Bytes7} = ?RT_PER:getextension(Ext,Bytes6),\n\n%% attribute number 5 with type ENUMERATED\n{Term5,Bytes8} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}=?RT_PER:decode_enumerated(TmpVal5,[{'ValueRange',{0,4}}],{{sendOnly,recvOnly,sendRecv,inactive,loopBack},{}}), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\nBytes9= ?RT_PER:skipextensions(Bytes8,2,Extensions)\n,\n{{'IndAudLocalControlDescriptor',Term1,Term2,Term3,Term4,Term5},Bytes9}.\n\n'enc_IndAudStreamParms'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3IndAudLocalControlDescriptor\n'enc_IndAudLocalControlDescriptor'(Tmpval2)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3IndAudLocalRemoteDescriptor\n'enc_IndAudLocalRemoteDescriptor'(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type Externaltypereference413megaco_per_bin_drv_media_gateway_control_v3IndAudLocalRemoteDescriptor\n'enc_IndAudLocalRemoteDescriptor'(Tmpval4)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3IndAudStatisticsDescriptor\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_IndAudStatisticsDescriptor'(Tmpval5)))\nend].\n\n\n'dec_IndAudStreamParms'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type IndAudLocalControlDescriptor\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 ->'dec_IndAudLocalControlDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type IndAudLocalRemoteDescriptor\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->'dec_IndAudLocalRemoteDescriptor'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type IndAudLocalRemoteDescriptor\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_IndAudLocalRemoteDescriptor'(Bytes4,telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type IndAudStatisticsDescriptor\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}='dec_IndAudStatisticsDescriptor'(TmpVal4,telltype), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\nBytes8= ?RT_PER:skipextensions(Bytes7,2,Extensions)\n,\n{{'IndAudStreamParms',Term1,Term2,Term3,Term4},Bytes8}.\n\n'enc_IndAudStreamDescriptor'(Val) ->\nVal1 = ?RT_PER:list_to_record('IndAudStreamDescriptor', Val),\n[\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\n\n%% attribute number 2 with type Externaltypereference406megaco_per_bin_drv_media_gateway_control_v3IndAudStreamParms\n'enc_IndAudStreamParms'(element(3,Val1))].\n\n\n'dec_IndAudStreamDescriptor'(Bytes,_) ->\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes1} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type IndAudStreamParms\n{Term2,Bytes2} = 'dec_IndAudStreamParms'(Bytes1,telltype),\n{{'IndAudStreamDescriptor',Term1,Term2},Bytes2}.\n\n'enc_IndAudMediaDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3],2,Val),\n[\n?RT_PER:setext(false), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type Externaltypereferenceundefinedmegaco_per_bin_drv_media_gateway_control_v3IndAudTerminationStateDescriptor\n'enc_IndAudTerminationStateDescriptor'(Tmpval1)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type CHOICE\n'enc_IndAudMediaDescriptor_streams'(Tmpval2)\nend].\n\n'enc_IndAudMediaDescriptor_streams'({'IndAudMediaDescriptor_streams',Val}) ->\n'enc_IndAudMediaDescriptor_streams'(Val);\n\n'enc_IndAudMediaDescriptor_streams'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[oneStream,multiStream], 2),\ncase element(1,Val) of\noneStream ->\n'enc_IndAudStreamParms'(element(2,Val));\nmultiStream ->\n'enc_IndAudMediaDescriptor_streams_multiStream'(element(2,Val))\nend\n].\n\n'enc_IndAudMediaDescriptor_streams_multiStream'({'IndAudMediaDescriptor_streams_multiStream',Val}) ->\n'enc_IndAudMediaDescriptor_streams_multiStream'(Val);\n\n'enc_IndAudMediaDescriptor_streams_multiStream'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_IndAudMediaDescriptor_streams_multiStream_components'(Val, [])\n].\n'enc_IndAudMediaDescriptor_streams_multiStream_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_IndAudMediaDescriptor_streams_multiStream_components'([H|T], Acc) ->\n'enc_IndAudMediaDescriptor_streams_multiStream_components'(T, ['enc_IndAudStreamDescriptor'(H)\n\n | Acc]).\n\n'dec_IndAudMediaDescriptor_streams_multiStream'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_IndAudMediaDescriptor_streams_multiStream_components'(Num, Bytes1, telltype, []).\n'dec_IndAudMediaDescriptor_streams_multiStream_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_IndAudMediaDescriptor_streams_multiStream_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAudStreamDescriptor'(Bytes,telltype),\n 'dec_IndAudMediaDescriptor_streams_multiStream_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'dec_IndAudMediaDescriptor_streams'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {oneStream,\n'dec_IndAudStreamParms'(Bytes1,telltype)};\n1 -> {multiStream,\n'dec_IndAudMediaDescriptor_streams_multiStream'(Bytes1, telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_IndAudMediaDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type IndAudTerminationStateDescriptor\n{Term1,Bytes3} = case Opt band (1 bsl 1) of\n _Opt1 when _Opt1 > 0 ->'dec_IndAudTerminationStateDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type CHOICE\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_IndAudMediaDescriptor_streams'(Bytes3, telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'IndAudMediaDescriptor',Term1,Term2},Bytes6}.\n\n\n'enc_IndAuditParameter'({'IndAuditParameter',Val}) ->\n'enc_IndAuditParameter'(Val);\n\n'enc_IndAuditParameter'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[indAudMediaDescriptor,indAudEventsDescriptor,indAudEventBufferDescriptor,indAudSignalsDescriptor,indAudDigitMapDescriptor,indAudStatisticsDescriptor,indAudPackagesDescriptor],[]}, {7,0}),\ncase element(1,Val) of\nindAudMediaDescriptor ->\n'enc_IndAudMediaDescriptor'(element(2,Val));\nindAudEventsDescriptor ->\n'enc_IndAudEventsDescriptor'(element(2,Val));\nindAudEventBufferDescriptor ->\n'enc_IndAudEventBufferDescriptor'(element(2,Val));\nindAudSignalsDescriptor ->\n'enc_IndAudSignalsDescriptor'(element(2,Val));\nindAudDigitMapDescriptor ->\n'enc_IndAudDigitMapDescriptor'(element(2,Val));\nindAudStatisticsDescriptor ->\n'enc_IndAudStatisticsDescriptor'(element(2,Val));\nindAudPackagesDescriptor ->\n'enc_IndAudPackagesDescriptor'(element(2,Val))\nend\n].\n\n\n'dec_IndAuditParameter'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,7,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*7 of\n0 -> {indAudMediaDescriptor,\n'dec_IndAudMediaDescriptor'(Bytes2,telltype)};\n1 -> {indAudEventsDescriptor,\n'dec_IndAudEventsDescriptor'(Bytes2,telltype)};\n2 -> {indAudEventBufferDescriptor,\n'dec_IndAudEventBufferDescriptor'(Bytes2,telltype)};\n3 -> {indAudSignalsDescriptor,\n'dec_IndAudSignalsDescriptor'(Bytes2,telltype)};\n4 -> {indAudDigitMapDescriptor,\n'dec_IndAudDigitMapDescriptor'(Bytes2,telltype)};\n5 -> {indAudStatisticsDescriptor,\n'dec_IndAudStatisticsDescriptor'(Bytes2,telltype)};\n6 -> {indAudPackagesDescriptor,\n'dec_IndAudPackagesDescriptor'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_AuditDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\nExtensions = ?RT_PER:fixextensions({ext,2,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type BIT STRING\n?RT_PER:encode_bit_string(no,Tmpval2,[{muxToken,0},{modemToken,1},{mediaToken,2},{eventsToken,3},{signalsToken,4},{digitMapToken,5},{statsToken,6},{observedEventsToken,7},{packagesToken,8},{eventBufferToken,9}])\nend\n,Extensions\n,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type SEQUENCE OF\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_AuditDescriptor_auditPropertyToken'(Tmpval3)))\nend].\n\n'enc_AuditDescriptor_auditPropertyToken'({'AuditDescriptor_auditPropertyToken',Val}) ->\n'enc_AuditDescriptor_auditPropertyToken'(Val);\n\n'enc_AuditDescriptor_auditPropertyToken'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_AuditDescriptor_auditPropertyToken_components'(Val, [])\n].\n'enc_AuditDescriptor_auditPropertyToken_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_AuditDescriptor_auditPropertyToken_components'([H|T], Acc) ->\n'enc_AuditDescriptor_auditPropertyToken_components'(T, ['enc_IndAuditParameter'(H)\n\n | Acc]).\n\n'dec_AuditDescriptor_auditPropertyToken'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_AuditDescriptor_auditPropertyToken_components'(Num, Bytes1, telltype, []).\n'dec_AuditDescriptor_auditPropertyToken_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_AuditDescriptor_auditPropertyToken_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAuditParameter'(Bytes,telltype),\n 'dec_AuditDescriptor_auditPropertyToken_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_AuditDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type BIT STRING\n{Term1,Bytes3} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_bit_string(Bytes2,[],[{muxToken,0},{modemToken,1},{mediaToken,2},{eventsToken,3},{signalsToken,4},{digitMapToken,5},{statsToken,6},{observedEventsToken,7},{packagesToken,8},{eventBufferToken,9}]);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes5} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal2,Trem2}=?RT_PER:decode_open_type(Bytes4,[]),\n{TmpValx2,_}='dec_AuditDescriptor_auditPropertyToken'(TmpVal2, telltype), {TmpValx2,Trem2}\nend;\n_ ->\n{asn1_NOVALUE,Bytes4}\n\nend,\nBytes6= ?RT_PER:skipextensions(Bytes5,2,Extensions)\n,\n{{'AuditDescriptor',Term1,Term2},Bytes6}.\n\n\n'enc_AuditReturnParameter'({'AuditReturnParameter',Val}) ->\n'enc_AuditReturnParameter'(Val);\n\n'enc_AuditReturnParameter'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[errorDescriptor,mediaDescriptor,modemDescriptor,muxDescriptor,eventsDescriptor,eventBufferDescriptor,signalsDescriptor,digitMapDescriptor,observedEventsDescriptor,statisticsDescriptor,packagesDescriptor,emptyDescriptors],[]}, {12,0}),\ncase element(1,Val) of\nerrorDescriptor ->\n'enc_ErrorDescriptor'(element(2,Val));\nmediaDescriptor ->\n'enc_MediaDescriptor'(element(2,Val));\nmodemDescriptor ->\n'enc_ModemDescriptor'(element(2,Val));\nmuxDescriptor ->\n'enc_MuxDescriptor'(element(2,Val));\neventsDescriptor ->\n'enc_EventsDescriptor'(element(2,Val));\neventBufferDescriptor ->\n'enc_EventBufferDescriptor'(element(2,Val));\nsignalsDescriptor ->\n'enc_SignalsDescriptor'(element(2,Val));\ndigitMapDescriptor ->\n'enc_DigitMapDescriptor'(element(2,Val));\nobservedEventsDescriptor ->\n'enc_ObservedEventsDescriptor'(element(2,Val));\nstatisticsDescriptor ->\n'enc_StatisticsDescriptor'(element(2,Val));\npackagesDescriptor ->\n'enc_PackagesDescriptor'(element(2,Val));\nemptyDescriptors ->\n'enc_AuditDescriptor'(element(2,Val))\nend\n].\n\n\n'dec_AuditReturnParameter'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,12,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*12 of\n0 -> {errorDescriptor,\n'dec_ErrorDescriptor'(Bytes2,telltype)};\n1 -> {mediaDescriptor,\n'dec_MediaDescriptor'(Bytes2,telltype)};\n2 -> {modemDescriptor,\n'dec_ModemDescriptor'(Bytes2,telltype)};\n3 -> {muxDescriptor,\n'dec_MuxDescriptor'(Bytes2,telltype)};\n4 -> {eventsDescriptor,\n'dec_EventsDescriptor'(Bytes2,telltype)};\n5 -> {eventBufferDescriptor,\n'dec_EventBufferDescriptor'(Bytes2,telltype)};\n6 -> {signalsDescriptor,\n'dec_SignalsDescriptor'(Bytes2,telltype)};\n7 -> {digitMapDescriptor,\n'dec_DigitMapDescriptor'(Bytes2,telltype)};\n8 -> {observedEventsDescriptor,\n'dec_ObservedEventsDescriptor'(Bytes2,telltype)};\n9 -> {statisticsDescriptor,\n'dec_StatisticsDescriptor'(Bytes2,telltype)};\n10 -> {packagesDescriptor,\n'dec_PackagesDescriptor'(Bytes2,telltype)};\n11 -> {emptyDescriptors,\n'dec_AuditDescriptor'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n\n'enc_TerminationAudit'({'TerminationAudit',Val}) ->\n'enc_TerminationAudit'(Val);\n\n'enc_TerminationAudit'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TerminationAudit_components'(Val, [])\n].\n'enc_TerminationAudit_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TerminationAudit_components'([H|T], Acc) ->\n'enc_TerminationAudit_components'(T, ['enc_AuditReturnParameter'(H)\n\n | Acc]).\n\n\n'dec_TerminationAudit'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TerminationAudit_components'(Num, Bytes1, telltype, []).\n'dec_TerminationAudit_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TerminationAudit_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_AuditReturnParameter'(Bytes,telltype),\n 'dec_TerminationAudit_components'(Num-1, Remain, telltype, [Term|Acc]).\n'enc_TermListAuditResult'(Val) ->\nVal1 = ?RT_PER:list_to_record('TermListAuditResult', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type Externaltypereference338megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference339megaco_per_bin_drv_media_gateway_control_v3TerminationAudit\n'enc_TerminationAudit'(element(3,Val1))].\n\n\n'dec_TermListAuditResult'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes2} = 'dec_TerminationIDList'(Bytes1,telltype),\n\n%% attribute number 2 with type TerminationAudit\n{Term2,Bytes3} = 'dec_TerminationAudit'(Bytes2,telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'TermListAuditResult',Term1,Term2},Bytes5}.\n\n'enc_AuditResult'(Val) ->\nVal1 = ?RT_PER:list_to_record('AuditResult', Val),\n[\n\n%% attribute number 1 with type Externaltypereference332megaco_per_bin_drv_media_gateway_control_v3TerminationID\n'enc_TerminationID'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference333megaco_per_bin_drv_media_gateway_control_v3TerminationAudit\n'enc_TerminationAudit'(element(3,Val1))].\n\n\n'dec_AuditResult'(Bytes,_) ->\n\n%% attribute number 1 with type TerminationID\n{Term1,Bytes1} = 'dec_TerminationID'(Bytes,telltype),\n\n%% attribute number 2 with type TerminationAudit\n{Term2,Bytes2} = 'dec_TerminationAudit'(Bytes1,telltype),\n{{'AuditResult',Term1,Term2},Bytes2}.\n\n\n'enc_AuditReply'({'AuditReply',Val}) ->\n'enc_AuditReply'(Val);\n\n'enc_AuditReply'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[contextAuditResult,error,auditResult],[auditResultTermList]}, {3,1}),\ncase element(1,Val) of\ncontextAuditResult ->\n'enc_TerminationIDList'(element(2,Val));\nerror ->\n'enc_ErrorDescriptor'(element(2,Val));\nauditResult ->\n'enc_AuditResult'(element(2,Val));\nauditResultTermList ->\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_TermListAuditResult'(element(2,Val))))\nend\n].\n\n\n'dec_AuditReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,3,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*3 of\n0 -> {contextAuditResult,\n'dec_TerminationIDList'(Bytes2,telltype)};\n1 -> {error,\n'dec_ErrorDescriptor'(Bytes2,telltype)};\n2 -> {auditResult,\n'dec_AuditResult'(Bytes2,telltype)};\n3 -> {auditResultTermList,\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes2,[]),\n{TmpValx4,_}='dec_TermListAuditResult'(TmpVal4,telltype), {TmpValx4,Trem4}\nend};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_AuditRequest'(Val) ->\nVal1 = ?RT_PER:list_to_record('AuditRequest', Val),\nExtensions = ?RT_PER:fixextensions({ext,3,1},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), \n%% attribute number 1 with type Externaltypereference312megaco_per_bin_drv_media_gateway_control_v3TerminationID\n'enc_TerminationID'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference313megaco_per_bin_drv_media_gateway_control_v3AuditDescriptor\n'enc_AuditDescriptor'(element(3,Val1))\n,Extensions\n, case element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type Externaltypereference315megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_TerminationIDList'(Tmpval2)))\nend].\n\n\n'dec_AuditRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationID\n{Term1,Bytes2} = 'dec_TerminationID'(Bytes1,telltype),\n\n%% attribute number 2 with type AuditDescriptor\n{Term2,Bytes3} = 'dec_AuditDescriptor'(Bytes2,telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\n\n%% attribute number 3 with type TerminationIDList\n{Term3,Bytes5} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal3,Trem3}=?RT_PER:decode_open_type(Bytes4,[]),\n{TmpValx3,_}='dec_TerminationIDList'(TmpVal3,telltype), {TmpValx3,Trem3}\nend;\n_ ->\n{asn1_NOVALUE,Bytes4}\n\nend,\nBytes6= ?RT_PER:skipextensions(Bytes5,2,Extensions)\n,\n{{'AuditRequest',Term1,Term2,Term3},Bytes6}.\n\n'enc_SubtractRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type Externaltypereference305megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type Externaltypereference306megaco_per_bin_drv_media_gateway_control_v3AuditDescriptor\n'enc_AuditDescriptor'(Tmpval1)\nend].\n\n\n'dec_SubtractRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes3} = 'dec_TerminationIDList'(Bytes2,telltype),\n\n%% attribute number 2 with type AuditDescriptor\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_AuditDescriptor'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'SubtractRequest',Term1,Term2},Bytes6}.\n\n'enc_AmmsReply'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type Externaltypereference298megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type Externaltypereference299megaco_per_bin_drv_media_gateway_control_v3TerminationAudit\n'enc_TerminationAudit'(Tmpval1)\nend].\n\n\n'dec_AmmsReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes3} = 'dec_TerminationIDList'(Bytes2,telltype),\n\n%% attribute number 2 with type TerminationAudit\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->'dec_TerminationAudit'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'AmmsReply',Term1,Term2},Bytes6}.\n\n\n'enc_AmmDescriptor'({'AmmDescriptor',Val}) ->\n'enc_AmmDescriptor'(Val);\n\n'enc_AmmDescriptor'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[mediaDescriptor,modemDescriptor,muxDescriptor,eventsDescriptor,eventBufferDescriptor,signalsDescriptor,digitMapDescriptor,auditDescriptor],[statisticsDescriptor]}, {8,1}),\ncase element(1,Val) of\nmediaDescriptor ->\n'enc_MediaDescriptor'(element(2,Val));\nmodemDescriptor ->\n'enc_ModemDescriptor'(element(2,Val));\nmuxDescriptor ->\n'enc_MuxDescriptor'(element(2,Val));\neventsDescriptor ->\n'enc_EventsDescriptor'(element(2,Val));\neventBufferDescriptor ->\n'enc_EventBufferDescriptor'(element(2,Val));\nsignalsDescriptor ->\n'enc_SignalsDescriptor'(element(2,Val));\ndigitMapDescriptor ->\n'enc_DigitMapDescriptor'(element(2,Val));\nauditDescriptor ->\n'enc_AuditDescriptor'(element(2,Val));\nstatisticsDescriptor ->\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_StatisticsDescriptor'(element(2,Val))))\nend\n].\n\n\n'dec_AmmDescriptor'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,8,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*8 of\n0 -> {mediaDescriptor,\n'dec_MediaDescriptor'(Bytes2,telltype)};\n1 -> {modemDescriptor,\n'dec_ModemDescriptor'(Bytes2,telltype)};\n2 -> {muxDescriptor,\n'dec_MuxDescriptor'(Bytes2,telltype)};\n3 -> {eventsDescriptor,\n'dec_EventsDescriptor'(Bytes2,telltype)};\n4 -> {eventBufferDescriptor,\n'dec_EventBufferDescriptor'(Bytes2,telltype)};\n5 -> {signalsDescriptor,\n'dec_SignalsDescriptor'(Bytes2,telltype)};\n6 -> {digitMapDescriptor,\n'dec_DigitMapDescriptor'(Bytes2,telltype)};\n7 -> {auditDescriptor,\n'dec_AuditDescriptor'(Bytes2,telltype)};\n8 -> {statisticsDescriptor,\nbegin\n{TmpVal9,Trem9}=?RT_PER:decode_open_type(Bytes2,[]),\n{TmpValx9,_}='dec_StatisticsDescriptor'(TmpVal9,telltype), {TmpValx9,Trem9}\nend};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_AmmRequest'(Val) ->\nVal1 = ?RT_PER:list_to_record('AmmRequest', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type Externaltypereference274megaco_per_bin_drv_media_gateway_control_v3TerminationIDList\n'enc_TerminationIDList'(element(2,Val1)),\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_AmmRequest_descriptors'(element(3,Val1))].\n\n'enc_AmmRequest_descriptors'({'AmmRequest_descriptors',Val}) ->\n'enc_AmmRequest_descriptors'(Val);\n\n'enc_AmmRequest_descriptors'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_AmmRequest_descriptors_components'(Val, [])\n].\n'enc_AmmRequest_descriptors_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_AmmRequest_descriptors_components'([H|T], Acc) ->\n'enc_AmmRequest_descriptors_components'(T, ['enc_AmmDescriptor'(H)\n\n | Acc]).\n\n'dec_AmmRequest_descriptors'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_AmmRequest_descriptors_components'(Num, Bytes1, telltype, []).\n'dec_AmmRequest_descriptors_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_AmmRequest_descriptors_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_AmmDescriptor'(Bytes,telltype),\n 'dec_AmmRequest_descriptors_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_AmmRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationIDList\n{Term1,Bytes2} = 'dec_TerminationIDList'(Bytes1,telltype),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes3} = 'dec_AmmRequest_descriptors'(Bytes2, telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'AmmRequest',Term1,Term2},Bytes5}.\n\n'enc_TopologyRequest'(Val) ->\nVal1 = ?RT_PER:list_to_record('TopologyRequest', Val),\nExtensions = ?RT_PER:fixextensions({ext,4,2},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), \n%% attribute number 1 with type Externaltypereference251megaco_per_bin_drv_media_gateway_control_v3TerminationID\n'enc_TerminationID'(element(2,Val1)),\n\n%% attribute number 2 with type Externaltypereference252megaco_per_bin_drv_media_gateway_control_v3TerminationID\n'enc_TerminationID'(element(3,Val1)),\n\n%% attribute number 3 with type ENUMERATED\n begin\n Tmpval3=(case element(4,Val1) of bothway->0;isolate->1;oneway->2;Tmpval2 ->exit({error,{asn1,{enumerated,Tmpval2}}}) end),\n case Tmpval3 of\n Tmpval4 when Tmpval4=<2,Tmpval4>=0 ->\n [10,2,Tmpval4- 0];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end\n,Extensions\n, case element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval5 of\n Tmpval6 when Tmpval6=<65535,Tmpval6>=0 ->\n [20,2,<<(Tmpval6- 0):16>>];\n Tmpval6 ->\n exit({error,{value_out_of_bounds,Tmpval6}})\n end\n\n end))\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval7 ->\n\n%% attribute number 5 with type ENUMERATED\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval7 of\n'onewayexternal' -> [0,0];\n'onewayboth' -> [0,1];\n\nEnumVal -> exit({error,{asn1, {enumerated_not_in_range, EnumVal}}})\nend))\nend].\n\n\n'dec_TopologyRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type TerminationID\n{Term1,Bytes2} = 'dec_TerminationID'(Bytes1,telltype),\n\n%% attribute number 2 with type TerminationID\n{Term2,Bytes3} = 'dec_TerminationID'(Bytes2,telltype),\n\n%% attribute number 3 with type ENUMERATED\n{Term3,Bytes4} = begin\n {Tmpterm1,Tmpremain1} =\n begin\n {Tmpterm2,Tmpremain2}=?RT_PER:getbits(Bytes3,2),\n {Tmpterm2+0,Tmpremain2}\n end,\n case Tmpterm1 of 0->{bothway,Tmpremain1};1->{isolate,Tmpremain1};2->{oneway,Tmpremain1};_->exit({error,{asn1,{decode_enumerated,{Tmpterm1,[bothway,isolate,oneway]}}}}) end\n end,\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\n\n%% attribute number 4 with type INTEGER\n{Term4,Bytes6} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes5,[]),\n{TmpValx4,_}= begin\n {Tmpterm3,Tmpremain3}=?RT_PER:getoctets(TmpVal4,2),\n {Tmpterm3+0,Tmpremain3}\n end, {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes5}\n\nend,\n\n%% attribute number 5 with type ENUMERATED\n{Term5,Bytes7} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx5,_}=?RT_PER:decode_enumerated(TmpVal5,[{'ValueRange',{0,1}}],{{onewayexternal,onewayboth},{}}), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\nBytes8= ?RT_PER:skipextensions(Bytes7,3,Extensions)\n,\n{{'TopologyRequest',Term1,Term2,Term3,Term4,Term5},Bytes8}.\n\n\n'enc_CommandReply'({'CommandReply',Val}) ->\n'enc_CommandReply'(Val);\n\n'enc_CommandReply'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[addReply,moveReply,modReply,subtractReply,auditCapReply,auditValueReply,notifyReply,serviceChangeReply],[]}, {8,0}),\ncase element(1,Val) of\naddReply ->\n'enc_AmmsReply'(element(2,Val));\nmoveReply ->\n'enc_AmmsReply'(element(2,Val));\nmodReply ->\n'enc_AmmsReply'(element(2,Val));\nsubtractReply ->\n'enc_AmmsReply'(element(2,Val));\nauditCapReply ->\n'enc_AuditReply'(element(2,Val));\nauditValueReply ->\n'enc_AuditReply'(element(2,Val));\nnotifyReply ->\n'enc_NotifyReply'(element(2,Val));\nserviceChangeReply ->\n'enc_ServiceChangeReply'(element(2,Val))\nend\n].\n\n\n'dec_CommandReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,8,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*8 of\n0 -> {addReply,\n'dec_AmmsReply'(Bytes2,telltype)};\n1 -> {moveReply,\n'dec_AmmsReply'(Bytes2,telltype)};\n2 -> {modReply,\n'dec_AmmsReply'(Bytes2,telltype)};\n3 -> {subtractReply,\n'dec_AmmsReply'(Bytes2,telltype)};\n4 -> {auditCapReply,\n'dec_AuditReply'(Bytes2,telltype)};\n5 -> {auditValueReply,\n'dec_AuditReply'(Bytes2,telltype)};\n6 -> {notifyReply,\n'dec_NotifyReply'(Bytes2,telltype)};\n7 -> {serviceChangeReply,\n'dec_ServiceChangeReply'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n\n'enc_Command'({'Command',Val}) ->\n'enc_Command'(Val);\n\n'enc_Command'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[addReq,moveReq,modReq,subtractReq,auditCapRequest,auditValueRequest,notifyReq,serviceChangeReq],[]}, {8,0}),\ncase element(1,Val) of\naddReq ->\n'enc_AmmRequest'(element(2,Val));\nmoveReq ->\n'enc_AmmRequest'(element(2,Val));\nmodReq ->\n'enc_AmmRequest'(element(2,Val));\nsubtractReq ->\n'enc_SubtractRequest'(element(2,Val));\nauditCapRequest ->\n'enc_AuditRequest'(element(2,Val));\nauditValueRequest ->\n'enc_AuditRequest'(element(2,Val));\nnotifyReq ->\n'enc_NotifyRequest'(element(2,Val));\nserviceChangeReq ->\n'enc_ServiceChangeRequest'(element(2,Val))\nend\n].\n\n\n'dec_Command'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,8,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*8 of\n0 -> {addReq,\n'dec_AmmRequest'(Bytes2,telltype)};\n1 -> {moveReq,\n'dec_AmmRequest'(Bytes2,telltype)};\n2 -> {modReq,\n'dec_AmmRequest'(Bytes2,telltype)};\n3 -> {subtractReq,\n'dec_SubtractRequest'(Bytes2,telltype)};\n4 -> {auditCapRequest,\n'dec_AuditRequest'(Bytes2,telltype)};\n5 -> {auditValueRequest,\n'dec_AuditRequest'(Bytes2,telltype)};\n6 -> {notifyReq,\n'dec_NotifyRequest'(Bytes2,telltype)};\n7 -> {serviceChangeReq,\n'dec_ServiceChangeRequest'(Bytes2,telltype)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_CommandRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type Externaltypereference215megaco_per_bin_drv_media_gateway_control_v3Command\n'enc_Command'(element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type NULL\n?RT_PER:encode_null(Tmpval1)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type NULL\n?RT_PER:encode_null(Tmpval2)\nend].\n\n\n'dec_CommandRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,2), \n%% attribute number 1 with type Command\n{Term1,Bytes3} = 'dec_Command'(Bytes2,telltype),\n\n%% attribute number 2 with type NULL\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_null(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type NULL\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_null(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'CommandRequest',Term1,Term2,Term3},Bytes7}.\n\n\n'enc_SelectLogic'({'SelectLogic',Val}) ->\n'enc_SelectLogic'(Val);\n\n'enc_SelectLogic'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[andAUDITSelect,orAUDITSelect],[]}, {2,0}),\ncase element(1,Val) of\nandAUDITSelect ->\n?RT_PER:encode_null(element(2,Val));\norAUDITSelect ->\n?RT_PER:encode_null(element(2,Val))\nend\n].\n\n\n'dec_SelectLogic'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,2,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*2 of\n0 -> {andAUDITSelect,\n?RT_PER:decode_null(Bytes2)};\n1 -> {orAUDITSelect,\n?RT_PER:decode_null(Bytes2)};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_ContextAttrAuditRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,6},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type NULL\n?RT_PER:encode_null(Tmpval2)\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type NULL\n?RT_PER:encode_null(Tmpval3)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 3 with type NULL\n?RT_PER:encode_null(Tmpval4)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 4 with type NULL\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(?RT_PER:encode_null(Tmpval5)))\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 5 with type SEQUENCE OF\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_ContextAttrAuditRequest_contextPropAud'(Tmpval6)))\nend,\ncase element(7,Val1) of\nasn1_NOVALUE -> [];\nTmpval7 ->\n\n%% attribute number 6 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,15},16,{bits,4}}]\n begin\n case Tmpval7 of\n Tmpval8 when Tmpval8=<15,Tmpval8>=0 ->\n [10,4,Tmpval8- 0];\n Tmpval8 ->\n exit({error,{value_out_of_bounds,Tmpval8}})\n end\n\n end))\nend,\ncase element(8,Val1) of\nasn1_NOVALUE -> [];\nTmpval9 ->\n\n%% attribute number 7 with type BOOLEAN\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval9 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval9}}})\nend))\nend,\ncase element(9,Val1) of\nasn1_NOVALUE -> [];\nTmpval10 ->\n\n%% attribute number 8 with type BOOLEAN\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval10 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval10}}})\nend))\nend,\ncase element(10,Val1) of\nasn1_NOVALUE -> [];\nTmpval11 ->\n\n%% attribute number 9 with type Externaltypereference202megaco_per_bin_drv_media_gateway_control_v3SelectLogic\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_SelectLogic'(Tmpval11)))\nend].\n\n'enc_ContextAttrAuditRequest_contextPropAud'({'ContextAttrAuditRequest_contextPropAud',Val}) ->\n'enc_ContextAttrAuditRequest_contextPropAud'(Val);\n\n'enc_ContextAttrAuditRequest_contextPropAud'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ContextAttrAuditRequest_contextPropAud_components'(Val, [])\n].\n'enc_ContextAttrAuditRequest_contextPropAud_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ContextAttrAuditRequest_contextPropAud_components'([H|T], Acc) ->\n'enc_ContextAttrAuditRequest_contextPropAud_components'(T, ['enc_IndAudPropertyParm'(H)\n\n | Acc]).\n\n'dec_ContextAttrAuditRequest_contextPropAud'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ContextAttrAuditRequest_contextPropAud_components'(Num, Bytes1, telltype, []).\n'dec_ContextAttrAuditRequest_contextPropAud_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ContextAttrAuditRequest_contextPropAud_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_IndAudPropertyParm'(Bytes,telltype),\n 'dec_ContextAttrAuditRequest_contextPropAud_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ContextAttrAuditRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type NULL\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 ->?RT_PER:decode_null(Bytes2);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type NULL\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_null(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type NULL\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_null(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type NULL\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}=?RT_PER:decode_null(TmpVal4), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\n\n%% attribute number 5 with type SEQUENCE OF\n{Term5,Bytes8} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}='dec_ContextAttrAuditRequest_contextPropAud'(TmpVal5, telltype), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\n\n%% attribute number 6 with type INTEGER\n{Term6,Bytes9} = case Extensions of\n <<_:2,1:1,_\/bitstring>> when bit_size(Extensions) >= 3 ->\nbegin\n{TmpVal6,Trem6}=?RT_PER:decode_open_type(Bytes8,[]),\n{TmpValx6,_}= begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(TmpVal6,4),\n {Tmpterm1+0,Tmpremain1}\n end, {TmpValx6,Trem6}\nend;\n_ ->\n{asn1_NOVALUE,Bytes8}\n\nend,\n\n%% attribute number 7 with type BOOLEAN\n{Term7,Bytes10} = case Extensions of\n <<_:3,1:1,_\/bitstring>> when bit_size(Extensions) >= 4 ->\nbegin\n{TmpVal7,Trem7}=?RT_PER:decode_open_type(Bytes9,[]),\n{TmpValx7,_}=?RT_PER:decode_boolean(TmpVal7), {TmpValx7,Trem7}\nend;\n_ ->\n{asn1_NOVALUE,Bytes9}\n\nend,\n\n%% attribute number 8 with type BOOLEAN\n{Term8,Bytes11} = case Extensions of\n <<_:4,1:1,_\/bitstring>> when bit_size(Extensions) >= 5 ->\nbegin\n{TmpVal8,Trem8}=?RT_PER:decode_open_type(Bytes10,[]),\n{TmpValx8,_}=?RT_PER:decode_boolean(TmpVal8), {TmpValx8,Trem8}\nend;\n_ ->\n{asn1_NOVALUE,Bytes10}\n\nend,\n\n%% attribute number 9 with type SelectLogic\n{Term9,Bytes12} = case Extensions of\n <<_:5,1:1,_\/bitstring>> when bit_size(Extensions) >= 6 ->\nbegin\n{TmpVal9,Trem9}=?RT_PER:decode_open_type(Bytes11,[]),\n{TmpValx9,_}='dec_SelectLogic'(TmpVal9,telltype), {TmpValx9,Trem9}\nend;\n_ ->\n{asn1_NOVALUE,Bytes11}\n\nend,\nBytes13= ?RT_PER:skipextensions(Bytes12,7,Extensions)\n,\n{{'ContextAttrAuditRequest',Term1,Term2,Term3,Term4,Term5,Term6,Term7,Term8,Term9},Bytes13}.\n\n'enc_ContextRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2,3,4],3,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,3},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,15},16,{bits,4}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<15,Tmpval3>=0 ->\n [10,4,Tmpval3- 0];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval4 ->\n\n%% attribute number 2 with type BOOLEAN\ncase Tmpval4 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval4}}})\nend\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 3 with type SEQUENCE OF\n'enc_ContextRequest_topologyReq'(Tmpval5)\nend\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval6 ->\n\n%% attribute number 4 with type BOOLEAN\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(case Tmpval6 of\n true -> [1];\n false -> [0];\n _ -> exit({error,{asn1,{encode_boolean,Tmpval6}}})\nend))\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval7 ->\n\n%% attribute number 5 with type SEQUENCE OF\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_ContextRequest_contextProp'(Tmpval7)))\nend,\ncase element(7,Val1) of\nasn1_NOVALUE -> [];\nTmpval8 ->\n\n%% attribute number 6 with type SEQUENCE OF\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_ContextRequest_contextList'(Tmpval8)))\nend].\n\n'enc_ContextRequest_topologyReq'({'ContextRequest_topologyReq',Val}) ->\n'enc_ContextRequest_topologyReq'(Val);\n\n'enc_ContextRequest_topologyReq'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ContextRequest_topologyReq_components'(Val, [])\n].\n'enc_ContextRequest_topologyReq_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ContextRequest_topologyReq_components'([H|T], Acc) ->\n'enc_ContextRequest_topologyReq_components'(T, ['enc_TopologyRequest'(H)\n\n | Acc]).\n\n'dec_ContextRequest_topologyReq'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ContextRequest_topologyReq_components'(Num, Bytes1, telltype, []).\n'dec_ContextRequest_topologyReq_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ContextRequest_topologyReq_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_TopologyRequest'(Bytes,telltype),\n 'dec_ContextRequest_topologyReq_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'enc_ContextRequest_contextProp'({'ContextRequest_contextProp',Val}) ->\n'enc_ContextRequest_contextProp'(Val);\n\n'enc_ContextRequest_contextProp'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ContextRequest_contextProp_components'(Val, [])\n].\n'enc_ContextRequest_contextProp_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ContextRequest_contextProp_components'([H|T], Acc) ->\n'enc_ContextRequest_contextProp_components'(T, ['enc_PropertyParm'(H)\n\n | Acc]).\n\n'dec_ContextRequest_contextProp'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ContextRequest_contextProp_components'(Num, Bytes1, telltype, []).\n'dec_ContextRequest_contextProp_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ContextRequest_contextProp_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_PropertyParm'(Bytes,telltype),\n 'dec_ContextRequest_contextProp_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'enc_ContextRequest_contextList'({'ContextRequest_contextList',Val}) ->\n'enc_ContextRequest_contextList'(Val);\n\n'enc_ContextRequest_contextList'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ContextRequest_contextList_components'(Val, [])\n].\n'enc_ContextRequest_contextList_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ContextRequest_contextList_components'([H|T], Acc) ->\n'enc_ContextRequest_contextList_components'(T, [ %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],H) | Acc]).\n\n'dec_ContextRequest_contextList'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ContextRequest_contextList_components'(Num, Bytes1, telltype, []).\n'dec_ContextRequest_contextList_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ContextRequest_contextList_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = ?RT_PER:decode_constrained_number(Bytes,{0,4294967295},4294967296),\n 'dec_ContextRequest_contextList_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ContextRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,3), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = case Opt band (1 bsl 2) of\n _Opt1 when _Opt1 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes2,4),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 2 with type BOOLEAN\n{Term2,Bytes4} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_boolean(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type SEQUENCE OF\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_ContextRequest_topologyReq'(Bytes4, telltype);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type BOOLEAN\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}=?RT_PER:decode_boolean(TmpVal4), {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\n\n%% attribute number 5 with type SEQUENCE OF\n{Term5,Bytes8} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}='dec_ContextRequest_contextProp'(TmpVal5, telltype), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\n\n%% attribute number 6 with type SEQUENCE OF\n{Term6,Bytes9} = case Extensions of\n <<_:2,1:1,_\/bitstring>> when bit_size(Extensions) >= 3 ->\nbegin\n{TmpVal6,Trem6}=?RT_PER:decode_open_type(Bytes8,[]),\n{TmpValx6,_}='dec_ContextRequest_contextList'(TmpVal6, telltype), {TmpValx6,Trem6}\nend;\n_ ->\n{asn1_NOVALUE,Bytes8}\n\nend,\nBytes10= ?RT_PER:skipextensions(Bytes9,4,Extensions)\n,\n{{'ContextRequest',Term1,Term2,Term3,Term4,Term5,Term6},Bytes10}.\n\n'enc_ActionReply'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\nOpt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type Externaltypereference166megaco_per_bin_drv_media_gateway_control_v3ErrorDescriptor\n'enc_ErrorDescriptor'(Tmpval1)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type Externaltypereference167megaco_per_bin_drv_media_gateway_control_v3ContextRequest\n'enc_ContextRequest'(Tmpval2)\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_ActionReply_commandReply'(element(5,Val1))].\n\n'enc_ActionReply_commandReply'({'ActionReply_commandReply',Val}) ->\n'enc_ActionReply_commandReply'(Val);\n\n'enc_ActionReply_commandReply'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ActionReply_commandReply_components'(Val, [])\n].\n'enc_ActionReply_commandReply_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ActionReply_commandReply_components'([H|T], Acc) ->\n'enc_ActionReply_commandReply_components'(T, ['enc_CommandReply'(H)\n\n | Acc]).\n\n'dec_ActionReply_commandReply'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ActionReply_commandReply_components'(Num, Bytes1, telltype, []).\n'dec_ActionReply_commandReply_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ActionReply_commandReply_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_CommandReply'(Bytes,telltype),\n 'dec_ActionReply_commandReply_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ActionReply'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,2), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = ?RT_PER:decode_constrained_number(Bytes1,{0,4294967295},4294967296),\n\n%% attribute number 2 with type ErrorDescriptor\n{Term2,Bytes3} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->'dec_ErrorDescriptor'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 3 with type ContextRequest\n{Term3,Bytes4} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_ContextRequest'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes5} = 'dec_ActionReply_commandReply'(Bytes4, telltype),\n{{'ActionReply',Term1,Term2,Term3,Term4},Bytes5}.\n\n'enc_ActionRequest'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3,4],2,Val),\n[\nOpt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type Externaltypereference158megaco_per_bin_drv_media_gateway_control_v3ContextRequest\n'enc_ContextRequest'(Tmpval1)\nend,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 3 with type Externaltypereference159megaco_per_bin_drv_media_gateway_control_v3ContextAttrAuditRequest\n'enc_ContextAttrAuditRequest'(Tmpval2)\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n'enc_ActionRequest_commandRequests'(element(5,Val1))].\n\n'enc_ActionRequest_commandRequests'({'ActionRequest_commandRequests',Val}) ->\n'enc_ActionRequest_commandRequests'(Val);\n\n'enc_ActionRequest_commandRequests'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_ActionRequest_commandRequests_components'(Val, [])\n].\n'enc_ActionRequest_commandRequests_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_ActionRequest_commandRequests_components'([H|T], Acc) ->\n'enc_ActionRequest_commandRequests_components'(T, ['enc_CommandRequest'(H)\n\n | Acc]).\n\n'dec_ActionRequest_commandRequests'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_ActionRequest_commandRequests_components'(Num, Bytes1, telltype, []).\n'dec_ActionRequest_commandRequests_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_ActionRequest_commandRequests_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_CommandRequest'(Bytes,telltype),\n 'dec_ActionRequest_commandRequests_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_ActionRequest'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,2), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = ?RT_PER:decode_constrained_number(Bytes1,{0,4294967295},4294967296),\n\n%% attribute number 2 with type ContextRequest\n{Term2,Bytes3} = case Opt band (1 bsl 1) of\n _Opt2 when _Opt2 > 0 ->'dec_ContextRequest'(Bytes2,telltype);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n\n%% attribute number 3 with type ContextAttrAuditRequest\n{Term3,Bytes4} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->'dec_ContextAttrAuditRequest'(Bytes3,telltype);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 4 with type SEQUENCE OF\n{Term4,Bytes5} = 'dec_ActionRequest_commandRequests'(Bytes4, telltype),\n{{'ActionRequest',Term1,Term2,Term3,Term4},Bytes5}.\n\n\n'enc_ContextID'({'ContextID',Val}) ->\n'enc_ContextID'(Val);\n\n'enc_ContextID'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Val).\n\n\n'dec_ContextID'(Bytes,_) ->\n?RT_PER:decode_constrained_number(Bytes,{0,4294967295},4294967296).\n\n\n'enc_ErrorText'({'ErrorText',Val}) ->\n'enc_ErrorText'(Val);\n\n'enc_ErrorText'(Val) ->\n?RT_PER:encode_known_multiplier_string('IA5String',no,8,{0,127,notab},Val).\n\n\n'dec_ErrorText'(Bytes,_) ->\n?RT_PER:decode_known_multiplier_string('IA5String',no,8,{0,127,notab},Bytes).\n\n\n'enc_ErrorCode'({'ErrorCode',Val}) ->\n'enc_ErrorCode'(Val);\n\n'enc_ErrorCode'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n case Val of \n Tmpval1 when Tmpval1=<65535,Tmpval1>=0 ->\n [20,2,<<(Tmpval1- 0):16>>];\n Tmpval1 ->\n exit({error,{value_out_of_bounds,Tmpval1}})\n end\n.\n\n\n'dec_ErrorCode'(Bytes,_) ->\n begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end.\n\n'enc_ErrorDescriptor'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 2 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',no,8,{0,127,notab},Tmpval3)\nend].\n\n\n'dec_ErrorDescriptor'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes1,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type IA5String\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_known_multiplier_string('IA5String',no,8,{0,127,notab},Bytes2);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'ErrorDescriptor',Term1,Term2},Bytes3}.\n\n'enc_TransactionAck'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Tmpval1)\nend].\n\n\n'dec_TransactionAck'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = ?RT_PER:decode_constrained_number(Bytes1,{0,4294967295},4294967296),\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296);\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'TransactionAck',Term1,Term2},Bytes3}.\n\n\n'enc_TransactionResponseAck'({'TransactionResponseAck',Val}) ->\n'enc_TransactionResponseAck'(Val);\n\n'enc_TransactionResponseAck'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TransactionResponseAck_components'(Val, [])\n].\n'enc_TransactionResponseAck_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TransactionResponseAck_components'([H|T], Acc) ->\n'enc_TransactionResponseAck_components'(T, ['enc_TransactionAck'(H)\n\n | Acc]).\n\n\n'dec_TransactionResponseAck'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TransactionResponseAck_components'(Num, Bytes1, telltype, []).\n'dec_TransactionResponseAck_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TransactionResponseAck_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_TransactionAck'(Bytes,telltype),\n 'dec_TransactionResponseAck_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'enc_SegmentNumber'({'SegmentNumber',Val}) ->\n'enc_SegmentNumber'(Val);\n\n'enc_SegmentNumber'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n case Val of \n Tmpval1 when Tmpval1=<65535,Tmpval1>=0 ->\n [20,2,<<(Tmpval1- 0):16>>];\n Tmpval1 ->\n exit({error,{value_out_of_bounds,Tmpval1}})\n end\n.\n\n\n'dec_SegmentNumber'(Bytes,_) ->\n begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes,2),\n {Tmpterm1+0,Tmpremain1}\n end.\n\n'enc_SegmentReply'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([4],1,Val),\n[\n?RT_PER:setext(false), Opt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n Tmpval1=element(3,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\ncase element(4,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 3 with type NULL\n?RT_PER:encode_null(Tmpval3)\nend].\n\n\n'dec_SegmentReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = ?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296),\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes4} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes3,2),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 3 with type NULL\n{Term3,Bytes5} = case Opt band (1 bsl 0) of\n _Opt3 when _Opt3 > 0 ->?RT_PER:decode_null(Bytes4);\n0 ->{asn1_NOVALUE,Bytes4}\n\nend,\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\nBytes7= ?RT_PER:skipextensions(Bytes6,1,Extensions)\n,\n{{'SegmentReply',Term1,Term2,Term3},Bytes7}.\n\n'enc_TransactionReply'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\nExtensions = ?RT_PER:fixextensions({ext,4,2},Val1),\n[\n?RT_PER:setext(Extensions =\/= []), Opt,\n\n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type NULL\n?RT_PER:encode_null(Tmpval2)\nend,\n\n%% attribute number 3 with type CHOICE\n'enc_TransactionReply_transactionResult'(element(4,Val1))\n,Extensions\n,\ncase element(5,Val1) of\nasn1_NOVALUE -> [];\nTmpval3 ->\n\n%% attribute number 4 with type INTEGER\n?RT_PER:encode_open_type(dummy,?RT_PER:complete( %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval3 of\n Tmpval4 when Tmpval4=<65535,Tmpval4>=0 ->\n [20,2,<<(Tmpval4- 0):16>>];\n Tmpval4 ->\n exit({error,{value_out_of_bounds,Tmpval4}})\n end\n\n end))\nend,\ncase element(6,Val1) of\nasn1_NOVALUE -> [];\nTmpval5 ->\n\n%% attribute number 5 with type NULL\n?RT_PER:encode_open_type(dummy,?RT_PER:complete(?RT_PER:encode_null(Tmpval5)))\nend].\n\n'enc_TransactionReply_transactionResult'({'TransactionReply_transactionResult',Val}) ->\n'enc_TransactionReply_transactionResult'(Val);\n\n'enc_TransactionReply_transactionResult'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[transactionError,actionReplies], 2),\ncase element(1,Val) of\ntransactionError ->\n'enc_ErrorDescriptor'(element(2,Val));\nactionReplies ->\n'enc_TransactionReply_transactionResult_actionReplies'(element(2,Val))\nend\n].\n\n'enc_TransactionReply_transactionResult_actionReplies'({'TransactionReply_transactionResult_actionReplies',Val}) ->\n'enc_TransactionReply_transactionResult_actionReplies'(Val);\n\n'enc_TransactionReply_transactionResult_actionReplies'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TransactionReply_transactionResult_actionReplies_components'(Val, [])\n].\n'enc_TransactionReply_transactionResult_actionReplies_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TransactionReply_transactionResult_actionReplies_components'([H|T], Acc) ->\n'enc_TransactionReply_transactionResult_actionReplies_components'(T, ['enc_ActionReply'(H)\n\n | Acc]).\n\n'dec_TransactionReply_transactionResult_actionReplies'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TransactionReply_transactionResult_actionReplies_components'(Num, Bytes1, telltype, []).\n'dec_TransactionReply_transactionResult_actionReplies_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TransactionReply_transactionResult_actionReplies_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_ActionReply'(Bytes,telltype),\n 'dec_TransactionReply_transactionResult_actionReplies_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'dec_TransactionReply_transactionResult'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {transactionError,\n'dec_ErrorDescriptor'(Bytes1,telltype)};\n1 -> {actionReplies,\n'dec_TransactionReply_transactionResult_actionReplies'(Bytes1, telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_TransactionReply'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n{Opt,Bytes2} = ?RT_PER:getoptionals2(Bytes1,1), \n%% attribute number 1 with type INTEGER\n{Term1,Bytes3} = ?RT_PER:decode_constrained_number(Bytes2,{0,4294967295},4294967296),\n\n%% attribute number 2 with type NULL\n{Term2,Bytes4} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 ->?RT_PER:decode_null(Bytes3);\n0 ->{asn1_NOVALUE,Bytes3}\n\nend,\n\n%% attribute number 3 with type CHOICE\n{Term3,Bytes5} = 'dec_TransactionReply_transactionResult'(Bytes4, telltype),\n{Extensions,Bytes6} = ?RT_PER:getextension(Ext,Bytes5),\n\n%% attribute number 4 with type INTEGER\n{Term4,Bytes7} = case Extensions of\n <<_:0,1:1,_\/bitstring>> when bit_size(Extensions) >= 1 ->\nbegin\n{TmpVal4,Trem4}=?RT_PER:decode_open_type(Bytes6,[]),\n{TmpValx4,_}= begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(TmpVal4,2),\n {Tmpterm1+0,Tmpremain1}\n end, {TmpValx4,Trem4}\nend;\n_ ->\n{asn1_NOVALUE,Bytes6}\n\nend,\n\n%% attribute number 5 with type NULL\n{Term5,Bytes8} = case Extensions of\n <<_:1,1:1,_\/bitstring>> when bit_size(Extensions) >= 2 ->\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes7,[]),\n{TmpValx5,_}=?RT_PER:decode_null(TmpVal5), {TmpValx5,Trem5}\nend;\n_ ->\n{asn1_NOVALUE,Bytes7}\n\nend,\nBytes9= ?RT_PER:skipextensions(Bytes8,3,Extensions)\n,\n{{'TransactionReply',Term1,Term2,Term3,Term4,Term5},Bytes9}.\n\n'enc_TransactionPending'(Val) ->\nVal1 = ?RT_PER:list_to_record('TransactionPending', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1))].\n\n\n'dec_TransactionPending'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = ?RT_PER:decode_constrained_number(Bytes1,{0,4294967295},4294967296),\n{Extensions,Bytes3} = ?RT_PER:getextension(Ext,Bytes2),\nBytes4= ?RT_PER:skipextensions(Bytes3,1,Extensions)\n,\n{{'TransactionPending',Term1},Bytes4}.\n\n'enc_TransactionRequest'(Val) ->\nVal1 = ?RT_PER:list_to_record('TransactionRequest', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],element(2,Val1)),\n\n%% attribute number 2 with type SEQUENCE OF\n'enc_TransactionRequest_actions'(element(3,Val1))].\n\n'enc_TransactionRequest_actions'({'TransactionRequest_actions',Val}) ->\n'enc_TransactionRequest_actions'(Val);\n\n'enc_TransactionRequest_actions'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_TransactionRequest_actions_components'(Val, [])\n].\n'enc_TransactionRequest_actions_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_TransactionRequest_actions_components'([H|T], Acc) ->\n'enc_TransactionRequest_actions_components'(T, ['enc_ActionRequest'(H)\n\n | Acc]).\n\n'dec_TransactionRequest_actions'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_TransactionRequest_actions_components'(Num, Bytes1, telltype, []).\n'dec_TransactionRequest_actions_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_TransactionRequest_actions_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_ActionRequest'(Bytes,telltype),\n 'dec_TransactionRequest_actions_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n\n'dec_TransactionRequest'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = ?RT_PER:decode_constrained_number(Bytes1,{0,4294967295},4294967296),\n\n%% attribute number 2 with type SEQUENCE OF\n{Term2,Bytes3} = 'dec_TransactionRequest_actions'(Bytes2, telltype),\n{Extensions,Bytes4} = ?RT_PER:getextension(Ext,Bytes3),\nBytes5= ?RT_PER:skipextensions(Bytes4,1,Extensions)\n,\n{{'TransactionRequest',Term1,Term2},Bytes5}.\n\n\n'enc_TransactionId'({'TransactionId',Val}) ->\n'enc_TransactionId'(Val);\n\n'enc_TransactionId'(Val) ->\n %%INTEGER with effective constraint: [{'ValueRange',{0,4294967295}}]\n ?RT_PER:encode_integer([{'ValueRange',{0,4294967295}}],Val).\n\n\n'dec_TransactionId'(Bytes,_) ->\n?RT_PER:decode_constrained_number(Bytes,{0,4294967295},4294967296).\n\n\n'enc_Transaction'({'Transaction',Val}) ->\n'enc_Transaction'(Val);\n\n'enc_Transaction'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[transactionRequest,transactionPending,transactionReply,transactionResponseAck],[segmentReply]}, {4,1}),\ncase element(1,Val) of\ntransactionRequest ->\n'enc_TransactionRequest'(element(2,Val));\ntransactionPending ->\n'enc_TransactionPending'(element(2,Val));\ntransactionReply ->\n'enc_TransactionReply'(element(2,Val));\ntransactionResponseAck ->\n'enc_TransactionResponseAck'(element(2,Val));\nsegmentReply ->\n?RT_PER:encode_open_type(dummy,?RT_PER:complete('enc_SegmentReply'(element(2,Val))))\nend\n].\n\n\n'dec_Transaction'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,4,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*4 of\n0 -> {transactionRequest,\n'dec_TransactionRequest'(Bytes2,telltype)};\n1 -> {transactionPending,\n'dec_TransactionPending'(Bytes2,telltype)};\n2 -> {transactionReply,\n'dec_TransactionReply'(Bytes2,telltype)};\n3 -> {transactionResponseAck,\n'dec_TransactionResponseAck'(Bytes2,telltype)};\n4 -> {segmentReply,\nbegin\n{TmpVal5,Trem5}=?RT_PER:decode_open_type(Bytes2,[]),\n{TmpValx5,_}='dec_SegmentReply'(TmpVal5,telltype), {TmpValx5,Trem5}\nend};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n\n'enc_PathName'({'PathName',Val}) ->\n'enc_PathName'(Val);\n\n'enc_PathName'(Val) ->\n?RT_PER:encode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},Val).\n\n\n'dec_PathName'(Bytes,_) ->\n?RT_PER:decode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},Bytes).\n\n'enc_IP6Address'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 16 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend].\n\n\n'dec_IP6Address'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,16,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes2,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'IP6Address',Term1,Term2},Bytes3}.\n\n'enc_IP4Address'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval2 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval2 of\n Tmpval3 when Tmpval3=<65535,Tmpval3>=0 ->\n [20,2,<<(Tmpval3- 0):16>>];\n Tmpval3 ->\n exit({error,{value_out_of_bounds,Tmpval3}})\n end\n\n end\nend].\n\n\n'dec_IP4Address'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,4,false)\n,\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes2,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'IP4Address',Term1,Term2},Bytes3}.\n\n'enc_DomainName'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([3],1,Val),\n[\nOpt,\n\n%% attribute number 1 with type IA5String\n?RT_PER:encode_known_multiplier_string('IA5String',no,8,{0,127,notab},element(2,Val1)),\ncase element(3,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 2 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,65535},65536,{octets,2}}]\n begin\n case Tmpval1 of\n Tmpval2 when Tmpval2=<65535,Tmpval2>=0 ->\n [20,2,<<(Tmpval2- 0):16>>];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end\nend].\n\n\n'dec_DomainName'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type IA5String\n{Term1,Bytes2} = ?RT_PER:decode_known_multiplier_string('IA5String',no,8,{0,127,notab},Bytes1),\n\n%% attribute number 2 with type INTEGER\n{Term2,Bytes3} = case Opt band (1 bsl 0) of\n _Opt2 when _Opt2 > 0 -> begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getoctets(Bytes2,2),\n {Tmpterm1+0,Tmpremain1}\n end;\n0 ->{asn1_NOVALUE,Bytes2}\n\nend,\n{{'DomainName',Term1,Term2},Bytes3}.\n\n\n'enc_MId'({'MId',Val}) ->\n'enc_MId'(Val);\n\n'enc_MId'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),{[ip4Address,ip6Address,domainName,deviceName,mtpAddress],[]}, {5,0}),\ncase element(1,Val) of\nip4Address ->\n'enc_IP4Address'(element(2,Val));\nip6Address ->\n'enc_IP6Address'(element(2,Val));\ndomainName ->\n'enc_DomainName'(element(2,Val));\ndeviceName ->\n?RT_PER:encode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},element(2,Val));\nmtpAddress ->\n ?RT_PER:encode_octet_string({2,4},false,element(2,Val))\n\nend\n].\n\n\n'dec_MId'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getbit(Bytes),\n{Choice,Bytes2} = ?RT_PER:getchoice(Bytes1,5,Ext ),\n{Cname,{Val,NewBytes}} = case Choice + Ext*5 of\n0 -> {ip4Address,\n'dec_IP4Address'(Bytes2,telltype)};\n1 -> {ip6Address,\n'dec_IP6Address'(Bytes2,telltype)};\n2 -> {domainName,\n'dec_DomainName'(Bytes2,telltype)};\n3 -> {deviceName,\n?RT_PER:decode_known_multiplier_string('IA5String',{1,64},8,{0,127,notab},Bytes2)};\n4 -> {mtpAddress,\n ?RT_PER:decode_octet_string(Bytes2,{2,4},false)\n};\n_ -> {asn1_ExtAlt, ?RT_PER:decode_open_type(Bytes2,[])}\nend,\n\n{{Cname,Val},NewBytes}.\n'enc_Message'(Val) ->\nVal1 = ?RT_PER:list_to_record('Message', Val),\n[\n?RT_PER:setext(false), \n%% attribute number 1 with type INTEGER\n %%INTEGER with effective constraint: [{'ValueRange',{0,99},100,{bits,7}}]\n begin\n Tmpval1=element(2,Val1),\n case Tmpval1 of\n Tmpval2 when Tmpval2=<99,Tmpval2>=0 ->\n [10,7,Tmpval2- 0];\n Tmpval2 ->\n exit({error,{value_out_of_bounds,Tmpval2}})\n end\n\n end,\n\n%% attribute number 2 with type Externaltypereference31megaco_per_bin_drv_media_gateway_control_v3MId\n'enc_MId'(element(3,Val1)),\n\n%% attribute number 3 with type CHOICE\n'enc_Message_messageBody'(element(4,Val1))].\n\n'enc_Message_messageBody'({'Message_messageBody',Val}) ->\n'enc_Message_messageBody'(Val);\n\n'enc_Message_messageBody'(Val) ->\n[\n?RT_PER:set_choice(element(1,Val),[messageError,transactions], 2),\ncase element(1,Val) of\nmessageError ->\n'enc_ErrorDescriptor'(element(2,Val));\ntransactions ->\n'enc_Message_messageBody_transactions'(element(2,Val))\nend\n].\n\n'enc_Message_messageBody_transactions'({'Message_messageBody_transactions',Val}) ->\n'enc_Message_messageBody_transactions'(Val);\n\n'enc_Message_messageBody_transactions'(Val) ->\n[\n\n ?RT_PER:encode_length(undefined,length(Val)),\n 'enc_Message_messageBody_transactions_components'(Val, [])\n].\n'enc_Message_messageBody_transactions_components'([], Acc) -> lists:reverse(Acc);\n\n'enc_Message_messageBody_transactions_components'([H|T], Acc) ->\n'enc_Message_messageBody_transactions_components'(T, ['enc_Transaction'(H)\n\n | Acc]).\n\n'dec_Message_messageBody_transactions'(Bytes,_) ->\n\n{Num,Bytes1} = ?RT_PER:decode_length(Bytes,undefined),\n'dec_Message_messageBody_transactions_components'(Num, Bytes1, telltype, []).\n'dec_Message_messageBody_transactions_components'(0, Bytes, _, Acc) ->\n {lists:reverse(Acc), Bytes};\n'dec_Message_messageBody_transactions_components'(Num, Bytes, _, Acc) ->\n {Term,Remain} = 'dec_Transaction'(Bytes,telltype),\n 'dec_Message_messageBody_transactions_components'(Num-1, Remain, telltype, [Term|Acc]).\n\n'dec_Message_messageBody'(Bytes,_) ->\n{Choice,Bytes1} = ?RT_PER:getchoice(Bytes,2, 0),\n{Cname,{Val,NewBytes}} = case Choice of\n0 -> {messageError,\n'dec_ErrorDescriptor'(Bytes1,telltype)};\n1 -> {transactions,\n'dec_Message_messageBody_transactions'(Bytes1, telltype)}\nend,\n\n{{Cname,Val},NewBytes}.\n\n\n'dec_Message'(Bytes,_) ->\n{Ext,Bytes1} = ?RT_PER:getext(Bytes),\n\n%% attribute number 1 with type INTEGER\n{Term1,Bytes2} = begin\n {Tmpterm1,Tmpremain1}=?RT_PER:getbits(Bytes1,7),\n {Tmpterm1+0,Tmpremain1}\n end,\n\n%% attribute number 2 with type MId\n{Term2,Bytes3} = 'dec_MId'(Bytes2,telltype),\n\n%% attribute number 3 with type CHOICE\n{Term3,Bytes4} = 'dec_Message_messageBody'(Bytes3, telltype),\n{Extensions,Bytes5} = ?RT_PER:getextension(Ext,Bytes4),\nBytes6= ?RT_PER:skipextensions(Bytes5,1,Extensions)\n,\n{{'Message',Term1,Term2,Term3},Bytes6}.\n\n\n'enc_AuthData'({'AuthData',Val}) ->\n'enc_AuthData'(Val);\n\n'enc_AuthData'(Val) ->\n ?RT_PER:encode_octet_string({12,32},false,Val)\n.\n\n\n'dec_AuthData'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,{12,32},false)\n.\n\n\n'enc_SequenceNum'({'SequenceNum',Val}) ->\n'enc_SequenceNum'(Val);\n\n'enc_SequenceNum'(Val) ->\n begin\n case length(Val) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,Val];\n _ -> exit({error,{value_out_of_bounds,Val}})\n end\n end.\n\n\n'dec_SequenceNum'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,4,false)\n.\n\n\n'enc_SecurityParmIndex'({'SecurityParmIndex',Val}) ->\n'enc_SecurityParmIndex'(Val);\n\n'enc_SecurityParmIndex'(Val) ->\n begin\n case length(Val) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,Val];\n _ -> exit({error,{value_out_of_bounds,Val}})\n end\n end.\n\n\n'dec_SecurityParmIndex'(Bytes,_) ->\n ?RT_PER:decode_octet_string(Bytes,4,false)\n.\n\n'enc_AuthenticationHeader'(Val) ->\nVal1 = ?RT_PER:list_to_record('AuthenticationHeader', Val),\n[\n\n%% attribute number 1 with type OCTET STRING\n begin\n case length(element(2,Val1)) of\n Tmpval1 when Tmpval1 == 4 -> [2,20,Tmpval1,element(2,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(2,Val1)}})\n end\n end,\n\n%% attribute number 2 with type OCTET STRING\n begin\n case length(element(3,Val1)) of\n Tmpval2 when Tmpval2 == 4 -> [2,20,Tmpval2,element(3,Val1)];\n _ -> exit({error,{value_out_of_bounds,element(3,Val1)}})\n end\n end,\n\n%% attribute number 3 with type OCTET STRING\n ?RT_PER:encode_octet_string({12,32},false,element(4,Val1))\n].\n\n\n'dec_AuthenticationHeader'(Bytes,_) ->\n\n%% attribute number 1 with type OCTET STRING\n{Term1,Bytes1} = ?RT_PER:decode_octet_string(Bytes,4,false)\n,\n\n%% attribute number 2 with type OCTET STRING\n{Term2,Bytes2} = ?RT_PER:decode_octet_string(Bytes1,4,false)\n,\n\n%% attribute number 3 with type OCTET STRING\n{Term3,Bytes3} = ?RT_PER:decode_octet_string(Bytes2,{12,32},false)\n,\n{{'AuthenticationHeader',Term1,Term2,Term3},Bytes3}.\n\n'enc_MegacoMessage'(Val) ->\n{Val1,Opt} = ?RT_PER:fixoptionals([2],1,Val),\n[\nOpt,\ncase element(2,Val1) of\nasn1_NOVALUE -> [];\nTmpval1 ->\n\n%% attribute number 1 with type Externaltypereference10megaco_per_bin_drv_media_gateway_control_v3AuthenticationHeader\n'enc_AuthenticationHeader'(Tmpval1)\nend,\n\n%% attribute number 2 with type Externaltypereference11megaco_per_bin_drv_media_gateway_control_v3Message\n'enc_Message'(element(3,Val1))].\n\n\n'dec_MegacoMessage'(Bytes,_) ->\n{Opt,Bytes1} = ?RT_PER:getoptionals2(Bytes,1), \n%% attribute number 1 with type AuthenticationHeader\n{Term1,Bytes2} = case Opt band (1 bsl 0) of\n _Opt1 when _Opt1 > 0 ->'dec_AuthenticationHeader'(Bytes1,telltype);\n0 ->{asn1_NOVALUE,Bytes1}\n\nend,\n\n%% attribute number 2 with type Message\n{Term2,Bytes3} = 'dec_Message'(Bytes2,telltype),\n{{'MegacoMessage',Term1,Term2},Bytes3}.\n\n","avg_line_length":30.7164814052,"max_line_length":1182,"alphanum_fraction":0.7406838195} +{"size":33832,"ext":"erl","lang":"Erlang","max_stars_count":3.0,"content":"-file(\"\/usr\/local\/lib\/erlang\/lib\/parsetools-2.1.1\/include\/leexinc.hrl\", 0).\n%% The source of this file is part of leex distribution, as such it\n%% has the same Copyright as the other files in the leex\n%% distribution. The Copyright is defined in the accompanying file\n%% COPYRIGHT. However, the resultant scanner generated by leex is the\n%% property of the creator of the scanner and is not covered by that\n%% Copyright.\n\n-module(from_whitespace_lexer).\n\n-export([string\/1,string\/2,token\/2,token\/3,tokens\/2,tokens\/3]).\n-export([format_error\/1]).\n\n%% User code. This is placed here to allow extra attributes.\n-file(\"priv\/from_whitespace_lexer.xrl\", 75).\n\nextract_number_or_label(StartIdx, TokenChars) ->\n %io:format(\"XXX StartIdx: ~p. TokenChars: ~p~n\", [StartIdx, TokenChars]),\n % The number starts at StartIdx (1-based), but nthtail is 0-based\n lists:nthtail(StartIdx - 1, TokenChars).\n\n\n-file(\"\/usr\/local\/lib\/erlang\/lib\/parsetools-2.1.1\/include\/leexinc.hrl\", 14).\n\nformat_error({illegal,S}) -> [\"illegal characters \",io_lib:write_string(S)];\nformat_error({user,S}) -> S.\n\nstring(String) -> string(String, 1).\n\nstring(String, Line) -> string(String, Line, String, []).\n\n%% string(InChars, Line, TokenChars, Tokens) ->\n%% {ok,Tokens,Line} | {error,ErrorInfo,Line}.\n%% Note the line number going into yystate, L0, is line of token\n%% start while line number returned is line of token end. We want line\n%% of token start.\n\nstring([], L, [], Ts) -> % No partial tokens!\n {ok,yyrev(Ts),L};\nstring(Ics0, L0, Tcs, Ts) ->\n case yystate(yystate(), Ics0, L0, 0, reject, 0) of\n {A,Alen,Ics1,L1} -> % Accepting end state\n string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);\n {A,Alen,Ics1,L1,_S1} -> % Accepting transistion state\n string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);\n {reject,_Alen,Tlen,_Ics1,L1,_S1} -> % After a non-accepting state\n {error,{L0,?MODULE,{illegal,yypre(Tcs, Tlen+1)}},L1};\n {A,Alen,_Tlen,_Ics1,_L1,_S1} ->\n string_cont(yysuf(Tcs, Alen), L0, yyaction(A, Alen, Tcs, L0), Ts)\n end.\n\n%% string_cont(RestChars, Line, Token, Tokens)\n%% Test for and remove the end token wrapper. Push back characters\n%% are prepended to RestChars.\n\n-dialyzer({nowarn_function, string_cont\/4}).\n\nstring_cont(Rest, Line, {token,T}, Ts) ->\n string(Rest, Line, Rest, [T|Ts]);\nstring_cont(Rest, Line, {token,T,Push}, Ts) ->\n NewRest = Push ++ Rest,\n string(NewRest, Line, NewRest, [T|Ts]);\nstring_cont(Rest, Line, {end_token,T}, Ts) ->\n string(Rest, Line, Rest, [T|Ts]);\nstring_cont(Rest, Line, {end_token,T,Push}, Ts) ->\n NewRest = Push ++ Rest,\n string(NewRest, Line, NewRest, [T|Ts]);\nstring_cont(Rest, Line, skip_token, Ts) ->\n string(Rest, Line, Rest, Ts);\nstring_cont(Rest, Line, {skip_token,Push}, Ts) ->\n NewRest = Push ++ Rest,\n string(NewRest, Line, NewRest, Ts);\nstring_cont(_Rest, Line, {error,S}, _Ts) ->\n {error,{Line,?MODULE,{user,S}},Line}.\n\n%% token(Continuation, Chars) ->\n%% token(Continuation, Chars, Line) ->\n%% {more,Continuation} | {done,ReturnVal,RestChars}.\n%% Must be careful when re-entering to append the latest characters to the\n%% after characters in an accept. The continuation is:\n%% {token,State,CurrLine,TokenChars,TokenLen,TokenLine,AccAction,AccLen}\n\ntoken(Cont, Chars) -> token(Cont, Chars, 1).\n\ntoken([], Chars, Line) ->\n token(yystate(), Chars, Line, Chars, 0, Line, reject, 0);\ntoken({token,State,Line,Tcs,Tlen,Tline,Action,Alen}, Chars, _) ->\n token(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Action, Alen).\n\n%% token(State, InChars, Line, TokenChars, TokenLen, TokenLine,\n%% AcceptAction, AcceptLen) ->\n%% {more,Continuation} | {done,ReturnVal,RestChars}.\n%% The argument order is chosen to be more efficient.\n\ntoken(S0, Ics0, L0, Tcs, Tlen0, Tline, A0, Alen0) ->\n case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of\n %% Accepting end state, we have a token.\n {A1,Alen1,Ics1,L1} ->\n token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));\n %% Accepting transition state, can take more chars.\n {A1,Alen1,[],L1,S1} -> % Need more chars to check\n {more,{token,S1,L1,Tcs,Alen1,Tline,A1,Alen1}};\n {A1,Alen1,Ics1,L1,_S1} -> % Take what we got\n token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));\n %% After a non-accepting state, maybe reach accept state later.\n {A1,Alen1,Tlen1,[],L1,S1} -> % Need more chars to check\n {more,{token,S1,L1,Tcs,Tlen1,Tline,A1,Alen1}};\n {reject,_Alen1,Tlen1,eof,L1,_S1} -> % No token match\n %% Check for partial token which is error.\n Ret = if Tlen1 > 0 -> {error,{Tline,?MODULE,\n %% Skip eof tail in Tcs.\n {illegal,yypre(Tcs, Tlen1)}},L1};\n true -> {eof,L1}\n end,\n {done,Ret,eof};\n {reject,_Alen1,Tlen1,Ics1,L1,_S1} -> % No token match\n Error = {Tline,?MODULE,{illegal,yypre(Tcs, Tlen1+1)}},\n {done,{error,Error,L1},Ics1};\n {A1,Alen1,_Tlen1,_Ics1,_L1,_S1} -> % Use last accept match\n token_cont(yysuf(Tcs, Alen1), L0, yyaction(A1, Alen1, Tcs, Tline))\n end.\n\n%% token_cont(RestChars, Line, Token)\n%% If we have a token or error then return done, else if we have a\n%% skip_token then continue.\n\n-dialyzer({nowarn_function, token_cont\/3}).\n\ntoken_cont(Rest, Line, {token,T}) ->\n {done,{ok,T,Line},Rest};\ntoken_cont(Rest, Line, {token,T,Push}) ->\n NewRest = Push ++ Rest,\n {done,{ok,T,Line},NewRest};\ntoken_cont(Rest, Line, {end_token,T}) ->\n {done,{ok,T,Line},Rest};\ntoken_cont(Rest, Line, {end_token,T,Push}) ->\n NewRest = Push ++ Rest,\n {done,{ok,T,Line},NewRest};\ntoken_cont(Rest, Line, skip_token) ->\n token(yystate(), Rest, Line, Rest, 0, Line, reject, 0);\ntoken_cont(Rest, Line, {skip_token,Push}) ->\n NewRest = Push ++ Rest,\n token(yystate(), NewRest, Line, NewRest, 0, Line, reject, 0);\ntoken_cont(Rest, Line, {error,S}) ->\n {done,{error,{Line,?MODULE,{user,S}},Line},Rest}.\n\n%% tokens(Continuation, Chars, Line) ->\n%% {more,Continuation} | {done,ReturnVal,RestChars}.\n%% Must be careful when re-entering to append the latest characters to the\n%% after characters in an accept. The continuation is:\n%% {tokens,State,CurrLine,TokenChars,TokenLen,TokenLine,Tokens,AccAction,AccLen}\n%% {skip_tokens,State,CurrLine,TokenChars,TokenLen,TokenLine,Error,AccAction,AccLen}\n\ntokens(Cont, Chars) -> tokens(Cont, Chars, 1).\n\ntokens([], Chars, Line) ->\n tokens(yystate(), Chars, Line, Chars, 0, Line, [], reject, 0);\ntokens({tokens,State,Line,Tcs,Tlen,Tline,Ts,Action,Alen}, Chars, _) ->\n tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Ts, Action, Alen);\ntokens({skip_tokens,State,Line,Tcs,Tlen,Tline,Error,Action,Alen}, Chars, _) ->\n skip_tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Error, Action, Alen).\n\n%% tokens(State, InChars, Line, TokenChars, TokenLen, TokenLine, Tokens,\n%% AcceptAction, AcceptLen) ->\n%% {more,Continuation} | {done,ReturnVal,RestChars}.\n\ntokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Ts, A0, Alen0) ->\n case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of\n %% Accepting end state, we have a token.\n {A1,Alen1,Ics1,L1} ->\n tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);\n %% Accepting transition state, can take more chars.\n {A1,Alen1,[],L1,S1} -> % Need more chars to check\n {more,{tokens,S1,L1,Tcs,Alen1,Tline,Ts,A1,Alen1}};\n {A1,Alen1,Ics1,L1,_S1} -> % Take what we got\n tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);\n %% After a non-accepting state, maybe reach accept state later.\n {A1,Alen1,Tlen1,[],L1,S1} -> % Need more chars to check\n {more,{tokens,S1,L1,Tcs,Tlen1,Tline,Ts,A1,Alen1}};\n {reject,_Alen1,Tlen1,eof,L1,_S1} -> % No token match\n %% Check for partial token which is error, no need to skip here.\n Ret = if Tlen1 > 0 -> {error,{Tline,?MODULE,\n %% Skip eof tail in Tcs.\n {illegal,yypre(Tcs, Tlen1)}},L1};\n Ts == [] -> {eof,L1};\n true -> {ok,yyrev(Ts),L1}\n end,\n {done,Ret,eof};\n {reject,_Alen1,Tlen1,_Ics1,L1,_S1} ->\n %% Skip rest of tokens.\n Error = {L1,?MODULE,{illegal,yypre(Tcs, Tlen1+1)}},\n skip_tokens(yysuf(Tcs, Tlen1+1), L1, Error);\n {A1,Alen1,_Tlen1,_Ics1,_L1,_S1} ->\n Token = yyaction(A1, Alen1, Tcs, Tline),\n tokens_cont(yysuf(Tcs, Alen1), L0, Token, Ts)\n end.\n\n%% tokens_cont(RestChars, Line, Token, Tokens)\n%% If we have an end_token or error then return done, else if we have\n%% a token then save it and continue, else if we have a skip_token\n%% just continue.\n\n-dialyzer({nowarn_function, tokens_cont\/4}).\n\ntokens_cont(Rest, Line, {token,T}, Ts) ->\n tokens(yystate(), Rest, Line, Rest, 0, Line, [T|Ts], reject, 0);\ntokens_cont(Rest, Line, {token,T,Push}, Ts) ->\n NewRest = Push ++ Rest,\n tokens(yystate(), NewRest, Line, NewRest, 0, Line, [T|Ts], reject, 0);\ntokens_cont(Rest, Line, {end_token,T}, Ts) ->\n {done,{ok,yyrev(Ts, [T]),Line},Rest};\ntokens_cont(Rest, Line, {end_token,T,Push}, Ts) ->\n NewRest = Push ++ Rest,\n {done,{ok,yyrev(Ts, [T]),Line},NewRest};\ntokens_cont(Rest, Line, skip_token, Ts) ->\n tokens(yystate(), Rest, Line, Rest, 0, Line, Ts, reject, 0);\ntokens_cont(Rest, Line, {skip_token,Push}, Ts) ->\n NewRest = Push ++ Rest,\n tokens(yystate(), NewRest, Line, NewRest, 0, Line, Ts, reject, 0);\ntokens_cont(Rest, Line, {error,S}, _Ts) ->\n skip_tokens(Rest, Line, {Line,?MODULE,{user,S}}).\n\n%%skip_tokens(InChars, Line, Error) -> {done,{error,Error,Line},Ics}.\n%% Skip tokens until an end token, junk everything and return the error.\n\nskip_tokens(Ics, Line, Error) ->\n skip_tokens(yystate(), Ics, Line, Ics, 0, Line, Error, reject, 0).\n\n%% skip_tokens(State, InChars, Line, TokenChars, TokenLen, TokenLine, Tokens,\n%% AcceptAction, AcceptLen) ->\n%% {more,Continuation} | {done,ReturnVal,RestChars}.\n\nskip_tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Error, A0, Alen0) ->\n case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of\n {A1,Alen1,Ics1,L1} -> % Accepting end state\n skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);\n {A1,Alen1,[],L1,S1} -> % After an accepting state\n {more,{skip_tokens,S1,L1,Tcs,Alen1,Tline,Error,A1,Alen1}};\n {A1,Alen1,Ics1,L1,_S1} ->\n skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);\n {A1,Alen1,Tlen1,[],L1,S1} -> % After a non-accepting state\n {more,{skip_tokens,S1,L1,Tcs,Tlen1,Tline,Error,A1,Alen1}};\n {reject,_Alen1,_Tlen1,eof,L1,_S1} ->\n {done,{error,Error,L1},eof};\n {reject,_Alen1,Tlen1,_Ics1,L1,_S1} ->\n skip_tokens(yysuf(Tcs, Tlen1+1), L1, Error);\n {A1,Alen1,_Tlen1,_Ics1,L1,_S1} ->\n Token = yyaction(A1, Alen1, Tcs, Tline),\n skip_cont(yysuf(Tcs, Alen1), L1, Token, Error)\n end.\n\n%% skip_cont(RestChars, Line, Token, Error)\n%% Skip tokens until we have an end_token or error then return done\n%% with the original rror.\n\n-dialyzer({nowarn_function, skip_cont\/4}).\n\nskip_cont(Rest, Line, {token,_T}, Error) ->\n skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);\nskip_cont(Rest, Line, {token,_T,Push}, Error) ->\n NewRest = Push ++ Rest,\n skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);\nskip_cont(Rest, Line, {end_token,_T}, Error) ->\n {done,{error,Error,Line},Rest};\nskip_cont(Rest, Line, {end_token,_T,Push}, Error) ->\n NewRest = Push ++ Rest,\n {done,{error,Error,Line},NewRest};\nskip_cont(Rest, Line, skip_token, Error) ->\n skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);\nskip_cont(Rest, Line, {skip_token,Push}, Error) ->\n NewRest = Push ++ Rest,\n skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);\nskip_cont(Rest, Line, {error,_S}, Error) ->\n skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0).\n\nyyrev(List) -> lists:reverse(List).\nyyrev(List, Tail) -> lists:reverse(List, Tail).\nyypre(List, N) -> lists:sublist(List, N).\nyysuf(List, N) -> lists:nthtail(N, List).\n\n%% yystate() -> InitialState.\n%% yystate(State, InChars, Line, CurrTokLen, AcceptAction, AcceptLen) ->\n%% {Action, AcceptLen, RestChars, Line} |\n%% {Action, AcceptLen, RestChars, Line, State} |\n%% {reject, AcceptLen, CurrTokLen, RestChars, Line, State} |\n%% {Action, AcceptLen, CurrTokLen, RestChars, Line, State}.\n%% Generated state transition functions. The non-accepting end state\n%% return signal either an unrecognised character or end of current\n%% input.\n\n-file(\"priv\/from_whitespace_lexer.erl\", 290).\nyystate() -> 60.\n\nyystate(61, Ics, Line, Tlen, _, _) ->\n {12,Tlen,Ics,Line};\nyystate(60, [78|Ics], Line, Tlen, Action, Alen) ->\n yystate(58, Ics, Line, Tlen+1, Action, Alen);\nyystate(60, [76|Ics], Line, Tlen, Action, Alen) ->\n yystate(52, Ics, Line, Tlen+1, Action, Alen);\nyystate(60, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(46, Ics, Line, Tlen+1, Action, Alen);\nyystate(60, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(16, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(60, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(25, Ics, Line, Tlen+1, Action, Alen);\nyystate(60, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,60};\nyystate(59, Ics, Line, Tlen, _, _) ->\n {11,Tlen,Ics,Line};\nyystate(58, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(56, Ics, Line, Tlen+1, Action, Alen);\nyystate(58, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(56, Ics, Line, Tlen+1, Action, Alen);\nyystate(58, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,58};\nyystate(57, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(59, Ics, Line, Tlen+1, Action, Alen);\nyystate(57, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(61, Ics, Line, Tlen+1, Action, Alen);\nyystate(57, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,57};\nyystate(56, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(56, Ics, Line, Tlen+1, Action, Alen);\nyystate(56, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(54, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(56, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(56, Ics, Line, Tlen+1, Action, Alen);\nyystate(56, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,56};\nyystate(55, Ics, Line, Tlen, _, _) ->\n {23,Tlen,Ics,Line};\nyystate(54, Ics, Line, Tlen, _, _) ->\n {24,Tlen,Ics,Line};\nyystate(53, Ics, Line, Tlen, _, _) ->\n {22,Tlen,Ics,Line};\nyystate(52, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(50, Ics, Line, Tlen+1, Action, Alen);\nyystate(52, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(50, Ics, Line, Tlen+1, Action, Alen);\nyystate(52, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,52};\nyystate(51, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(53, Ics, Line, Tlen+1, Action, Alen);\nyystate(51, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(55, Ics, Line, Tlen+1, Action, Alen);\nyystate(51, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,51};\nyystate(50, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(50, Ics, Line, Tlen+1, Action, Alen);\nyystate(50, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(48, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(50, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(50, Ics, Line, Tlen+1, Action, Alen);\nyystate(50, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,50};\nyystate(49, Ics, Line, Tlen, _, _) ->\n {21,Tlen,Ics,Line};\nyystate(48, Ics, Line, Tlen, _, _) ->\n {25,Tlen,Ics,Line};\nyystate(47, Ics, Line, Tlen, _, _) ->\n {20,Tlen,Ics,Line};\nyystate(46, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(44, Ics, Line, Tlen+1, Action, Alen);\nyystate(46, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(38, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(46, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(30, Ics, Line, Tlen+1, Action, Alen);\nyystate(46, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,46};\nyystate(45, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(47, Ics, Line, Tlen+1, Action, Alen);\nyystate(45, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(49, Ics, Line, Tlen+1, Action, Alen);\nyystate(45, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,45};\nyystate(44, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(42, Ics, Line, Tlen+1, Action, Alen);\nyystate(44, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(42, Ics, Line, Tlen+1, Action, Alen);\nyystate(44, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,44};\nyystate(43, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(45, Ics, Line, Tlen+1, Action, Alen);\nyystate(43, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(51, Ics, Line, Tlen+1, Action, Alen);\nyystate(43, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,43};\nyystate(42, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(42, Ics, Line, Tlen+1, Action, Alen);\nyystate(42, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(40, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(42, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(42, Ics, Line, Tlen+1, Action, Alen);\nyystate(42, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,42};\nyystate(41, Ics, Line, Tlen, _, _) ->\n {10,Tlen,Ics,Line};\nyystate(40, Ics, Line, Tlen, _, _) ->\n {0,Tlen,Ics,Line};\nyystate(39, Ics, Line, Tlen, _, _) ->\n {9,Tlen,Ics,Line};\nyystate(38, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(36, Ics, Line, Tlen+1, Action, Alen);\nyystate(38, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(34, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(38, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(32, Ics, Line, Tlen+1, Action, Alen);\nyystate(38, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,38};\nyystate(37, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(39, Ics, Line, Tlen+1, Action, Alen);\nyystate(37, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(41, Ics, Line, Tlen+1, Action, Alen);\nyystate(37, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,37};\nyystate(36, Ics, Line, Tlen, _, _) ->\n {1,Tlen,Ics,Line};\nyystate(35, Ics, Line, Tlen, _, _) ->\n {7,Tlen,Ics,Line};\nyystate(34, Ics, Line, Tlen, _, _) ->\n {4,Tlen,Ics,Line};\nyystate(33, Ics, Line, Tlen, _, _) ->\n {8,Tlen,Ics,Line};\nyystate(32, Ics, Line, Tlen, _, _) ->\n {3,Tlen,Ics,Line};\nyystate(31, Ics, Line, Tlen, _, _) ->\n {6,Tlen,Ics,Line};\nyystate(30, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(28, Ics, Line, Tlen+1, Action, Alen);\nyystate(30, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(22, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(30, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,30};\nyystate(29, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(31, Ics, Line, Tlen+1, Action, Alen);\nyystate(29, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(33, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(29, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(35, Ics, Line, Tlen+1, Action, Alen);\nyystate(29, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,29};\nyystate(28, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(26, Ics, Line, Tlen+1, Action, Alen);\nyystate(28, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(26, Ics, Line, Tlen+1, Action, Alen);\nyystate(28, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,28};\nyystate(27, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(29, Ics, Line, Tlen+1, Action, Alen);\nyystate(27, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(37, Ics, Line, Tlen+1, Action, Alen);\nyystate(27, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,27};\nyystate(26, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(26, Ics, Line, Tlen+1, Action, Alen);\nyystate(26, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(24, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(26, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(26, Ics, Line, Tlen+1, Action, Alen);\nyystate(26, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,26};\nyystate(25, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(27, Ics, Line, Tlen+1, Action, Alen);\nyystate(25, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(43, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(25, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(57, Ics, Line, Tlen+1, Action, Alen);\nyystate(25, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,25};\nyystate(24, Ics, Line, Tlen, _, _) ->\n {2,Tlen,Ics,Line};\nyystate(23, Ics, Line, Tlen, _, _) ->\n {17,Tlen,Ics,Line};\nyystate(22, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(20, Ics, Line, Tlen+1, Action, Alen);\nyystate(22, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(20, Ics, Line, Tlen+1, Action, Alen);\nyystate(22, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,22};\nyystate(21, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(21, Ics, Line, Tlen+1, Action, Alen);\nyystate(21, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(23, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(21, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(21, Ics, Line, Tlen+1, Action, Alen);\nyystate(21, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,21};\nyystate(20, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(20, Ics, Line, Tlen+1, Action, Alen);\nyystate(20, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(18, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(20, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(20, Ics, Line, Tlen+1, Action, Alen);\nyystate(20, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,20};\nyystate(19, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(21, Ics, Line, Tlen+1, Action, Alen);\nyystate(19, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(21, Ics, Line, Tlen+1, Action, Alen);\nyystate(19, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,19};\nyystate(18, Ics, Line, Tlen, _, _) ->\n {5,Tlen,Ics,Line};\nyystate(17, Ics, Line, Tlen, _, _) ->\n {18,Tlen,Ics,Line};\nyystate(16, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(14, Ics, Line, Tlen+1, Action, Alen);\nyystate(16, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(5, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(16, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(9, Ics, Line, Tlen+1, Action, Alen);\nyystate(16, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,16};\nyystate(15, Ics, Line, Tlen, _, _) ->\n {16,Tlen,Ics,Line};\nyystate(14, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(12, Ics, Line, Tlen+1, Action, Alen);\nyystate(14, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(6, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(14, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(0, Ics, Line, Tlen+1, Action, Alen);\nyystate(14, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,14};\nyystate(13, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(13, Ics, Line, Tlen+1, Action, Alen);\nyystate(13, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(15, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(13, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(13, Ics, Line, Tlen+1, Action, Alen);\nyystate(13, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,13};\nyystate(12, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(10, Ics, Line, Tlen+1, Action, Alen);\nyystate(12, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(10, Ics, Line, Tlen+1, Action, Alen);\nyystate(12, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,12};\nyystate(11, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(13, Ics, Line, Tlen+1, Action, Alen);\nyystate(11, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(13, Ics, Line, Tlen+1, Action, Alen);\nyystate(11, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,11};\nyystate(10, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(10, Ics, Line, Tlen+1, Action, Alen);\nyystate(10, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(8, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(10, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(10, Ics, Line, Tlen+1, Action, Alen);\nyystate(10, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,10};\nyystate(9, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(11, Ics, Line, Tlen+1, Action, Alen);\nyystate(9, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(17, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(9, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(19, Ics, Line, Tlen+1, Action, Alen);\nyystate(9, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,9};\nyystate(8, Ics, Line, Tlen, _, _) ->\n {13,Tlen,Ics,Line};\nyystate(7, Ics, Line, Tlen, _, _) ->\n {19,Tlen,Ics,Line};\nyystate(6, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(4, Ics, Line, Tlen+1, Action, Alen);\nyystate(6, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(4, Ics, Line, Tlen+1, Action, Alen);\nyystate(6, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,6};\nyystate(5, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(7, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(5, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,5};\nyystate(4, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(4, Ics, Line, Tlen+1, Action, Alen);\nyystate(4, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(2, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(4, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(4, Ics, Line, Tlen+1, Action, Alen);\nyystate(4, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,4};\nyystate(3, Ics, Line, Tlen, _, _) ->\n {14,Tlen,Ics,Line};\nyystate(2, Ics, Line, Tlen, _, _) ->\n {15,Tlen,Ics,Line};\nyystate(1, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(1, Ics, Line, Tlen+1, Action, Alen);\nyystate(1, [10|Ics], Line, Tlen, Action, Alen) ->\n yystate(3, Ics, Line+1, Tlen+1, Action, Alen);\nyystate(1, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(1, Ics, Line, Tlen+1, Action, Alen);\nyystate(1, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,1};\nyystate(0, [32|Ics], Line, Tlen, Action, Alen) ->\n yystate(1, Ics, Line, Tlen+1, Action, Alen);\nyystate(0, [9|Ics], Line, Tlen, Action, Alen) ->\n yystate(1, Ics, Line, Tlen+1, Action, Alen);\nyystate(0, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,0};\nyystate(S, Ics, Line, Tlen, Action, Alen) ->\n {Action,Alen,Tlen,Ics,Line,S}.\n\n%% yyaction(Action, TokenLength, TokenChars, TokenLine) ->\n%% {token,Token} | {end_token, Token} | skip_token | {error,String}.\n%% Generated action function.\n\nyyaction(0, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_0(TokenChars, TokenLine);\nyyaction(1, _, _, TokenLine) ->\n yyaction_1(TokenLine);\nyyaction(2, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_2(TokenChars, TokenLine);\nyyaction(3, _, _, TokenLine) ->\n yyaction_3(TokenLine);\nyyaction(4, _, _, TokenLine) ->\n yyaction_4(TokenLine);\nyyaction(5, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_5(TokenChars, TokenLine);\nyyaction(6, _, _, TokenLine) ->\n yyaction_6(TokenLine);\nyyaction(7, _, _, TokenLine) ->\n yyaction_7(TokenLine);\nyyaction(8, _, _, TokenLine) ->\n yyaction_8(TokenLine);\nyyaction(9, _, _, TokenLine) ->\n yyaction_9(TokenLine);\nyyaction(10, _, _, TokenLine) ->\n yyaction_10(TokenLine);\nyyaction(11, _, _, TokenLine) ->\n yyaction_11(TokenLine);\nyyaction(12, _, _, TokenLine) ->\n yyaction_12(TokenLine);\nyyaction(13, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_13(TokenChars, TokenLine);\nyyaction(14, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_14(TokenChars, TokenLine);\nyyaction(15, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_15(TokenChars, TokenLine);\nyyaction(16, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_16(TokenChars, TokenLine);\nyyaction(17, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_17(TokenChars, TokenLine);\nyyaction(18, _, _, TokenLine) ->\n yyaction_18(TokenLine);\nyyaction(19, _, _, TokenLine) ->\n yyaction_19(TokenLine);\nyyaction(20, _, _, TokenLine) ->\n yyaction_20(TokenLine);\nyyaction(21, _, _, TokenLine) ->\n yyaction_21(TokenLine);\nyyaction(22, _, _, TokenLine) ->\n yyaction_22(TokenLine);\nyyaction(23, _, _, TokenLine) ->\n yyaction_23(TokenLine);\nyyaction(24, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_24(TokenChars, TokenLine);\nyyaction(25, TokenLen, YYtcs, TokenLine) ->\n TokenChars = yypre(YYtcs, TokenLen),\n yyaction_25(TokenChars, TokenLine);\nyyaction(_, _, _, _) -> error.\n\n-compile({inline,yyaction_0\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 40).\nyyaction_0(TokenChars, TokenLine) ->\n { token, { stack_push, TokenLine }, \"N\" ++ extract_number_or_label (3, TokenChars) } .\n\n-compile({inline,yyaction_1\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 41).\nyyaction_1(TokenLine) ->\n { token, { stack_duplicate, TokenLine } } .\n\n-compile({inline,yyaction_2\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 42).\nyyaction_2(TokenChars, TokenLine) ->\n { token, { stack_copy, TokenLine }, \"N\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_3\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 43).\nyyaction_3(TokenLine) ->\n { token, { stack_swap, TokenLine } } .\n\n-compile({inline,yyaction_4\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 44).\nyyaction_4(TokenLine) ->\n { token, { stack_discard, TokenLine } } .\n\n-compile({inline,yyaction_5\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 45).\nyyaction_5(TokenChars, TokenLine) ->\n { token, { stack_slide, TokenLine }, \"N\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_6\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 47).\nyyaction_6(TokenLine) ->\n { token, { arith_add, TokenLine } } .\n\n-compile({inline,yyaction_7\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 48).\nyyaction_7(TokenLine) ->\n { token, { arith_sub, TokenLine } } .\n\n-compile({inline,yyaction_8\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 49).\nyyaction_8(TokenLine) ->\n { token, { arith_mul, TokenLine } } .\n\n-compile({inline,yyaction_9\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 50).\nyyaction_9(TokenLine) ->\n { token, { arith_div, TokenLine } } .\n\n-compile({inline,yyaction_10\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 51).\nyyaction_10(TokenLine) ->\n { token, { arith_mod, TokenLine } } .\n\n-compile({inline,yyaction_11\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 53).\nyyaction_11(TokenLine) ->\n { token, { heap_store, TokenLine } } .\n\n-compile({inline,yyaction_12\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 54).\nyyaction_12(TokenLine) ->\n { token, { heap_retrieve, TokenLine } } .\n\n-compile({inline,yyaction_13\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 56).\nyyaction_13(TokenChars, TokenLine) ->\n { token, { flow_mark, TokenLine }, \"L\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_14\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 57).\nyyaction_14(TokenChars, TokenLine) ->\n { token, { flow_call, TokenLine }, \"L\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_15\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 58).\nyyaction_15(TokenChars, TokenLine) ->\n { token, { flow_jump, TokenLine }, \"L\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_16\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 59).\nyyaction_16(TokenChars, TokenLine) ->\n { token, { flow_jump_zero, TokenLine }, \"L\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_17\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 60).\nyyaction_17(TokenChars, TokenLine) ->\n { token, { flow_jump_negative, TokenLine }, \"L\" ++ extract_number_or_label (4, TokenChars) } .\n\n-compile({inline,yyaction_18\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 61).\nyyaction_18(TokenLine) ->\n { token, { flow_end_sub, TokenLine } } .\n\n-compile({inline,yyaction_19\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 62).\nyyaction_19(TokenLine) ->\n { token, { flow_end_program, TokenLine } } .\n\n-compile({inline,yyaction_20\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 64).\nyyaction_20(TokenLine) ->\n { token, { io_output_char, TokenLine } } .\n\n-compile({inline,yyaction_21\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 65).\nyyaction_21(TokenLine) ->\n { token, { io_output_num, TokenLine } } .\n\n-compile({inline,yyaction_22\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 66).\nyyaction_22(TokenLine) ->\n { token, { io_read_char, TokenLine } } .\n\n-compile({inline,yyaction_23\/1}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 67).\nyyaction_23(TokenLine) ->\n { token, { io_read_num, TokenLine } } .\n\n-compile({inline,yyaction_24\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 69).\nyyaction_24(TokenChars, TokenLine) ->\n { token, { ws_number, TokenLine, tl (TokenChars) } } .\n\n-compile({inline,yyaction_25\/2}).\n-file(\"priv\/from_whitespace_lexer.xrl\", 70).\nyyaction_25(TokenChars, TokenLine) ->\n { token, { ws_label, TokenLine, tl (TokenChars) } } .\n\n-file(\"\/usr\/local\/lib\/erlang\/lib\/parsetools-2.1.1\/include\/leexinc.hrl\", 290).\n","avg_line_length":42.1845386534,"max_line_length":99,"alphanum_fraction":0.6364093166} +{"size":3923,"ext":"erl","lang":"Erlang","max_stars_count":3.0,"content":"%%%-------------------------------------------------------------------\n%%% @author Mikael Bylund \n%%% @copyright (C) 2012, mikael\n%%% @doc\n%%%\n%%% @end\n%%% Created : 20 Jun 2017 by Taddic \n%%%-------------------------------------------------------------------\n-module(ePortAcceptor).\n\n%% API\n-export([\n start\/2\n ]).\n\n\n%%%===================================================================\n%%% API\n%%%===================================================================\nstart(ListenSocket, SSLConfig) ->\n LPid = self(),\n Fun = fun() -> doAccept(LPid, ListenSocket, SSLConfig) end,\n spawn(Fun).\n\n\n%%%===================================================================\n%%% Internal functions\n%%%===================================================================\ndoAccept(LPid, ListenSocket, false) ->\n case gen_tcp:accept(ListenSocket) of\n {ok, Socket} ->\n ListenConfig = ePortListener:getConfig(LPid),\n AllowedIps = proplists:get_value(allowedIps, ListenConfig),\n Module = proplists:get_value(protocolModules, ListenConfig),\n startPort(LPid, Module, Socket, AllowedIps, false);\n Reason ->\n eLog:log(debug, ?MODULE, doAccept, [Reason],\n \"Received error from accept\", ?LINE),\n Reason\n end,\n LPid ! nextWorker;\ndoAccept(LPid, ListenSocket, {true, SSLOptions}) ->\n case ssl:transport_accept(ListenSocket) of\n {ok, TransportSocket} ->\n case catch ssl:handshake(TransportSocket) of\n {ok, Socket} ->\n ListenConfig = ePortListener:getConfig(LPid),\n AllowedIps = proplists:get_value(allowedIps,ListenConfig),\n Module = proplists:get_value(protocolModules,ListenConfig),\n startPort(LPid, Module, Socket, AllowedIps,\n {true, SSLOptions});\n RetValue ->\n eLog:log(error, ?MODULE, doAccept, [RetValue],\n \"Handshake error\", ?LINE),\n ok\n end;\n Reason ->\n eLog:log(error, ?MODULE, doAccept, [Reason],\n \"Received error from accept\", ?LINE),\n Reason\n end,\n LPid ! nextWorker.\n\nstartPort(LPid, Module, Socket, AllowedIps, false) ->\n case allowedIp(Socket, AllowedIps) of\n {true, IP} ->\n eLog:log(debug, ?MODULE, startPort, [LPid, IP],\n \"Connect attempt\", ?LINE, Module),\n case ePort:start(LPid, Module, Socket) of\n {ok, Pid} ->\n gen_tcp:controlling_process(Socket, Pid);\n Reason ->\n Reason\n end;\n {false, IP} ->\n eLog:log(debug, ?MODULE, startPort, [LPid, IP],\n \"Illegal connect attempt\", ?LINE, Module),\n gen_tcp:close(Socket),\n {error, notAllowedIp}\n end;\nstartPort(LPid, Module, Socket, AllowedIps, {true, SSLOptions}) ->\n case allowedIp(Socket, AllowedIps) of\n {true, IP} ->\n eLog:log(debug, ?MODULE, startPort, [LPid, IP],\n \"Connect attempt\", ?LINE, Module),\n case ePort:start(LPid, Module, Socket, SSLOptions) of\n {ok, Pid} ->\n ssl:controlling_process(Socket, Pid);\n Reason ->\n Reason\n end;\n {false, IP} ->\n eLog:log(debug, ?MODULE, startPort, [LPid, IP],\n \"Illegal connect attempt\", ?LINE, Module),\n ssl:close(Socket),\n {error, notAllowedIp}\n end.\n\nallowedIp(Socket, AllowedIps) when is_list(AllowedIps)->\n IP = ePortListener:getIpAddress(Socket),\n {lists:member(IP, AllowedIps), IP};\nallowedIp(Socket, _) ->\n IP = ePortListener:getIpAddress(Socket),\n {true, IP}.\n","avg_line_length":37.3619047619,"max_line_length":79,"alphanum_fraction":0.4820290594} +{"size":34398,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2004-2012. All Rights Reserved.\n%%\n%% The contents of this file are subject to the Erlang Public License,\n%% Version 1.1, (the \"License\"); you may not use this file except in\n%% compliance with the License. You should have received a copy of the\n%% Erlang Public License along with this software. If not, it can be\n%% retrieved online at http:\/\/www.erlang.org\/.\n%%\n%% Software distributed under the License is distributed on an \"AS IS\"\n%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See\n%% the License for the specific language governing rights and limitations\n%% under the License.\n%%\n%% %CopyrightEnd%\n%%\n\n%%% @doc Common Test user interface module for the OTP snmp application\n%%%\n%%% The purpose of this module is to make snmp configuration easier for \n%%% the test case writer. Many test cases can use default values for common\n%%% operations and then no snmp configuration files need to be supplied. When\n%%% it is necessary to change particular configuration parameters, a subset\n%%% of the relevant snmp configuration files may be passed to ct_snmp<\/code>\n%%% by means of Common Test configuration files.\n%%% For more specialized configuration parameters, it is possible to place a \n%%% \"simple snmp configuration file\" in the test suite data directory. \n%%% To simplify the test suite, Common Test keeps track\n%%% of some of the snmp manager information. This way the test suite doesn't\n%%% have to handle as many input parameters as it would if it had to interface the\n%%% OTP snmp manager directly.\n%%% \n%%%

The following snmp manager and agent parameters are configurable: <\/p>\n%%%\n%%%

\n%%% {snmp,\n%%%        %%% Manager config\n%%%        [{start_manager, boolean()}    % Optional - default is true\n%%%        {users, [{user_name(), [call_back_module(), user_data()]}]}, %% Optional \n%%%        {usm_users, [{usm_user_name(), [usm_config()]}]},%% Optional - snmp v3 only\n%%%        % managed_agents is optional \n%%%        {managed_agents,[{agent_name(), [user_name(), agent_ip(), agent_port(), [agent_config()]]}]},   \n%%%        {max_msg_size, integer()},     % Optional - default is 484\n%%%        {mgr_port, integer()},         % Optional - default is 5000\n%%%        {engine _id, string()},        % Optional - default is \"mgrEngine\"\n%%%\n%%%        %%% Agent config \n%%%        {start_agent, boolean()},      % Optional - default is false\n%%%        {agent_sysname, string()},     % Optional - default is \"ct_test\"\n%%%        {agent_manager_ip, manager_ip()}, % Optional - default is localhost\n%%%        {agent_vsns, list()},          % Optional - default is [v2]\n%%%        {agent_trap_udp, integer()},   % Optional - default is 5000\n%%%        {agent_udp, integer()},        % Optional - default is 4000\n%%%        {agent_notify_type, atom()},   % Optional - default is trap\n%%%        {agent_sec_type, sec_type()},  % Optional - default is none\n%%%        {agent_passwd, string()},      % Optional - default is \"\"\n%%%        {agent_engine_id, string()},   % Optional - default is \"agentEngine\"\n%%%        {agent_max_msg_size, string()},% Optional - default is 484\n%%%\n%%%        %% The following parameters represents the snmp configuration files\n%%%        %% context.conf, standard.conf, community.conf, vacm.conf,  \n%%%        %% usm.conf, notify.conf, target_addr.conf and target_params.conf.\n%%%        %% Note all values in agent.conf can be altered by the parametes \n%%%        %% above. All these configuration files have default values set   \n%%%        %% up by the snmp application. These values can be overridden by\n%%%        %% suppling a list of valid configuration values or a file located\n%%%        %% in the test suites data dir that can produce a list \n%%%        %% of valid configuration values if you apply file:consult\/1 to the \n%%%        %% file. \n%%%        {agent_contexts, [term()] | {data_dir_file, rel_path()}}, % Optional\n%%%        {agent_community, [term()] | {data_dir_file, rel_path()}},% Optional\n%%%        {agent_sysinfo,  [term()] | {data_dir_file, rel_path()}}, % Optional\n%%%        {agent_vacm, [term()] | {data_dir_file, rel_path()}},     % Optional\n%%%        {agent_usm, [term()] | {data_dir_file, rel_path()}},      % Optional \n%%%        {agent_notify_def, [term()] | {data_dir_file, rel_path()}},% Optional\n%%%        {agent_target_address_def, [term()] | {data_dir_file, rel_path()}},% Optional\n%%%        {agent_target_param_def, [term()] | {data_dir_file, rel_path()}},% Optional\n%%%       ]}.\n%%% <\/pre>\n%%%\n%%% 

The MgrAgentConfName<\/code> parameter in the functions \n%%% should be a name you allocate in your test suite using a\n%%% require<\/code> statement. \n%%% Example (where MgrAgentConfName = snmp_mgr_agent<\/code>):<\/p>\n%%%

 suite() -> [{require, snmp_mgr_agent, snmp}].<\/pre>\n%%% 

or<\/p>\n%%%

  ct:require(snmp_mgr_agent, snmp).<\/pre>\n%%%\n%%% 

Note that Usm users are needed for snmp v3 configuration and are\n%%% not to be confused with users.<\/p>\n%%%\n%%%

Snmp traps, inform and report messages are handled by the\n%%% user callback module. For more information about this see\n%%% the snmp application. <\/p> \n%%%

Note: It is recommended to use the .hrl-files created by the \n%%% Erlang\/OTP mib-compiler to define the oids. \n%%% Example for the getting the erlang node name from the erlNodeTable \n%%% in the OTP-MIB:<\/p> \n%%%

Oid = ?erlNodeEntry ++ [?erlNodeName, 1] <\/pre>\n%%%\n%%% 

It is also possible to set values for snmp application configuration \n%%% parameters, such as config<\/code>, server<\/code>, \n%%% net_if<\/code>, etc (see the \"Configuring the application\" chapter in\n%%% the OTP snmp User's Guide for a list of valid parameters and types). This is \n%%% done by defining a configuration data variable on the following form:<\/p>\n%%%

\n%%% {snmp_app, [{manager, [snmp_app_manager_params()]},\n%%%             {agent, [snmp_app_agent_params()]}]}.<\/pre>\n%%% \n%%% 

A name for the data needs to be allocated in the suite using \n%%% require<\/code> (see example above), and this name passed as \n%%% the SnmpAppConfName<\/code> argument to start\/3<\/code>.\n%%% ct_snmp<\/code> specifies default values for some snmp application\n%%% configuration parameters (such as {verbosity,trace}<\/code> for the\n%%% config<\/code> parameter). This set of defaults will be\n%%% merged with the parameters specified by the user, and user values\n%%% override ct_snmp<\/code> defaults.<\/p>\n\n-module(ct_snmp).\n\n%%% Common Types\n%%% @type agent_ip() = ip()\n%%% @type manager_ip() = ip()\n%%% @type agent_name() = atom()\n%%% @type ip() = string() | {integer(), integer(), \n%%% integer(), integer()}\n%%% @type agent_port() = integer()\n%%% @type agent_config() = {Item, Value} \n%%% @type user_name() = atom() \n%%% @type usm_user_name() = string() \n%%% @type usm_config() = {Item, Value}\n%%% @type call_back_module() = atom()\n%%% @type user_data() = term() \n%%% @type oids() = [oid()]\n%%% @type oid() = [byte()]\n%%% @type snmpreply() = {error_status(), error_index(), varbinds()} \n%%% @type error_status() = noError | atom() \n%%% @type error_index() = integer() \n%%% @type varbinds() = [varbind()] \n%%% @type varbind() = term() \n%%% @type value_type() = o ('OBJECT IDENTIFIER') | i ('INTEGER') | \n%%% u ('Unsigned32') | g ('Unsigned32') | s ('OCTET STRING') \n%%% @type varsandvals() = [var_and_val()]\n%%% @type var_and_val() = {oid(), value_type(), value()}\n%%% @type sec_type() = none | minimum | semi\n%%% @type rel_path() = string() \n%%% @type snmp_app_manager_params() = term()\n%%% @type snmp_app_agent_params() = term()\n\n\n-include(\"snmp_types.hrl\").\n-include(\"inet.hrl\").\n-include(\"ct.hrl\").\n\n%%% API\n-export([start\/2, start\/3, stop\/1, get_values\/3, get_next_values\/3, set_values\/4, \n\t set_info\/1, register_users\/2, register_agents\/2, register_usm_users\/2,\n\t unregister_users\/1, unregister_users\/2, unregister_agents\/1,\n\t unregister_agents\/2, unregister_usm_users\/1, unregister_usm_users\/2,\n\t load_mibs\/1, unload_mibs\/1]).\n\n%% Manager values\n-define(CT_SNMP_LOG_FILE, \"ct_snmp_set.log\").\n-define(MGR_PORT, 5000).\n-define(MAX_MSG_SIZE, 484).\n-define(ENGINE_ID, \"mgrEngine\").\n\n%% Agent values\n-define(AGENT_ENGINE_ID, \"agentEngine\").\n-define(TRAP_UDP, 5000). \n-define(AGENT_UDP, 4000).\n-define(CONF_FILE_VER, [v2]).\n-define(AGENT_MAX_MSG_SIZE, 484).\n-define(AGENT_NOTIFY_TYPE, trap).\n-define(AGENT_SEC_TYPE, none).\n-define(AGENT_PASSWD, \"\").\n%%%=========================================================================\n%%% API\n%%%=========================================================================\n\n%%%-----------------------------------------------------------------\n%%% @spec start(Config, MgrAgentConfName) -> ok\n%%% @equiv start(Config, MgrAgentConfName, undefined)\nstart(Config, MgrAgentConfName) ->\n start(Config, MgrAgentConfName, undefined).\n\n%%% @spec start(Config, MgrAgentConfName, SnmpAppConfName) -> ok\n%%% Config = [{Key, Value}] \n%%% Key = atom()\n%%% Value = term()\n%%% MgrAgentConfName = atom()\n%%% SnmpConfName = atom()\n%%%\n%%% @doc Starts an snmp manager and\/or agent. In the manager case,\n%%% registrations of users and agents as specified by the configuration \n%%% MgrAgentConfName<\/code> will be performed. When using snmp\n%%% v3 also so called usm users will be registered. Note that users,\n%%% usm_users and managed agents may also be registered at a later time\n%%% using ct_snmp:register_users\/2, ct_snmp:register_agents\/2, and\n%%% ct_snmp:register_usm_users\/2. The agent started will be\n%%% called snmp_master_agent<\/code>. Use ct_snmp:load_mibs\/1 to load \n%%% mibs into the agent. With SnmpAppConfName<\/code> it's possible \n%%% to configure the snmp application with parameters such as config<\/code>,\n%%% mibs<\/code>, net_if<\/code>, etc. The values will be merged\n%%% with (and possibly override) default values set by ct_snmp<\/code>.\nstart(Config, MgrAgentConfName, SnmpAppConfName) ->\n StartManager= ct:get_config({MgrAgentConfName, start_manager}, true),\n StartAgent = ct:get_config({MgrAgentConfName, start_agent}, false),\n \n SysName = ct:get_config({MgrAgentConfName, agent_sysname}, \"ct_test\"),\n {ok, HostName} = inet:gethostname(),\n {ok, Addr} = inet:getaddr(HostName, inet),\n IP = tuple_to_list(Addr),\n AgentManagerIP = ct:get_config({MgrAgentConfName, agent_manager_ip}, IP),\n \n prepare_snmp_env(),\n setup_agent(StartAgent, MgrAgentConfName, SnmpAppConfName, \n\t\tConfig, SysName, AgentManagerIP, IP),\n setup_manager(StartManager, MgrAgentConfName, SnmpAppConfName, \n\t\t Config, AgentManagerIP),\n application:start(snmp),\n\n manager_register(StartManager, MgrAgentConfName).\n \n%%% @spec stop(Config) -> ok\n%%% Config = [{Key, Value}]\n%%% Key = atom()\n%%% Value = term()\n%%%\n%%% @doc Stops the snmp manager and\/or agent removes all files created.\nstop(Config) ->\n PrivDir = ?config(priv_dir, Config),\n application:stop(snmp),\n application:stop(mnesia),\n MgrDir = filename:join(PrivDir,\"mgr\"),\n ConfDir = filename:join(PrivDir, \"conf\"),\n DbDir = filename:join(PrivDir,\"db\"),\n catch del_dir(MgrDir),\n catch del_dir(ConfDir),\n catch del_dir(DbDir).\n \n \n%%% @spec get_values(Agent, Oids, MgrAgentConfName) -> SnmpReply\n%%%\n%%%\t Agent = agent_name()\n%%% Oids = oids()\n%%% MgrAgentConfName = atom()\n%%% SnmpReply = snmpreply() \n%%%\n%%% @doc Issues a synchronous snmp get request. \nget_values(Agent, Oids, MgrAgentConfName) ->\n [Uid | _] = agent_conf(Agent, MgrAgentConfName),\n {ok, SnmpReply, _} = snmpm:sync_get2(Uid, target_name(Agent), Oids),\n SnmpReply.\n\n%%% @spec get_next_values(Agent, Oids, MgrAgentConfName) -> SnmpReply \n%%%\n%%%\t Agent = agent_name()\n%%% Oids = oids()\n%%% MgrAgentConfName = atom()\n%%% SnmpReply = snmpreply() \n%%%\n%%% @doc Issues a synchronous snmp get next request. \nget_next_values(Agent, Oids, MgrAgentConfName) ->\n [Uid | _] = agent_conf(Agent, MgrAgentConfName),\n {ok, SnmpReply, _} = snmpm:sync_get_next2(Uid, target_name(Agent), Oids),\n SnmpReply.\n\n%%% @spec set_values(Agent, VarsAndVals, MgrAgentConfName, Config) -> SnmpReply\n%%%\n%%%\t Agent = agent_name()\n%%% Oids = oids()\n%%% MgrAgentConfName = atom()\n%%% Config = [{Key, Value}] \n%%% SnmpReply = snmpreply() \n%%%\n%%% @doc Issues a synchronous snmp set request. \nset_values(Agent, VarsAndVals, MgrAgentConfName, Config) ->\n PrivDir = ?config(priv_dir, Config),\n [Uid | _] = agent_conf(Agent, MgrAgentConfName),\n Oids = lists:map(fun({Oid, _, _}) -> Oid end, VarsAndVals),\n TargetName = target_name(Agent),\n {ok, SnmpGetReply, _} = snmpm:sync_get2(Uid, TargetName, Oids),\n {ok, SnmpSetReply, _} = snmpm:sync_set2(Uid, TargetName, VarsAndVals),\n case SnmpSetReply of\n\t{noError, 0, _} when PrivDir \/= false ->\n\t log(PrivDir, Agent, SnmpGetReply, VarsAndVals);\n\t_ ->\n\t set_failed_or_user_did_not_want_to_log\n end,\n SnmpSetReply.\n\n%%% @spec set_info(Config) -> [{Agent, OldVarsAndVals, NewVarsAndVals}] \n%%%\n%%% Config = [{Key, Value}] \n%%%\t Agent = agent_name()\n%%% OldVarsAndVals = varsandvals()\n%%% NewVarsAndVals = varsandvals()\n%%%\n%%% @doc Returns a list of all successful set requests performed in\n%%% the test case in reverse order. The list contains the involved\n%%% user and agent, the value prior to the set and the new value. This\n%%% is intended to facilitate the clean up in the end_per_testcase\n%%% function i.e. the undoing of the set requests and its possible\n%%% side-effects.\nset_info(Config) ->\n PrivDir = ?config(priv_dir, Config),\n SetLogFile = filename:join(PrivDir, ?CT_SNMP_LOG_FILE),\n case file:consult(SetLogFile) of\n\t{ok, SetInfo} ->\n\t file:delete(SetLogFile),\n\t lists:reverse(SetInfo);\n\t_ ->\n\t []\n end.\n\n%%% @spec register_users(MgrAgentConfName, Users) -> ok | {error, Reason}\n%%%\n%%% MgrAgentConfName = atom()\n%%% Users = [user()]\n%%% Reason = term() \n%%%\n%%% @doc Register the manager entity (=user) responsible for specific agent(s).\n%%% Corresponds to making an entry in users.conf.\n%%%\n%%% This function will try to register the given users, without\n%%% checking if any of them already exist. In order to change an\n%%% already registered user, the user must first be unregistered.\nregister_users(MgrAgentConfName, Users) ->\n case setup_users(Users) of\n\tok ->\n\t SnmpVals = ct:get_config(MgrAgentConfName),\n\t OldUsers = ct:get_config({MgrAgentConfName,users},[]),\n\t NewSnmpVals = lists:keystore(users, 1, SnmpVals,\n\t\t\t\t\t {users, Users ++ OldUsers}),\n\t ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n\t ok;\n\tError ->\n\t Error\n end.\n\n%%% @spec register_agents(MgrAgentConfName, ManagedAgents) -> ok | {error, Reason}\n%%%\n%%% MgrAgentConfName = atom()\n%%% ManagedAgents = [agent()]\n%%% Reason = term() \n%%%\n%%% @doc Explicitly instruct the manager to handle this agent.\n%%% Corresponds to making an entry in agents.conf \n%%%\n%%% This function will try to register the given managed agents,\n%%% without checking if any of them already exist. In order to change\n%%% an already registered managed agent, the agent must first be\n%%% unregistered.\nregister_agents(MgrAgentConfName, ManagedAgents) ->\n case setup_managed_agents(MgrAgentConfName,ManagedAgents) of\n\tok ->\n\t SnmpVals = ct:get_config(MgrAgentConfName),\n\t OldAgents = ct:get_config({MgrAgentConfName,managed_agents},[]),\n\t NewSnmpVals = lists:keystore(managed_agents, 1, SnmpVals,\n\t\t\t\t\t {managed_agents,\n\t\t\t\t\t ManagedAgents ++ OldAgents}),\n\t ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n\t ok;\n\tError ->\n\t Error\n end.\n\n%%% @spec register_usm_users(MgrAgentConfName, UsmUsers) -> ok | {error, Reason}\n%%%\n%%% MgrAgentConfName = atom()\n%%% UsmUsers = [usm_user()]\n%%% Reason = term() \n%%%\n%%% @doc Explicitly instruct the manager to handle this USM user.\n%%% Corresponds to making an entry in usm.conf \n%%%\n%%% This function will try to register the given users, without\n%%% checking if any of them already exist. In order to change an\n%%% already registered user, the user must first be unregistered.\nregister_usm_users(MgrAgentConfName, UsmUsers) ->\n EngineID = ct:get_config({MgrAgentConfName, engine_id}, ?ENGINE_ID),\n case setup_usm_users(UsmUsers, EngineID) of\n\tok ->\n\t SnmpVals = ct:get_config(MgrAgentConfName),\n\t OldUsmUsers = ct:get_config({MgrAgentConfName,usm_users},[]),\n\t NewSnmpVals = lists:keystore(usm_users, 1, SnmpVals,\n\t\t\t\t\t {usm_users, UsmUsers ++ OldUsmUsers}),\n\t ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n\t ok;\n\tError ->\n\t Error\n end.\n\n%%% @spec unregister_users(MgrAgentConfName) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% Reason = term()\n%%%\n%%% @doc Unregister all users.\nunregister_users(MgrAgentConfName) ->\n Users = [Id || {Id,_} <- ct:get_config({MgrAgentConfName, users},[])],\n unregister_users(MgrAgentConfName,Users).\n\n%%% @spec unregister_users(MgrAgentConfName,Users) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% Users = [user_name()]\n%%% Reason = term()\n%%%\n%%% @doc Unregister the given users.\nunregister_users(MgrAgentConfName,Users) ->\n takedown_users(Users),\n SnmpVals = ct:get_config(MgrAgentConfName),\n AllUsers = ct:get_config({MgrAgentConfName, users},[]),\n RemainingUsers = lists:filter(fun({Id,_}) ->\n\t\t\t\t\t not lists:member(Id,Users)\n\t\t\t\t end,\n\t\t\t\t AllUsers),\n NewSnmpVals = lists:keyreplace(users, 1, SnmpVals, {users,RemainingUsers}),\n ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n ok.\n\n%%% @spec unregister_agents(MgrAgentConfName) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% Reason = term()\n%%%\n%%% @doc Unregister all managed agents.\nunregister_agents(MgrAgentConfName) -> \n ManagedAgents = [AgentName ||\n\t\t\t {AgentName, _} <-\n\t\t\t ct:get_config({MgrAgentConfName,managed_agents},[])],\n unregister_agents(MgrAgentConfName,ManagedAgents).\n\n%%% @spec unregister_agents(MgrAgentConfName,ManagedAgents) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% ManagedAgents = [agent_name()]\n%%% Reason = term()\n%%%\n%%% @doc Unregister the given managed agents.\nunregister_agents(MgrAgentConfName,ManagedAgents) ->\n takedown_managed_agents(MgrAgentConfName, ManagedAgents),\n SnmpVals = ct:get_config(MgrAgentConfName),\n AllAgents = ct:get_config({MgrAgentConfName,managed_agents},[]),\n RemainingAgents = lists:filter(fun({Name,_}) ->\n\t\t\t\t\t not lists:member(Name,ManagedAgents)\n\t\t\t\t end,\n\t\t\t\t AllAgents),\n NewSnmpVals = lists:keyreplace(managed_agents, 1, SnmpVals,\n\t\t\t\t {managed_agents,RemainingAgents}),\n ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n ok.\n\n%%% @spec unregister_usm_users(MgrAgentConfName) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% Reason = term()\n%%%\n%%% @doc Unregister all usm users.\nunregister_usm_users(MgrAgentConfName) ->\n UsmUsers = [Id || {Id,_} <- ct:get_config({MgrAgentConfName, usm_users},[])],\n unregister_usm_users(MgrAgentConfName,UsmUsers).\n\n%%% @spec unregister_usm_users(MgrAgentConfName,UsmUsers) -> ok\n%%%\n%%% MgrAgentConfName = atom()\n%%% UsmUsers = [usm_user_name()]\n%%% Reason = term()\n%%%\n%%% @doc Unregister the given usm users.\nunregister_usm_users(MgrAgentConfName,UsmUsers) ->\n EngineID = ct:get_config({MgrAgentConfName, engine_id}, ?ENGINE_ID),\n takedown_usm_users(UsmUsers,EngineID),\n SnmpVals = ct:get_config(MgrAgentConfName),\n AllUsmUsers = ct:get_config({MgrAgentConfName, usm_users},[]),\n RemainingUsmUsers = lists:filter(fun({Id,_}) ->\n\t\t\t\t\t not lists:member(Id,UsmUsers)\n\t\t\t\t end,\n\t\t\t\t AllUsmUsers),\n NewSnmpVals = lists:keyreplace(usm_users, 1, SnmpVals,\n\t\t\t\t {usm_users,RemainingUsmUsers}),\n ct_config:update_config(MgrAgentConfName, NewSnmpVals),\n ok.\n\n%%% @spec load_mibs(Mibs) -> ok | {error, Reason}\n%%%\n%%% Mibs = [MibName]\n%%% MibName = string()\n%%% Reason = term()\n%%%\n%%% @doc Load the mibs into the agent 'snmp_master_agent'.\nload_mibs(Mibs) -> \n snmpa:load_mibs(snmp_master_agent, Mibs).\n \n%%% @spec unload_mibs(Mibs) -> ok | {error, Reason}\n%%%\n%%% Mibs = [MibName]\n%%% MibName = string()\n%%% Reason = term()\n%%%\n%%% @doc Unload the mibs from the agent 'snmp_master_agent'.\nunload_mibs(Mibs) ->\n snmpa:unload_mibs(snmp_master_agent, Mibs).\n\n%%%========================================================================\n%%% Internal functions\n%%%========================================================================\nprepare_snmp_env() ->\n %% To make sure application:set_env is not overwritten by any\n %% app-file settings.\n application:load(snmp),\n \n %% Fix for older versions of snmp where there are some\n %% inappropriate default values for alway starting an \n %% agent.\n application:unset_env(snmp, agent).\n%%%---------------------------------------------------------------------------\nsetup_manager(false, _, _, _, _) ->\n ok;\nsetup_manager(true, MgrConfName, SnmpConfName, Config, IP) -> \n PrivDir = ?config(priv_dir, Config),\n MaxMsgSize = ct:get_config({MgrConfName,max_msg_size}, ?MAX_MSG_SIZE),\n Port = ct:get_config({MgrConfName,mgr_port}, ?MGR_PORT),\n EngineID = ct:get_config({MgrConfName,engine_id}, ?ENGINE_ID),\n MgrDir = filename:join(PrivDir,\"mgr\"),\n %%% Users, Agents and Usms are in test suites register after the\n %%% snmp application is started.\n Users = [],\n Agents = [],\n Usms = [],\n file:make_dir(MgrDir),\n \n snmp_config:write_manager_snmp_files(MgrDir, IP, Port, MaxMsgSize, \n\t\t\t\t\t EngineID, Users, Agents, Usms),\n SnmpEnv = merge_snmp_conf([{config, [{dir, MgrDir},{db_dir, MgrDir},\n\t\t\t\t\t {verbosity, trace}]},\n\t\t\t {server, [{verbosity, trace}]},\n\t\t\t {net_if, [{verbosity, trace}]},\n\t\t\t {versions, [v1, v2, v3]}],\n\t\t\t ct:get_config({SnmpConfName,manager})),\n application:set_env(snmp, manager, SnmpEnv).\n%%%---------------------------------------------------------------------------\nsetup_agent(false,_, _, _, _, _, _) ->\n ok;\nsetup_agent(true, AgentConfName, SnmpConfName, \n\t Config, SysName, ManagerIP, AgentIP) ->\n application:start(mnesia),\n PrivDir = ?config(priv_dir, Config),\n Vsns = ct:get_config({AgentConfName, agent_vsns}, ?CONF_FILE_VER),\n TrapUdp = ct:get_config({AgentConfName, agent_trap_udp}, ?TRAP_UDP),\n AgentUdp = ct:get_config({AgentConfName, agent_udp}, ?AGENT_UDP),\n NotifType = ct:get_config({AgentConfName, agent_notify_type},\n\t\t\t ?AGENT_NOTIFY_TYPE),\n SecType = ct:get_config({AgentConfName, agent_sec_type}, ?AGENT_SEC_TYPE),\n Passwd = ct:get_config({AgentConfName, agent_passwd}, ?AGENT_PASSWD),\n AgentEngineID = ct:get_config({AgentConfName, agent_engine_id}, \n\t\t\t\t ?AGENT_ENGINE_ID),\n AgentMaxMsgSize = ct:get_config({AgentConfName, agent_max_msg_size},\n\t\t\t\t ?MAX_MSG_SIZE),\n \n ConfDir = filename:join(PrivDir, \"conf\"),\n DbDir = filename:join(PrivDir,\"db\"),\n file:make_dir(ConfDir),\n file:make_dir(DbDir), \n snmp_config:write_agent_snmp_files(ConfDir, Vsns, ManagerIP, TrapUdp, \n\t\t\t\t AgentIP, AgentUdp, SysName, \n\t\t\t\t NotifType, SecType, Passwd,\n\t\t\t\t AgentEngineID, AgentMaxMsgSize),\n\n override_default_configuration(Config, AgentConfName),\n \n SnmpEnv = merge_snmp_conf([{db_dir, DbDir},\n\t\t\t {config, [{dir, ConfDir},\n\t\t\t\t\t {verbosity, trace}]},\n\t\t\t {agent_type, master},\n\t\t\t {agent_verbosity, trace},\n\t\t\t {net_if, [{verbosity, trace}]},\n\t\t\t {versions, Vsns}],\n\t\t\t ct:get_config({SnmpConfName,agent})),\n application:set_env(snmp, agent, SnmpEnv).\n%%%---------------------------------------------------------------------------\nmerge_snmp_conf(Defaults, undefined) ->\n Defaults;\nmerge_snmp_conf([Def={Key,DefList=[P|_]}|DefParams], UserParams) when is_tuple(P) ->\n case lists:keysearch(Key, 1, UserParams) of\n\tfalse ->\n\t [Def | merge_snmp_conf(DefParams, UserParams)];\n\t{value,{Key,UserList}} ->\n\t DefList1 = [{SubKey,Val} || {SubKey,Val} <- DefList, \n\t\t\t\t\tlists:keysearch(SubKey, 1, UserList) == false],\n\t [{Key,DefList1++UserList} | merge_snmp_conf(DefParams, \n\t\t\t\t\t\t\tlists:keydelete(Key, 1, UserParams))]\n end;\nmerge_snmp_conf([Def={Key,_}|DefParams], UserParams) ->\n case lists:keysearch(Key, 1, UserParams) of\n\tfalse ->\n\t [Def | merge_snmp_conf(DefParams, UserParams)];\n\t{value,_} ->\n\t merge_snmp_conf(DefParams, UserParams)\n end;\nmerge_snmp_conf([], UserParams) ->\n UserParams.\n\t\t\t \n\n%%%---------------------------------------------------------------------------\nmanager_register(false, _) ->\n ok;\nmanager_register(true, MgrAgentConfName) ->\n Agents = ct:get_config({MgrAgentConfName, managed_agents}, []),\n Users = ct:get_config({MgrAgentConfName, users}, []),\n UsmUsers = ct:get_config({MgrAgentConfName, usm_users}, []),\n EngineID = ct:get_config({MgrAgentConfName, engine_id}, ?ENGINE_ID),\n\n setup_usm_users(UsmUsers, EngineID),\n setup_users(Users),\n setup_managed_agents(MgrAgentConfName,Agents).\n\n%%%---------------------------------------------------------------------------\nsetup_users(Users) ->\n while_ok(fun({Id, [Module, Data]}) ->\n\t\t snmpm:register_user(Id, Module, Data)\n\t end, Users).\n%%%--------------------------------------------------------------------------- \nsetup_managed_agents(AgentConfName,Agents) ->\n Fun =\n\tfun({AgentName, [Uid, AgentIp, AgentUdpPort, AgentConf0]}) ->\n\t\tNewAgentIp = case AgentIp of\n\t\t\t\t IpTuple when is_tuple(IpTuple) ->\n\t\t\t\t IpTuple;\n\t\t\t\t HostName when is_list(HostName) ->\n\t\t\t\t {ok,Hostent} = inet:gethostbyname(HostName),\n\t\t\t\t [IpTuple|_] = Hostent#hostent.h_addr_list,\n\t\t\t\t IpTuple\n\t\t\t end,\n\t\tAgentConf =\n\t\t case lists:keymember(engine_id,1,AgentConf0) of\n\t\t\ttrue ->\n\t\t\t AgentConf0;\n\t\t\tfalse ->\n\t\t\t DefaultEngineID =\n\t\t\t\tct:get_config({AgentConfName,agent_engine_id},\n\t\t\t\t\t ?AGENT_ENGINE_ID),\n\t\t\t [{engine_id,DefaultEngineID}|AgentConf0]\n\t\t end,\n\t\tsnmpm:register_agent(Uid, target_name(AgentName),\n\t\t\t\t [{address,NewAgentIp},{port,AgentUdpPort} |\n\t\t\t\t AgentConf])\n\tend,\n while_ok(Fun,Agents).\n%%%---------------------------------------------------------------------------\nsetup_usm_users(UsmUsers, EngineID)->\n while_ok(fun({UsmUser, Conf}) ->\n\t\t snmpm:register_usm_user(EngineID, UsmUser, Conf)\n\t end, UsmUsers).\n%%%---------------------------------------------------------------------------\ntakedown_users(Users) ->\n lists:foreach(fun(Id) ->\n\t\t\t snmpm:unregister_user(Id)\n\t\t end, Users).\n%%%---------------------------------------------------------------------------\ntakedown_managed_agents(MgrAgentConfName,ManagedAgents) ->\n lists:foreach(fun(AgentName) ->\n\t\t\t [Uid | _] = agent_conf(AgentName, MgrAgentConfName),\n\t\t\t snmpm:unregister_agent(Uid, target_name(AgentName))\n\t\t end, ManagedAgents).\n%%%---------------------------------------------------------------------------\ntakedown_usm_users(UsmUsers, EngineID) ->\n lists:foreach(fun(Id) ->\n\t\t\t snmpm:unregister_usm_user(EngineID, Id)\n\t\t end, UsmUsers).\n%%%--------------------------------------------------------------------------- \nlog(PrivDir, Agent, {_, _, Varbinds}, NewVarsAndVals) ->\n\n Fun = fun(#varbind{oid = Oid, variabletype = Type, value = Value}) ->\n\t\t {Oid, Type, Value} \n\t end,\n OldVarsAndVals = lists:map(Fun, Varbinds),\n \n File = filename:join(PrivDir, ?CT_SNMP_LOG_FILE),\n {ok, Fd} = file:open(File, [write, append]),\n io:format(Fd, \"~p.~n\", [{Agent, OldVarsAndVals, NewVarsAndVals}]),\n file:close(Fd),\n ok.\n%%%---------------------------------------------------------------------------\ndel_dir(Dir) ->\n {ok, Files} = file:list_dir(Dir),\n FullPathFiles = lists:map(fun(File) -> filename:join(Dir, File) end,\n\t\t\t Files),\n lists:foreach(fun file:delete\/1, FullPathFiles), \n file:del_dir(Dir),\n ok.\n%%%---------------------------------------------------------------------------\nagent_conf(Agent, MgrAgentConfName) ->\n Agents = ct:get_config({MgrAgentConfName, managed_agents}),\n case lists:keysearch(Agent, 1, Agents) of\n\t{value, {Agent, AgentConf}} ->\n\t AgentConf;\n\t_ ->\n\t exit({error, {unknown_agent, Agent, Agents}})\n end.\n%%%---------------------------------------------------------------------------\noverride_default_configuration(Config, MgrAgentConfName) ->\n override_contexts(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_contexts}, undefined)),\n override_community(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_community}, undefined)),\n override_sysinfo(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_sysinfo}, undefined)),\n override_vacm(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_vacm}, undefined)),\n override_usm(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_usm}, undefined)),\n override_notify(Config,\n\t\t ct:get_config({MgrAgentConfName, agent_notify_def}, undefined)),\n override_target_address(Config,\n\t\t\t ct:get_config({MgrAgentConfName, \n\t\t\t\t\t agent_target_address_def}, \n\t\t\t\t\t undefined)),\n override_target_params(Config, \n\t\t\t ct:get_config({MgrAgentConfName, agent_target_param_def},\n\t\t\t\t\t undefined)).\n\n%%%---------------------------------------------------------------------------\noverride_contexts(_, undefined) ->\n ok;\n\noverride_contexts(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, ContextInfo} = file:consult(FullPathFile),\n override_contexts(Config, ContextInfo);\n\noverride_contexts(Config, Contexts) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"context.conf\"),\n file:delete(File),\n snmp_config:write_agent_context_config(Dir, \"\", Contexts).\n\t\t\n%%%---------------------------------------------------------------------------\noverride_sysinfo(_, undefined) ->\n ok;\n\noverride_sysinfo(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, SysInfo} = file:consult(FullPathFile),\n override_sysinfo(Config, SysInfo);\n\noverride_sysinfo(Config, SysInfo) -> \n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"standard.conf\"),\n file:delete(File),\n snmp_config:write_agent_standard_config(Dir, \"\", SysInfo).\n\n%%%---------------------------------------------------------------------------\noverride_target_address(_, undefined) ->\n ok;\noverride_target_address(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, TargetAddressConf} = file:consult(FullPathFile),\n override_target_address(Config, TargetAddressConf);\n\noverride_target_address(Config, TargetAddressConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"target_addr.conf\"),\n file:delete(File),\n snmp_config:write_agent_target_addr_config(Dir, \"\", TargetAddressConf).\n\n\n%%%---------------------------------------------------------------------------\noverride_target_params(_, undefined) ->\n ok;\noverride_target_params(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, TargetParamsConf} = file:consult(FullPathFile),\n override_target_params(Config, TargetParamsConf);\n\noverride_target_params(Config, TargetParamsConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"target_params.conf\"),\n file:delete(File),\n snmp_config:write_agent_target_params_config(Dir, \"\", TargetParamsConf). \n\n%%%---------------------------------------------------------------------------\noverride_notify(_, undefined) ->\n ok;\noverride_notify(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, NotifyConf} = file:consult(FullPathFile),\n override_notify(Config, NotifyConf);\n\noverride_notify(Config, NotifyConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"notify.conf\"),\n file:delete(File),\n snmp_config:write_agent_notify_config(Dir, \"\", NotifyConf).\n\n%%%---------------------------------------------------------------------------\noverride_usm(_, undefined) ->\n ok;\noverride_usm(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, UsmConf} = file:consult(FullPathFile),\n override_usm(Config, UsmConf);\n\noverride_usm(Config, UsmConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"usm.conf\"),\n file:delete(File),\n snmp_config:write_agent_usm_config(Dir, \"\", UsmConf).\n\n%%%--------------------------------------------------------------------------\noverride_community(_, undefined) ->\n ok;\noverride_community(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, CommunityConf} = file:consult(FullPathFile),\n override_community(Config, CommunityConf);\n\noverride_community(Config, CommunityConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"community.conf\"),\n file:delete(File),\n snmp_config:write_agent_community_config(Dir, \"\", CommunityConf).\n \n%%%---------------------------------------------------------------------------\n\noverride_vacm(_, undefined) ->\n ok;\noverride_vacm(Config, {data_dir_file, File}) ->\n Dir = ?config(data_dir, Config),\n FullPathFile = filename:join(Dir, File),\n {ok, VacmConf} = file:consult(FullPathFile),\n override_vacm(Config, VacmConf);\n\noverride_vacm(Config, VacmConf) ->\n Dir = filename:join(?config(priv_dir, Config),\"conf\"),\n File = filename:join(Dir,\"vacm.conf\"),\n file:delete(File),\n snmp_config:write_agent_vacm_config(Dir, \"\", VacmConf).\n\n%%%---------------------------------------------------------------------------\n\ntarget_name(Agent) ->\n atom_to_list(Agent).\n\nwhile_ok(Fun,[H|T]) ->\n case Fun(H) of\n\tok -> while_ok(Fun,T);\n\tError -> Error\n end;\nwhile_ok(_Fun,[]) ->\n ok.\n","avg_line_length":39.8586326767,"max_line_length":107,"alphanum_fraction":0.6281179138} +{"size":753,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%%------------------------------------------------------------\n%%\n%% Implementation stub file\n%% \n%% Target: CosNotifyFilter_ConstraintIDSeq\n%% Source: \/net\/isildur\/ldisk\/daily_build\/r14b02_prebuild_opu_o.2011-03-14_20\/otp_src_R14B02\/lib\/cosNotification\/src\/CosNotifyFilter.idl\n%% IC vsn: 4.2.26\n%% \n%% This file is automatically generated. DO NOT EDIT IT.\n%%\n%%------------------------------------------------------------\n\n-module('CosNotifyFilter_ConstraintIDSeq').\n-ic_compiled(\"4_2_26\").\n\n\n-include(\"CosNotifyFilter.hrl\").\n\n-export([tc\/0,id\/0,name\/0]).\n\n\n\n%% returns type code\ntc() -> {tk_sequence,tk_long,0}.\n\n%% returns id\nid() -> \"IDL:omg.org\/CosNotifyFilter\/ConstraintIDSeq:1.0\".\n\n%% returns name\nname() -> \"CosNotifyFilter_ConstraintIDSeq\".\n\n\n\n","avg_line_length":22.1470588235,"max_line_length":136,"alphanum_fraction":0.6082337317} +{"size":409,"ext":"erl","lang":"Erlang","max_stars_count":5.0,"content":"-module(pre_chat_channel_tests).\n\n-include(\"pre_client.hrl\").\n-include_lib(\"eunit\/include\/eunit.hrl\").\n\n%% channel_test_() ->\n%% \t% Setup\n%% \t{setup, fun() ->\n%% \t\tmeck:new(pre_client)\n%% \tend,\n%%\n%% \t% Teardown\n%% \tfun(_) ->\n%% \t\tmeck:unload()\n%% \tend,\n%%\n%% \t% Test runner\n%% \tfun(_) -> [\n%% \t\t{ \"does nothing\",\n%% \t\t\tfun() ->\n%% \t\t\t\t% Put Tests Here!\n%% \t\t\t\t?assert(true)\n%% \t\t\tend\n%% \t\t}]\n%% \tend\n%% \t}.\n\n","avg_line_length":14.6071428571,"max_line_length":40,"alphanum_fraction":0.5036674817} +{"size":31427,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 1998-2020. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n-module(seq_trace_SUITE).\n\n%% label_capability_mismatch needs to run a part of the test on an OTP 20 node.\n-compile(r20).\n\n-export([all\/0, suite\/0,groups\/0,init_per_suite\/1, end_per_suite\/1, \n\t init_per_group\/2,end_per_group\/2,\n\t init_per_testcase\/2,end_per_testcase\/2]).\n-export([token_set_get\/1, tracer_set_get\/1, print\/1,\n old_heap_token\/1,\n\t send\/1, distributed_send\/1, recv\/1, distributed_recv\/1,\n\t trace_exit\/1, distributed_exit\/1, call\/1, port\/1,\n port_clean_token\/1,\n\t match_set_seq_token\/1, gc_seq_token\/1, label_capability_mismatch\/1,\n send_literal\/1]).\n\n%% internal exports\n-export([simple_tracer\/2, one_time_receiver\/0, one_time_receiver\/1,\n n_time_receiver\/1,\n\t start_tracer\/0, stop_tracer\/1, \n\t do_match_set_seq_token\/1, do_gc_seq_token\/1, countdown_start\/2]).\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n\n-define(TIMESTAMP_MODES, [no_timestamp,\n\t\t\t timestamp,\n\t\t\t monotonic_timestamp,\n\t\t\t strict_monotonic_timestamp]).\n\nsuite() ->\n [{ct_hooks,[ts_install_cth]},\n {timetrap,{minutes,1}}].\n\nall() -> \n [token_set_get, tracer_set_get, print, send, send_literal,\n distributed_send, recv, distributed_recv, trace_exit,\n old_heap_token,\n distributed_exit, call, port, match_set_seq_token,\n port_clean_token,\n gc_seq_token, label_capability_mismatch].\n\ngroups() -> \n [].\n\ninit_per_suite(Config) ->\n Config.\n\nend_per_suite(_Config) ->\n ok.\n\ninit_per_group(_GroupName, Config) ->\n Config.\n\nend_per_group(_GroupName, Config) ->\n Config.\n\n\ninit_per_testcase(_Case, Config) ->\n Config.\n\nend_per_testcase(_Case, _Config) ->\n ok.\n\n%% Verifies that the set_token and get_token functions work as expected\n\ntoken_set_get(Config) when is_list(Config) ->\n do_token_set_get(timestamp),\n do_token_set_get(monotonic_timestamp),\n do_token_set_get(strict_monotonic_timestamp).\n \ndo_token_set_get(TsType) ->\n io:format(\"Testing ~p~n\", [TsType]),\n Flags = case TsType of\n\t\ttimestamp -> 15;\n\t\tstrict_monotonic_timestamp -> 23;\n\t\tmonotonic_timestamp -> 39\n\t end,\n Self = self(),\n seq_trace:reset_trace(),\n %% Test that initial seq_trace is disabled\n [] = seq_trace:get_token(),\n %% Test setting and reading the different fields\n 0 = seq_trace:set_token(label,{my_label,1}),\n {label,{my_label,1}} = seq_trace:get_token(label),\n false = seq_trace:set_token(print,true),\n {print,true} = seq_trace:get_token(print),\n false = seq_trace:set_token(send,true),\n {send,true} = seq_trace:get_token(send),\n false = seq_trace:set_token('receive',true),\n {'receive',true} = seq_trace:get_token('receive'),\n false = seq_trace:set_token(TsType,true),\n {TsType,true} = seq_trace:get_token(TsType),\n %% Check the whole token\n {Flags,{my_label,1},0,Self,0} = seq_trace:get_token(), % all flags are set\n %% Test setting and reading the 'serial' field\n {0,0} = seq_trace:set_token(serial,{3,5}),\n {serial,{3,5}} = seq_trace:get_token(serial),\n %% Check the whole token, test that a whole token can be set and get\n {Flags,{my_label,1},5,Self,3} = seq_trace:get_token(),\n seq_trace:set_token({Flags,19,7,Self,5}),\n {Flags,19,7,Self,5} = seq_trace:get_token(),\n %% Check that receive timeout does not reset token\n receive after 0 -> ok end,\n {Flags,19,7,Self,5} = seq_trace:get_token(),\n %% Check that token can be unset\n {Flags,19,7,Self,5} = seq_trace:set_token([]),\n [] = seq_trace:get_token(),\n %% Check that Previous serial counter survived unset token\n 0 = seq_trace:set_token(label, 17),\n {0,17,0,Self,5} = seq_trace:get_token(),\n %% Check that reset_trace resets the token and clears\n %% the Previous serial counter\n seq_trace:reset_trace(),\n [] = seq_trace:get_token(),\n 0 = seq_trace:set_token(label, 19),\n {0,19,0,Self,0} = seq_trace:get_token(),\n %% Cleanup\n seq_trace:reset_trace(),\n ok.\n\ntracer_set_get(Config) when is_list(Config) ->\n Self = self(),\n seq_trace:set_system_tracer(self()),\n Self = seq_trace:get_system_tracer(),\n Self = seq_trace:set_system_tracer(false),\n false = seq_trace:get_system_tracer(),\n\n %% Set the system tracer to a port.\n\n Port = load_tracer(Config),\n seq_trace:set_system_tracer(Port),\n Port = seq_trace:get_system_tracer(),\n Port = seq_trace:set_system_tracer(false),\n false = seq_trace:get_system_tracer(),\n ok.\n\nprint(Config) when is_list(Config) ->\n [do_print(TsType, Label) || TsType <- ?TIMESTAMP_MODES,\n Label <- [17, \"label\"]].\n \ndo_print(TsType, Label) ->\n start_tracer(),\n seq_trace:set_token(label, Label),\n set_token_flags([print, TsType]),\n seq_trace:print(Label,print1),\n seq_trace:print(1,print2),\n seq_trace:print(print3),\n seq_trace:reset_trace(),\n [{Label,{print,_,_,[],print1}, Ts0},\n {Label,{print,_,_,[],print3}, Ts1}] = stop_tracer(2),\n check_ts(TsType, Ts0),\n check_ts(TsType, Ts1).\n\nsend(Config) when is_list(Config) ->\n lists:foreach(fun do_send\/1, ?TIMESTAMP_MODES).\n\ndo_send(TsType) ->\n do_send(TsType, send).\n\ndo_send(TsType, Msg) ->\n seq_trace:reset_trace(),\n start_tracer(),\n Receiver = spawn(?MODULE,n_time_receiver,[2]),\n register(n_time_receiver, Receiver),\n Label = make_ref(),\n seq_trace:set_token(label,Label),\n set_token_flags([send, TsType]),\n Receiver ! Msg,\n n_time_receiver ! Msg,\n Self = self(),\n seq_trace:reset_trace(),\n [{Label,{send,_,Self,Receiver,Msg}, Ts1},\n %% Apparently named local destination process is traced as pid (!?)\n {Label,{send,_,Self,Receiver,Msg}, Ts2}\n ] = stop_tracer(2),\n check_ts(TsType, Ts1),\n check_ts(TsType, Ts2).\n\n%% This testcase tests that we do not segfault when we have a\n%% literal as the message and the message is copied onto the\n%% heap during a GC.\nsend_literal(Config) when is_list(Config) ->\n lists:foreach(fun do_send_literal\/1,\n [atom, make_ref(), ets:new(hej,[]), 1 bsl 64,\n \"gurka\", {tuple,test,with,#{}}, #{}]).\n\ndo_send_literal(Msg) ->\n N = 10000,\n seq_trace:reset_trace(),\n start_tracer(),\n Label = make_ref(),\n seq_trace:set_token(label,Label),\n set_token_flags([send, 'receive', no_timestamp]),\n Receiver = spawn_link(fun() -> receive ok -> ok end end),\n [Receiver ! Msg || _ <- lists:seq(1, N)],\n erlang:garbage_collect(Receiver),\n [Receiver ! Msg || _ <- lists:seq(1, N)],\n erlang:garbage_collect(Receiver),\n Self = self(),\n seq_trace:reset_trace(),\n [{Label,{send,_,Self,Receiver,Msg}, Ts} | _] = stop_tracer(N),\n check_ts(no_timestamp, Ts).\n\ndistributed_send(Config) when is_list(Config) ->\n lists:foreach(fun do_distributed_send\/1, ?TIMESTAMP_MODES).\n\ndo_distributed_send(TsType) ->\n {ok,Node} = start_node(seq_trace_other,[]),\n {_,Dir} = code:is_loaded(?MODULE),\n Mdir = filename:dirname(Dir),\n true = rpc:call(Node,code,add_patha,[Mdir]),\n seq_trace:reset_trace(),\n start_tracer(),\n Receiver = spawn(Node,?MODULE,n_time_receiver,[2]),\n true = rpc:call(Node,erlang,register,[n_time_receiver, Receiver]),\n\n %% Make sure complex labels survive the trip.\n Label = make_ref(),\n seq_trace:set_token(label,Label),\n set_token_flags([send,TsType]),\n\n Receiver ! send,\n {n_time_receiver, Node} ! \"dsend\",\n\n Self = self(),\n seq_trace:reset_trace(),\n stop_node(Node),\n [{Label,{send,_,Self,Receiver,send}, Ts1},\n {Label,{send,_,Self,{n_time_receiver,Node}, \"dsend\"}, Ts2}\n ] = stop_tracer(2),\n\n check_ts(TsType, Ts1),\n check_ts(TsType, Ts2).\n\n\nrecv(Config) when is_list(Config) ->\n lists:foreach(fun do_recv\/1, ?TIMESTAMP_MODES).\n\ndo_recv(TsType) ->\n seq_trace:reset_trace(),\n start_tracer(),\n Receiver = spawn(?MODULE,one_time_receiver,[]),\n set_token_flags(['receive',TsType]),\n Receiver ! 'receive',\n %% let the other process receive the message:\n receive after 1 -> ok end,\n Self = self(),\n seq_trace:reset_trace(),\n [{0,{'receive',_,Self,Receiver,'receive'}, Ts}] = stop_tracer(1),\n check_ts(TsType, Ts).\n\ndistributed_recv(Config) when is_list(Config) ->\n lists:foreach(fun do_distributed_recv\/1, ?TIMESTAMP_MODES).\n\ndo_distributed_recv(TsType) ->\n {ok,Node} = start_node(seq_trace_other,[]),\n {_,Dir} = code:is_loaded(?MODULE),\n Mdir = filename:dirname(Dir),\n true = rpc:call(Node,code,add_patha,[Mdir]),\n seq_trace:reset_trace(),\n rpc:call(Node,?MODULE,start_tracer,[]),\n Receiver = spawn(Node,?MODULE,one_time_receiver,[]),\n\n %% Make sure complex labels survive the trip.\n Label = make_ref(),\n seq_trace:set_token(label,Label),\n set_token_flags(['receive',TsType]),\n\n Receiver ! 'receive',\n %% let the other process receive the message:\n receive after 1 -> ok end,\n Self = self(),\n seq_trace:reset_trace(),\n Result = rpc:call(Node,?MODULE,stop_tracer,[1]),\n stop_node(Node),\n ok = io:format(\"~p~n\",[Result]),\n [{Label,{'receive',_,Self,Receiver,'receive'}, Ts}] = Result,\n check_ts(TsType, Ts).\n\ntrace_exit(Config) when is_list(Config) ->\n lists:foreach(fun do_trace_exit\/1, ?TIMESTAMP_MODES).\n\ndo_trace_exit(TsType) ->\n seq_trace:reset_trace(),\n start_tracer(),\n Receiver = spawn_link(?MODULE, one_time_receiver, [exit]),\n process_flag(trap_exit, true),\n\n %% Make sure complex labels survive the trip.\n Label = make_ref(),\n seq_trace:set_token(label,Label),\n set_token_flags([send, TsType]),\n\n Receiver ! {before, exit},\n %% let the other process receive the message:\n receive\n\t {'EXIT', Receiver, {exit, {before, exit}}} ->\n\t\t seq_trace:set_token([]);\n\t Other ->\n\t\t seq_trace:set_token([]),\n\t\t ct:fail({received, Other})\n\t end,\n Self = self(),\n Result = stop_tracer(2),\n seq_trace:reset_trace(),\n ok = io:format(\"~p~n\", [Result]),\n [{Label, {send, {0,1}, Self, Receiver, {before, exit}}, Ts0},\n\t {Label, {send, {1,2}, Receiver, Self,\n\t {'EXIT', Receiver, {exit, {before, exit}}}}, Ts1}] = Result,\n check_ts(TsType, Ts0),\n check_ts(TsType, Ts1).\n\ndistributed_exit(Config) when is_list(Config) ->\n lists:foreach(fun do_distributed_exit\/1, ?TIMESTAMP_MODES).\n\ndo_distributed_exit(TsType) ->\n {ok, Node} = start_node(seq_trace_other, []),\n {_, Dir} = code:is_loaded(?MODULE),\n Mdir = filename:dirname(Dir),\n true = rpc:call(Node, code, add_patha, [Mdir]),\n seq_trace:reset_trace(),\n rpc:call(Node, ?MODULE, start_tracer,[]),\n Receiver = spawn_link(Node, ?MODULE, one_time_receiver, [exit]),\n process_flag(trap_exit, true),\n set_token_flags([send, TsType]),\n Receiver ! {before, exit},\n %% let the other process receive the message:\n receive\n\t {'EXIT', Receiver, {exit, {before, exit}}} ->\n\t\t seq_trace:set_token([]);\n\t Other ->\n\t\t seq_trace:set_token([]),\n\t\t ct:fail({received, Other})\n\t end,\n Self = self(),\n Result = rpc:call(Node, ?MODULE, stop_tracer, [1]),\n seq_trace:reset_trace(),\n stop_node(Node),\n ok = io:format(\"~p~n\", [Result]),\n [{0, {send, {1, 2}, Receiver, Self,\n\t\t{'EXIT', Receiver, {exit, {before, exit}}}}, Ts}] = Result,\n check_ts(TsType, Ts).\n\nlabel_capability_mismatch(Config) when is_list(Config) ->\n Releases = [\"20_latest\"],\n Available = [Rel || Rel <- Releases, test_server:is_release_available(Rel)],\n case Available of\n [] -> {skipped, \"No incompatible releases available\"};\n _ ->\n lists:foreach(fun do_incompatible_labels\/1, Available),\n lists:foreach(fun do_compatible_labels\/1, Available),\n ok\n end.\n\ndo_incompatible_labels(Rel) ->\n Cookie = atom_to_list(erlang:get_cookie()),\n {ok, Node} = test_server:start_node(\n list_to_atom(atom_to_list(?MODULE)++\"_\"++Rel), peer,\n [{args, \" -setcookie \"++Cookie}, {erl, [{release, Rel}]}]),\n\n {_,Dir} = code:is_loaded(?MODULE),\n Mdir = filename:dirname(Dir),\n true = rpc:call(Node,code,add_patha,[Mdir]),\n seq_trace:reset_trace(),\n true = is_pid(rpc:call(Node,?MODULE,start_tracer,[])),\n Receiver = spawn(Node,?MODULE,one_time_receiver,[]),\n\n %% This node does not support arbitrary labels, so it must fail with a\n %% timeout as the token is dropped silently.\n seq_trace:set_token(label,make_ref()),\n seq_trace:set_token('receive',true),\n\n Receiver ! 'receive',\n %% let the other process receive the message:\n receive after 10 -> ok end,\n seq_trace:reset_trace(),\n\n {error,timeout} = rpc:call(Node,?MODULE,stop_tracer,[1]),\n stop_node(Node),\n ok.\n\ndo_compatible_labels(Rel) ->\n Cookie = atom_to_list(erlang:get_cookie()),\n {ok, Node} = test_server:start_node(\n list_to_atom(atom_to_list(?MODULE)++\"_\"++Rel), peer,\n [{args, \" -setcookie \"++Cookie}, {erl, [{release, Rel}]}]),\n\n {_,Dir} = code:is_loaded(?MODULE),\n Mdir = filename:dirname(Dir),\n true = rpc:call(Node,code,add_patha,[Mdir]),\n seq_trace:reset_trace(),\n true = is_pid(rpc:call(Node,?MODULE,start_tracer,[])),\n Receiver = spawn(Node,?MODULE,one_time_receiver,[]),\n\n %% This node does not support arbitrary labels, but small integers should\n %% still work.\n Label = 1234,\n seq_trace:set_token(label,Label),\n seq_trace:set_token('receive',true),\n\n Receiver ! 'receive',\n %% let the other process receive the message:\n receive after 10 -> ok end,\n Self = self(),\n seq_trace:reset_trace(),\n Result = rpc:call(Node,?MODULE,stop_tracer,[1]),\n stop_node(Node),\n ok = io:format(\"~p~n\",[Result]),\n [{Label,{'receive',_,Self,Receiver,'receive'}, _}] = Result,\n ok.\n\ncall(doc) -> \n \"Tests special forms {is_seq_trace} and {get_seq_token} \"\n\t\"in trace match specs.\";\ncall(Config) when is_list(Config) ->\n Self = self(),\n seq_trace:reset_trace(),\n TrA = transparent_tracer(),\n 1 =\n\terlang:trace(Self, true, \n\t\t [call, set_on_spawn, {tracer, TrA(pid)}]),\n 1 =\n\terlang:trace_pattern({?MODULE, call_tracee_1, 1},\n\t\t\t [{'_',\n\t\t\t [],\n\t\t\t [{message, {{{self}, {get_seq_token}}}}]}],\n\t\t\t [local]),\n 1 =\n\terlang:trace_pattern({?MODULE, call_tracee_2, 1},\n\t\t\t [{'_',\n\t\t\t [{is_seq_trace}],\n\t\t\t [{message, {{{self}, {get_seq_token}}}}]}],\n\t\t\t [local]),\n RefA = make_ref(),\n Pid2A = spawn_link(\n\t\t fun() ->\n\t\t\t receive {_, msg, RefA} -> ok end,\n\t\t\t RefA = call_tracee_2(RefA),\n\t\t\t Self ! {self(), msg, RefA}\n\t\t end),\n Pid1A = spawn_link(\n\t\t fun() ->\n\t\t\t receive {_, msg, RefA} -> ok end,\n\t\t\t RefA = call_tracee_1(RefA),\n\t\t\t Pid2A ! {self(), msg, RefA}\n\t\t end),\n Pid1A ! {Self, msg, RefA},\n %% The message is passed Self -> Pid1B -> Pid2B -> Self.\n %% Traced functions are called in Pid1B and Pid2B. \n receive {Pid2A, msg, RefA} -> ok end,\n %% Only call_tracee1 will be traced since the guard for \n %% call_tracee2 requires a sequential trace. The trace\n %% token is undefined.\n Token2A = [],\n {ok, [{trace, Pid1A, call,\n\t\t {?MODULE, call_tracee_1, [RefA]},\n\t\t {Pid1A, Token2A}}]} = \n\tTrA({stop, 1}),\n\n seq_trace:reset_trace(),\n\n TrB = transparent_tracer(),\n 1 =\n\terlang:trace(Self, true, \n\t\t [call, set_on_spawn, {tracer, TrB(pid)}]),\n Label = 17,\n seq_trace:set_token(label, Label), % Token enters here!!\n RefB = make_ref(),\n Pid2B = spawn_link(\n\t\t fun() ->\n\t\t\t receive {_, msg, RefB} -> ok end,\n\t\t\t RefB = call_tracee_2(RefB),\n\t\t\t Self ! {self(), msg, RefB}\n\t\t end),\n Pid1B = spawn_link(\n\t\t fun() ->\n\t\t\t receive {_, msg, RefB} -> ok end,\n\t\t\t RefB = call_tracee_1(RefB),\n\t\t\t Pid2B ! {self(), msg, RefB}\n\t\t end),\n Pid1B ! {Self, msg, RefB},\n %% The message is passed Self -> Pid1B -> Pid2B -> Self, and the \n %% seq_trace token follows invisibly. Traced functions are \n %% called in Pid1B and Pid2B. Seq_trace flags == 0 so no\n %% seq_trace messages are generated.\n receive {Pid2B, msg, RefB} -> ok end,\n %% The values of these counters {.., 1, _, 0}, {.., 2, _, 1}\n %% depend on that seq_trace has been reset just before this test.\n Token1B = {0, Label, 1, Self, 0},\n Token2B = {0, Label, 2, Pid1B, 1},\n {ok, [{trace, Pid1B, call,\n\t\t {?MODULE, call_tracee_1, [RefB]},\n\t\t {Pid1B, Token1B}},\n\t\t{trace, Pid2B, call, \n\t\t {?MODULE, call_tracee_2, [RefB]},\n\t\t {Pid2B, Token2B}}]} =\n\tTrB({stop,2}),\n seq_trace:reset_trace(),\n ok.\n\n%% Send trace messages to a port.\nport(Config) when is_list(Config) ->\n lists:foreach(fun (TsType) -> do_port(TsType, Config) end,\n\t\t ?TIMESTAMP_MODES).\n\ndo_port(TsType, Config) ->\n io:format(\"Testing ~p~n\",[TsType]),\n Port = load_tracer(Config),\n seq_trace:set_system_tracer(Port),\n\n set_token_flags([print, TsType]),\n Small = [small,term],\n seq_trace:print(0, Small),\n case get_port_message(Port) of\n\t {seq_trace,0,{print,_,_,[],Small}} when TsType == no_timestamp ->\n\t\t ok;\n\t {seq_trace,0,{print,_,_,[],Small},Ts0} when TsType \/= no_timestamp ->\n\t\t check_ts(TsType, Ts0),\n\t\t ok;\n\t Other ->\n\t\t seq_trace:reset_trace(),\n\t\t ct:fail({unexpected,Other})\n\t end,\n %% OTP-4218 Messages from ports should not affect seq trace token.\n %%\n %% Check if trace token still is active on this process after\n %% the get_port_message\/1 above that receives from a port.\n OtherSmall = [other | Small],\n seq_trace:print(0, OtherSmall),\n seq_trace:reset_trace(),\n case get_port_message(Port) of\n\t {seq_trace,0,{print,_,_,[],OtherSmall}} when TsType == no_timestamp ->\n\t\t ok;\n\t {seq_trace,0,{print,_,_,[],OtherSmall}, Ts1} when TsType \/= no_timestamp ->\n\t\t check_ts(TsType, Ts1),\n\t\t ok;\n\t Other1 ->\n\t\t ct:fail({unexpected,Other1})\n\t end,\n\n\n seq_trace:set_token(print, true),\n Huge = huge_data(),\n seq_trace:print(0, Huge),\n seq_trace:reset_trace(),\n case get_port_message(Port) of\n\t {seq_trace,0,{print,_,_,[],Huge}} ->\n\t\t ok;\n\t Other2 ->\n\t\t ct:fail({unexpected,Other2})\n\t end,\n unlink(Port),\n exit(Port,kill),\n ok.\n\nget_port_message(Port) ->\n receive\n\t{Port,{data,Bin}} when is_binary(Bin) ->\n\t binary_to_term(Bin);\n\tOther ->\n\t ct:fail({unexpected,Other})\n after 5000 ->\n\t ct:fail(timeout)\n end.\n\n\n%% OTP-15849 ERL-700\n%% Verify changing label on existing token when it resides on old heap.\n%% Bug caused faulty ref from old to new heap.\nold_heap_token(Config) when is_list(Config) ->\n seq_trace:set_token(label, 1),\n erlang:garbage_collect(self(), [{type, minor}]),\n erlang:garbage_collect(self(), [{type, minor}]),\n %% Now token tuple should be on old-heap.\n %% Set a new non-literal label which should reside on new-heap.\n NewLabel = {self(), \"new label\"},\n 1 = seq_trace:set_token(label, NewLabel),\n\n %% If bug, we now have a ref from old to new heap. Yet another minor gc\n %% will make that a ref to deallocated memory.\n erlang:garbage_collect(self(), [{type, minor}]),\n {label,NewLabel} = seq_trace:get_token(label),\n ok.\n\n\nmatch_set_seq_token(doc) ->\n [\"Tests that match spec function set_seq_token does not \"\n \"corrupt the heap\"];\nmatch_set_seq_token(Config) when is_list(Config) ->\n Parent = self(),\n\n %% OTP-4222 Match spec 'set_seq_token' corrupts heap\n %%\n %% This test crashes the emulator if the bug in question is present,\n %% it is therefore done in a slave node.\n %%\n %% All the timeout stuff is here to get decent accuracy of the error\n %% return value, instead of just 'timeout'.\n %%\n {ok, Sandbox} = start_node(seq_trace_other, []),\n true = rpc:call(Sandbox, code, add_patha,\n\t\t\t [filename:dirname(code:which(?MODULE))]),\n Lbl = 4711,\n %% Do the possibly crashing test\n P1 =\n\tspawn(\n\t fun () ->\n\t\t Parent ! {self(),\n\t\t\t rpc:call(Sandbox, \n\t\t\t\t ?MODULE, do_match_set_seq_token, [Lbl])}\n\t end),\n %% Probe the node with a simple rpc request, to see if it is alive.\n P2 =\n\tspawn(\n\t fun () ->\n\t\t receive after 4000 -> ok end,\n\t\t Parent ! {self(), rpc:call(Sandbox, erlang, abs, [-1])}\n\t end),\n %% If the test node hangs completely, this timer expires.\n R3 = erlang:start_timer(8000, self(), void),\n %%\n {ok, Log} =\n\treceive\n\t {P1, Result} ->\n\t\texit(P2, done),\n\t\terlang:cancel_timer(R3),\n\t\tResult;\n\t {P2, 1} ->\n\t\texit(P1, timeout),\n\t\terlang:cancel_timer(R3),\n\t\t{error, \"Test process hung\"};\n\t {timeout, R3, _} ->\n\t\texit(P1, timeout),\n\t\texit(P2, timeout),\n\t\t{error, \"Test node hung\"}\n\tend,\n\n %% Sort the log on Pid, as events from different processes\n %% are not guaranteed to arrive in a certain order to the\n %% tracer\n SortedLog = lists:keysort(2, Log),\n\n ok = check_match_set_seq_token_log(Lbl, SortedLog),\n %%\n stop_node(Sandbox),\n ok.\n\n%% OTP-4222 Match spec 'set_seq_token' corrupts heap\n%%\n%% The crashing test goes as follows:\n%%\n%% One trigger function calls match spec function {set_seq_token, _, _},\n%% which when faulty corrupts the heap. It is assured that the process\n%% in question has a big heap and recently garbage collected so there \n%% will be room on the heap, which is necessary for the crash to happen.\n%%\n%% Then two processes bounces a few messages between each other, and if\n%% the heap is crashed the emulator crashes, or the triggering process's\n%% loop data gets corrupted so the loop never ends.\ndo_match_set_seq_token(Label) ->\n seq_trace:reset_trace(),\n Tr = transparent_tracer(),\n TrPid = Tr(pid),\n erlang:trace_pattern({?MODULE, '_', '_'}, \n\t\t\t [{'_', \n\t\t\t [{is_seq_trace}], \n\t\t\t [{message, {get_seq_token}}]}], \n\t\t\t [local]),\n erlang:trace_pattern({?MODULE, countdown, 2}, \n\t\t\t [{'_', \n\t\t\t [], \n\t\t\t [{set_seq_token, label, Label},\n\t\t\t {message, {get_seq_token}}]}],\n\t\t\t [local]),\n erlang:trace(new, true, [call, {tracer, TrPid}]),\n Ref = make_ref(),\n Bounce = spawn(fun () -> bounce(Ref) end),\n Mref = erlang:monitor(process, Bounce),\n _Countdown = erlang:spawn_opt(?MODULE, countdown_start, [Bounce, Ref],\n\t\t\t\t [{min_heap_size, 4192}]),\n receive \n\t{'DOWN', Mref, _, _, normal} -> \n\t Result = Tr({stop, 0}),\n\t seq_trace:reset_trace(),\n\t erlang:trace(new, false, [call]),\n\t Result;\n\t{'DOWN', Mref, _, _, Reason} ->\n\t Tr({stop, 0}),\n\t seq_trace:reset_trace(),\n\t erlang:trace(new, false, [call]),\n\t {error, Reason}\n end.\n\ncheck_match_set_seq_token_log(\n Label,\n [{trace,B,call,{?MODULE,bounce, [Ref]}, {0,Label,2,B,1}},\n {trace,B,call,{?MODULE,bounce, [Ref]}, {0,Label,4,B,3}},\n {trace,B,call,{?MODULE,bounce, [Ref]}, {0,Label,6,B,5}},\n {trace,C,call,{?MODULE,countdown,[B,Ref]}, {0,Label,0,C,0}},\n {trace,C,call,{?MODULE,countdown,[B,Ref,3]},{0,Label,0,C,0}},\n {trace,C,call,{?MODULE,countdown,[B,Ref,2]},{0,Label,2,B,1}},\n {trace,C,call,{?MODULE,countdown,[B,Ref,1]},{0,Label,4,B,3}},\n {trace,C,call,{?MODULE,countdown,[B,Ref,0]},{0,Label,6,B,5}}\n ]) ->\n ok;\ncheck_match_set_seq_token_log(_Label, Log) ->\n {error, Log}.\n\ncountdown_start(Bounce, Ref) ->\n %% This gc and the increased heap size of this process ensures that\n %% the match spec executed for countdown\/2 has got heap space for\n %% the trace token, so the heap gets trashed according to OTP-4222.\n erlang:garbage_collect(),\n countdown(Bounce, Ref).\n\ncountdown(Bounce, Ref) ->\n countdown(Bounce, Ref, 3).\n\ncountdown(Bounce, Ref, 0) ->\n Bounce ! Ref;\ncountdown(Bounce, Ref, Cnt) ->\n Tag = make_ref(),\n Bounce ! {Ref, self(), {Tag, Cnt}},\n receive {Tag, Cnt} -> countdown(Bounce, Ref, Cnt-1) end.\n\nbounce(Ref) ->\n receive \n\tRef ->\n\t ok;\n\t{Ref, Dest, Msg} ->\n\t Dest ! Msg,\n\t bounce(Ref)\n end.\n\n\n\ngc_seq_token(doc) ->\n [\"Tests that a seq_trace token on a message in the inqueue \",\n \"can be garbage collected.\"];\ngc_seq_token(Config) when is_list(Config) ->\n Parent = self(),\n\n %% OTP-4555 Seq trace token causes free mem read in gc\n %%\n %% This test crashes the emulator if the bug in question is present,\n %% it is therefore done in a slave node.\n %%\n %% All the timeout stuff is here to get decent accuracy of the error\n %% return value, instead of just 'timeout'.\n %%\n {ok, Sandbox} = start_node(seq_trace_other, []),\n true = rpc:call(Sandbox, code, add_patha,\n\t\t\t [filename:dirname(code:which(?MODULE))]),\n Label = 4711,\n %% Do the possibly crashing test\n P1 =\n\tspawn(\n\t fun () ->\n \t\t Parent ! {self(),\n\t\t\t rpc:call(Sandbox, \n\t\t\t\t ?MODULE, do_gc_seq_token, [Label])}\n\t end),\n %% Probe the node with a simple rpc request, to see if it is alive.\n P2 =\n\tspawn(\n\t fun () ->\n\t\t receive after 4000 -> ok end,\n\t\t Parent ! {self(), rpc:call(Sandbox, erlang, abs, [-1])}\n\t end),\n %% If the test node hangs completely, this timer expires.\n R3 = erlang:start_timer(8000, self(), void),\n %%\n ok =\n\treceive\n\t {P1, Result} ->\n\t\texit(P2, done),\n\t\terlang:cancel_timer(R3),\n\t\tResult;\n\t {P2, 1} ->\n\t\texit(P1, timeout),\n\t\terlang:cancel_timer(R3),\n\t\t{error, \"Test process hung\"};\n\t {timeout, R3, _} ->\n\t\texit(P1, timeout),\n\t\texit(P2, timeout),\n\t\t{error, \"Test node hung\"}\n\tend,\n %%\n stop_node(Sandbox),\n ok.\n\ndo_gc_seq_token(Label) ->\n Parent = self(),\n Comment = \n\t{\"OTP-4555 Seq trace token causes free mem read in gc\\n\"\n\t \"\\n\"\n\t \"The crashing test goes as follows:\\n\"\n\t \"\\n\"\n\t \"Put a message with seq_trace token in the inqueue,\\n\"\n\t \"Grow the process heap big enough to become mmap'ed\\n\"\n\t \"and force a garbage collection using large terms\\n\"\n\t \"to get a test_heap instruction with a big size value.\\n\"\n\t \"Then try to trick the heap into shrinking.\\n\"\n\t \"\\n\"\n\t \"All this to make the GC move the heap between memory blocks.\\n\"},\n seq_trace:reset_trace(),\n Child = spawn_link(\n\t fun() ->\n\t\t receive {Parent, no_seq_trace_token} -> ok end,\n\t\t do_grow(Comment, 256*1024, []),\n\t\t do_shrink(10),\n\t\t receive {Parent, seq_trace_token} -> ok end,\n\t\t Parent ! {self(), {token, seq_trace:get_token(label)}}\n\t end),\n seq_trace:set_token(label, Label),\n Child ! {Parent, seq_trace_token},\n seq_trace:set_token([]),\n Child ! {Parent, no_seq_trace_token},\n receive \n\t{Child, {token, {label, Label}}} -> \n\t ok;\n\t{Child, {token, Other}} ->\n\t {error, Other}\n end.\n\ndo_grow(_, 0, Acc) ->\n Acc;\ndo_grow(E, N, Acc) ->\n do_grow(E, N-1, [E | Acc]).\n\ndo_shrink(0) ->\n ok;\ndo_shrink(N) ->\n erlang:garbage_collect(),\n do_shrink(N-1).\n\n%% Test that messages from a port does not clear the token\nport_clean_token(Config) when is_list(Config) ->\n seq_trace:reset_trace(),\n Label = make_ref(),\n seq_trace:set_token(label, Label),\n {label,Label} = seq_trace:get_token(label),\n\n %% Create a port and get messages from it\n %% We use os:cmd as a convenience as it does\n %% open_port, port_command, port_close and receives replies.\n %% Maybe it is not ideal to rely on the internal implementation\n %% of os:cmd but it will have to do.\n os:cmd(\"ls\"),\n\n %% Make sure that the seq_trace token is still there\n {label,Label} = seq_trace:get_token(label),\n\n ok.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Internal help functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Call trace targets\n\ncall_tracee_1(X) ->\n X.\n\ncall_tracee_2(X) ->\n X.\n\n\ntransparent_tracer() ->\n Ref = make_ref(),\n Loop = \n\tfun(Fun, Log, LN) ->\n\t\treceive\n\t\t {stop, MinLN, Ref, From} when LN >= MinLN ->\n\t\t\tFrom ! {log, Ref, lists:reverse(Log)};\n\t\t Entry when is_tuple(Entry) == false; element(1, Entry) \/= stop ->\n\t\t\tFun(Fun, [Entry | Log], LN+1)\n\t\tend\n\tend,\n Self = self(),\n Pid = \n\tspawn(fun() ->\n\t\t seq_trace:set_system_tracer(self()),\n\t\t Self ! {started, Ref},\n\t\t Loop(Loop, [], 0) \n\t end),\n receive {started, Ref} -> ok end,\n fun(pid) ->\n\t Pid;\n ({stop, N}) when is_integer(N), N >= 0 ->\n\t Mref = erlang:monitor(process, Pid),\n\t receive\n\t\t{'DOWN', Mref, _, _, _} ->\n\t\t {error, not_started}\n\t after 0 ->\n\t\t DeliverRef = erlang:trace_delivered(all),\n\t\t receive\n\t\t\t{trace_delivered,_,DeliverRef} -> ok\n\t\t end,\n\t\t Pid ! {stop, N, Ref, self()},\n\t\t receive {'DOWN', Mref, _, _, _} -> ok end,\n\t\t receive {log, Ref, Log} -> \n\t\t\t {ok, Log} \n\t\t end\n\t end\n end.\n\nn_time_receiver(0) ->\n ok;\nn_time_receiver(N) ->\n receive _Term -> n_time_receiver(N-1)\n end.\n\none_time_receiver() ->\n receive _Term -> ok\n end.\n\t\none_time_receiver(exit) ->\n receive Term ->\n\t exit({exit, Term}) \n end.\n\nsimple_tracer(Data, DN) ->\n receive\n\t{seq_trace,Label,Info,Ts} ->\n\t simple_tracer([{Label,Info,Ts}|Data], DN+1);\n\t{seq_trace,Label,Info} ->\n\t simple_tracer([{Label,Info, no_timestamp}|Data], DN+1);\n\t{stop,N,From} when DN >= N ->\n\t From ! {tracerlog,lists:reverse(Data)}\n end.\n\nstop_tracer(N) when is_integer(N) ->\n case catch (seq_trace_SUITE_tracer ! {stop,N,self()}) of\n\t{'EXIT', _} ->\n\t {error, not_started};\n\t_ ->\n\t receive\n\t\t{tracerlog,Data} ->\n\t\t Data\n\t after 1000 ->\n\t\t {error,timeout}\n\t end\n end.\n\nstart_tracer() ->\n stop_tracer(0),\n Pid = spawn(?MODULE,simple_tracer,[[], 0]),\n register(seq_trace_SUITE_tracer,Pid),\n seq_trace:set_system_tracer(Pid),\n Pid.\n\nset_token_flags([]) ->\n ok;\nset_token_flags([no_timestamp|Flags]) ->\n seq_trace:set_token(timestamp, false),\n seq_trace:set_token(monotonic_timestamp, false),\n seq_trace:set_token(strict_monotonic_timestamp, false),\n set_token_flags(Flags);\nset_token_flags([Flag|Flags]) ->\n seq_trace:set_token(Flag, true),\n set_token_flags(Flags).\n\ncheck_ts(no_timestamp, Ts) ->\n try\n\tno_timestamp = Ts\n catch\n\t_ : _ ->\n\t ct:fail({unexpected_timestamp, Ts})\n end,\n ok;\ncheck_ts(timestamp, Ts) ->\n try\n\t{Ms,S,Us} = Ts,\n\ttrue = is_integer(Ms),\n\ttrue = is_integer(S),\n\ttrue = is_integer(Us)\n catch\n\t_ : _ ->\n\t ct:fail({unexpected_timestamp, Ts})\n end,\n ok;\ncheck_ts(monotonic_timestamp, Ts) ->\n try\n\ttrue = is_integer(Ts)\n catch\n\t_ : _ ->\n\t ct:fail({unexpected_timestamp, Ts})\n end,\n ok;\ncheck_ts(strict_monotonic_timestamp, Ts) ->\n try\n\t{MT, UMI} = Ts,\n\ttrue = is_integer(MT),\n\ttrue = is_integer(UMI)\n catch\n\t_ : _ ->\n\t ct:fail({unexpected_timestamp, Ts})\n end,\n ok.\n\nstart_node(Name, Param) ->\n test_server:start_node(Name, slave, [{args, Param}]).\n\nstop_node(Node) ->\n test_server:stop_node(Node).\n\nload_tracer(Config) ->\n Path = proplists:get_value(data_dir, Config),\n ok = erl_ddll:load_driver(Path, echo_drv),\n open_port({spawn,echo_drv}, [eof,binary]).\n\nhuge_data() -> huge_data(16384).\nhuge_data(0) -> [];\nhuge_data(N) when N rem 2 == 0 ->\n P = huge_data(N div 2),\n [P|P];\nhuge_data(N) ->\n P = huge_data(N div 2),\n [16#1234566,P|P].\n","avg_line_length":30.1892411143,"max_line_length":82,"alphanum_fraction":0.6305087982} +{"size":3640,"ext":"erl","lang":"Erlang","max_stars_count":40.0,"content":"%%%-------------------------------------------------------------------\n%%% File : cache_tab_app.erl\n%%% Author : Evgeniy Khramtsov \n%%% Description : Cache tab application\n%%%\n%%% Created : 8 May 2013 by Evgeniy Khramtsov \n%%%\n%%%\n%%% Copyright (C) 2002-2021 ProcessOne, SARL. All Rights Reserved.\n%%%\n%%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%%% you may not use this file except in compliance with the License.\n%%% You may obtain a copy of the License at\n%%%\n%%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%%\n%%% Unless required by applicable law or agreed to in writing, software\n%%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%%% See the License for the specific language governing permissions and\n%%% limitations under the License.\n%%%\n%%%-------------------------------------------------------------------\n-module(cache_tab_app).\n\n-behaviour(application).\n\n%% Application callbacks\n-export([start\/2, stop\/1, get_nodes\/0]).\n\n-define(PG, cache_tab).\n\n-include(\"ets_cache.hrl\").\n\n-ifdef(USE_OLD_PG2).\npg_create(PoolName) -> pg2:create(PoolName).\npg_join(PoolName, Pid) -> pg2:join(PoolName, Pid).\npg_get_members(Name) -> pg2:get_members(Name).\n-else.\npg_create(_) -> pg:start_link().\npg_join(PoolName, Pid) -> pg:join(PoolName, Pid).\npg_get_members(Group) -> pg:get_members(Group).\n-endif.\n\n%%%===================================================================\n%%% Application callbacks\n%%%===================================================================\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% This function is called whenever an application is started using\n%% application:start\/[1,2], and should start the processes of the\n%% application. If the application is structured according to the OTP\n%% design principles as a supervision tree, this means starting the\n%% top supervisor of the tree.\n%%\n%% @spec start(StartType, StartArgs) -> {ok, Pid} |\n%% {ok, Pid, State} |\n%% {error, Reason}\n%% StartType = normal | {takeover, Node} | {failover, Node}\n%% StartArgs = term()\n%% @end\n%%--------------------------------------------------------------------\nstart(_StartType, _StartArgs) ->\n case cache_tab_sup:start_link() of\n {ok, Pid} ->\n pg_create(?PG),\n pg_join(?PG, Pid),\n\t application:start(p1_utils),\n\t init_ets_cache_options(),\n {ok, Pid};\n Error ->\n Error\n end.\n\n%%--------------------------------------------------------------------\n%% @private\n%% @doc\n%% This function is called whenever an application has stopped. It\n%% is intended to be the opposite of Module:start\/2 and should do\n%% any necessary cleaning up. The return value is ignored.\n%%\n%% @spec stop(State) -> void()\n%% @end\n%%--------------------------------------------------------------------\nstop(_State) ->\n ok.\n\nget_nodes() ->\n [node(P) || P <- pg_get_members(?PG)].\n\n%%%===================================================================\n%%% Internal functions\n%%%===================================================================\ninit_ets_cache_options() ->\n p1_options:start_link(ets_cache_options),\n p1_options:insert(ets_cache_options, max_size, global, ?DEFAULT_MAX_SIZE),\n p1_options:insert(ets_cache_options, life_time, global, ?DEFAULT_LIFE_TIME),\n p1_options:insert(ets_cache_options, cache_missed, global, ?DEFAULT_CACHE_MISSED).\n","avg_line_length":36.0396039604,"max_line_length":86,"alphanum_fraction":0.5436813187} +{"size":3533,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"-module(raptor).\n\n-behaviour(gen_server).\n\n%% gen_server interface\n-export([start_link\/1, start\/1]).\n\n%% gen_server callbacks\n-export ([init\/1,\n\t handle_call\/3,\n\t handle_cast\/2,\n\t handle_info\/2,\n\t code_change\/3,\n\t terminate\/2]).\n\n%% API functions\n-export([parse_uri\/1, parse_uri\/2, test\/0]).\n\n%% server state\n-record(state, {port}).\n\n%% ===================================================================\n%% gen_server interface \n%% ===================================================================\nstart_link(SharedLib) ->\n\tgen_server:start_link({local, ?MODULE}, ?MODULE, SharedLib, []).\n\nstart(SharedLib) ->\n\tgen_server:start({local, ?MODULE}, ?MODULE, SharedLib, []).\n\n%% ===================================================================\n%% gen_server callbacks\n%% ===================================================================\ninit(SharedLib) ->\n\tcase load_driver(SharedLib) of\n\t\t{ok, Port} -> {ok, #state{port = Port}};\n\t\t{error, Msg} -> {stop, Msg};\n\t\t_ -> {stop, failed_to_load_driver}\n\tend.\n\nload_driver(SharedLib) ->\n\tPrivDir = code:priv_dir(?MODULE),\n\tResult = case erl_ddll:load_driver(PrivDir, SharedLib) of\n\t\tok -> ok;\n\t\t{error, already_loaded} -> ok;\n\t\t{error, ErrorDesc} -> {error, erl_ddll:format_error(ErrorDesc)}\n\tend,\n\tcase Result of\n\t\tok ->\n\t\t\tprocess_flag(trap_exit,true),\n\t\t\tcase open_port({spawn, SharedLib},[]) of\n\t\t\t\tP when is_port(P) -> {ok, P};\n\t\t\t\tError -> {error, Error}\n\t\t\tend;\n\t\t{error, Reason} -> {error, Reason}\n\tend.\n\nhandle_cast(_Msg, State) ->\n\t{noreply, State}.\n\n%% code_change not working, implementing stub\ncode_change(_OldVsn, State, _Extra) ->\n\t{ok, State}.\n\nhandle_info({'EXIT', _Port, Reason}, State) ->\n\t{stop, {port_terminated, Reason}, State};\nhandle_info(_Info, State) ->\n\t{noreply, State}.\n\nterminate({port_terminated, _Reason}, _State) ->\n\tok;\nterminate(_Reason, #state{port = Port} = _State) ->\n\tport_close(Port).\n\nhandle_call(Msg, _From, #state{port = Port} = State) ->\n\tport_command(Port, encode(Msg)),\n\tcase collect_response() of\n\t\t{error, Reason} ->\n\t\t\t{stop, Reason, State};\n\t\t{response, Response} ->\n\t\t\t{reply, Response, State};\n\t\ttimeout ->\n\t\t\t{stop, port_timeout, State}\n\tend.\n\ncollect_response() ->\n\tcollect_response([]).\n\ncollect_response(Acc) ->\n\treceive\n\t\t{error, Reason}->\n\t\t\t{error, Reason};\n\t\tok ->\n\t\t\t{response, lists:reverse(Acc)};\n\t\tData ->\n\t\t\tcollect_response([Data|Acc])\n\tend.\n\n%% ===================================================================\n%% API functions\n%% ===================================================================\ntest() ->\n\tcall_server({test}).\n\nparse_uri(Uri) ->\n\tcall_server({parse_uri,Uri}).\n\nparse_uri(Uri,Format) ->\n\tcall_server({parse_uri, Uri, Format}).\n\ncall_server(Msg) ->\n\tgen_server:call(?MODULE, Msg, get_timeout()).\n\nget_timeout() ->\n\t{ok, Value} = application:get_env(raptor, timeout),\n\tValue.\n\nencode({test}) -> [1];\nencode({parse_uri, Uri}) -> encode({parse_uri, Uri, default});\nencode({parse_uri, Uri, Format}) -> [2,encode_format(Format),Uri].\n\nencode_format(In) ->\n\tcase In of\n\t\tdefault -> 0; % default (RDF\/XML) \n\t\trdfxml -> 1; % RDF\/XML (default)\n\t\tntriples -> 2; % N-Triples\n\t\tturtle -> 3; % Turtle Terse RDF Triple Language\n\t\ttrig -> 4; % TriG - Turtle with Named Graphs\n\t\trss_tag_soup -> 5; % RSS Tag Soup\n\t\tgrddl -> 6; % Gleaning Resource Descriptions from Dialects of Languages\n\t\tguess -> 7; % Pick the parser to use using content type and URI\n\t\trdfa -> 8; % RDF\/A via librdfa\n\t\tnquads -> 9 % N-Quadsd\n\tend.\n","avg_line_length":26.1703703704,"max_line_length":80,"alphanum_fraction":0.5683555052} +{"size":4522,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"% Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n% use this file except in compliance with the License. You may obtain a copy of\n% the License at\n%\n% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n% License for the specific language governing permissions and limitations under\n% the License.\n\n-module(couch_views_server).\n\n\n-behaviour(gen_server).\n\n\n-export([\n start_link\/0\n]).\n\n-export([\n accepted\/1\n]).\n\n-export([\n init\/1,\n terminate\/2,\n handle_call\/3,\n handle_cast\/2,\n handle_info\/2,\n code_change\/3,\n format_status\/2\n]).\n\n-define(MAX_ACCEPTORS, 5).\n-define(MAX_WORKERS, 100).\n\n\nstart_link() ->\n gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).\n\n\naccepted(Worker) when is_pid(Worker) ->\n gen_server:call(?MODULE, {accepted, Worker}, infinity).\n\n\ninit(_) ->\n process_flag(trap_exit, true),\n couch_views_jobs:set_timeout(),\n St = #{\n acceptors => #{},\n workers => #{},\n max_acceptors => max_acceptors(),\n max_workers => max_workers()\n },\n {ok, spawn_acceptors(St)}.\n\n\nterminate(_, _St) ->\n ok.\n\n\nhandle_call({accepted, Pid}, _From, St) ->\n #{\n acceptors := Acceptors,\n workers := Workers\n } = St,\n case maps:is_key(Pid, Acceptors) of\n true ->\n St1 = St#{\n acceptors := maps:remove(Pid, Acceptors),\n workers := Workers#{Pid => true}\n },\n {reply, ok, spawn_acceptors(St1)};\n false ->\n LogMsg = \"~p : unknown acceptor processs ~p\",\n couch_log:error(LogMsg, [?MODULE, Pid]),\n {stop, {unknown_acceptor_pid, Pid}, St}\n end;\n\nhandle_call(Msg, _From, St) ->\n {stop, {bad_call, Msg}, {bad_call, Msg}, St}.\n\n\nhandle_cast(Msg, St) ->\n {stop, {bad_cast, Msg}, St}.\n\n\nhandle_info({'EXIT', Pid, Reason}, St) ->\n #{\n acceptors := Acceptors,\n workers := Workers\n } = St,\n\n % In Erlang 21+ could check map keys directly in the function head\n case {maps:is_key(Pid, Acceptors), maps:is_key(Pid, Workers)} of\n {true, false} -> handle_acceptor_exit(St, Pid, Reason);\n {false, true} -> handle_worker_exit(St, Pid, Reason);\n {false, false} -> handle_unknown_exit(St, Pid, Reason)\n end;\n\nhandle_info(Msg, St) ->\n {stop, {bad_info, Msg}, St}.\n\n\ncode_change(_OldVsn, St, _Extra) ->\n {ok, St}.\n\n\nformat_status(_Opt, [_PDict, State]) ->\n #{\n workers := Workers,\n acceptors := Acceptors\n } = State,\n Scrubbed = State#{\n workers => {map_size, maps:size(Workers)},\n acceptors => {map_size, maps:size(Acceptors)}\n },\n [{data, [{\"State\",\n Scrubbed\n }]}].\n\n\n% Worker process exit handlers\n\nhandle_acceptor_exit(#{acceptors := Acceptors} = St, Pid, Reason) ->\n St1 = St#{acceptors := maps:remove(Pid, Acceptors)},\n LogMsg = \"~p : acceptor process ~p exited with ~p\",\n couch_log:error(LogMsg, [?MODULE, Pid, Reason]),\n {noreply, spawn_acceptors(St1)}.\n\n\nhandle_worker_exit(#{workers := Workers} = St, Pid, normal) ->\n St1 = St#{workers := maps:remove(Pid, Workers)},\n {noreply, spawn_acceptors(St1)};\n\nhandle_worker_exit(#{workers := Workers} = St, Pid, Reason) ->\n St1 = St#{workers := maps:remove(Pid, Workers)},\n LogMsg = \"~p : indexer process ~p exited with ~p\",\n couch_log:error(LogMsg, [?MODULE, Pid, Reason]),\n {noreply, spawn_acceptors(St1)}.\n\n\nhandle_unknown_exit(St, Pid, Reason) ->\n LogMsg = \"~p : unknown process ~p exited with ~p\",\n couch_log:error(LogMsg, [?MODULE, Pid, Reason]),\n {stop, {unknown_pid_exit, Pid}, St}.\n\n\nspawn_acceptors(St) ->\n #{\n workers := Workers,\n acceptors := Acceptors,\n max_acceptors := MaxAcceptors,\n max_workers := MaxWorkers\n } = St,\n ACnt = maps:size(Acceptors),\n WCnt = maps:size(Workers),\n case ACnt < MaxAcceptors andalso (ACnt + WCnt) < MaxWorkers of\n true ->\n Pid = couch_views_indexer:spawn_link(),\n NewSt = St#{acceptors := Acceptors#{Pid => true}},\n spawn_acceptors(NewSt);\n false ->\n St\n end.\n\n\nmax_acceptors() ->\n config:get_integer(\"couch_views\", \"max_acceptors\", ?MAX_ACCEPTORS).\n\n\nmax_workers() ->\n config:get_integer(\"couch_views\", \"max_workers\", ?MAX_WORKERS).\n","avg_line_length":25.5480225989,"max_line_length":79,"alphanum_fraction":0.6090225564} +{"size":5399,"ext":"erl","lang":"Erlang","max_stars_count":4.0,"content":"% @copyright 2007-2015 Zuse Institute Berlin\n\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\n%% @author Thorsten Schuett \n%% @doc Re-register with mgmt_server nodes\n%% @end\n%% @version $Id$\n-module(dht_node_reregister).\n\n-author('schuett@zib.de').\n-vsn('$Id$').\n\n-behaviour(gen_component).\n\n-include(\"scalaris.hrl\").\n\n-export([start_link\/1]).\n-export([init\/1, on_active\/2, on_inactive\/2,\n activate\/0, deactivate\/0]).\n\n-include(\"gen_component.hrl\").\n\n-type(message() ::\n {register_trigger} |\n {register} |\n {web_debug_info, Requestor::comm:erl_local_pid()}).\n\n-type state_active() :: ok.\n-type state_inactive() :: inactive.\n\n%% @doc Activates the re-register process. If not activated, it will\n%% queue most messages without processing them.\n-spec activate() -> ok.\nactivate() ->\n Pid = pid_groups:get_my(dht_node_reregister),\n comm:send_local(Pid, {activate_reregister}).\n\n%% @doc Deactivates the re-register process.\n-spec deactivate() -> ok.\ndeactivate() ->\n Pid = pid_groups:get_my(dht_node_reregister),\n comm:send_local(Pid, {deactivate_reregister}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Startup\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% @doc Starts a re-register process, registers it with the process\n%% dictionary and returns its pid for use by a supervisor.\n-spec start_link(pid_groups:groupname()) -> {ok, pid()}.\nstart_link(DHTNodeGroup) ->\n gen_component:start_link(?MODULE, fun ?MODULE:on_inactive\/2, [],\n [{pid_groups_join_as, DHTNodeGroup, ?MODULE}]).\n\n%% @doc Initialises the module with an uninitialized state.\n-spec init([]) -> state_inactive().\ninit([]) ->\n msg_delay:send_trigger(get_base_interval(), {register_trigger}),\n inactive.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Message Loop\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n-spec on_inactive(message(), state_inactive()) -> state_inactive();\n ({activate_reregister}, state_inactive()) -> {'$gen_component', [{on_handler, Handler::gen_component:handler()}], State::state_active()}.\non_inactive({activate_reregister}, _State) ->\n log:log(info, \"[ Reregister ~.0p ] activating...~n\", [comm:this()]),\n comm:send_local(self(), {register}),\n gen_component:change_handler(ok, fun ?MODULE:on_active\/2);\n\non_inactive({web_debug_info, Requestor}, State) ->\n KeyValueList = [{\"\", \"\"}, {\"inactive re-register process\", \"\"}],\n comm:send_local(Requestor, {web_debug_info_reply, KeyValueList}),\n State;\n\non_inactive({register_trigger}, State) ->\n msg_delay:send_trigger(get_base_interval(), {register_trigger}),\n State;\n\non_inactive(_Msg, State) ->\n State.\n\n-spec on_active(message(), state_active()) -> state_active();\n ({deactivate_reregister}, state_active()) -> {'$gen_component', [{on_handler, Handler::gen_component:handler()}], State::state_inactive()}.\non_active({deactivate_reregister}, _State) ->\n log:log(info, \"[ Reregister ~.0p ] deactivating...~n\", [comm:this()]),\n gen_component:change_handler(inactive, fun ?MODULE:on_inactive\/2);\n\non_active({register_trigger}, State) ->\n msg_delay:send_trigger(get_base_interval(), {register_trigger}),\n gen_component:post_op({register}, State);\n\non_active({register}, State) ->\n comm:send_local(pid_groups:get_my(dht_node),\n {get_node_details, comm:this(), [node]}),\n State;\n\non_active({get_node_details_response, NodeDetails}, State) ->\n RegisterMessage = {register, node_details:get(NodeDetails, node)},\n _ = case config:read(register_hosts) of\n failed -> MgmtServer = mgmtServer(),\n case comm:is_valid(MgmtServer) of\n true -> comm:send(MgmtServer, RegisterMessage);\n _ -> ok\n end;\n Hosts -> [comm:send(Host, RegisterMessage) || Host <- Hosts]\n end,\n State;\n\non_active({web_debug_info, Requestor}, State) ->\n KeyValueList =\n case config:read(register_hosts) of\n failed -> [{\"Hosts (mgmt_server):\", webhelpers:safe_html_string(\"~.0p\", [mgmtServer()])}];\n Hosts -> [{\"Hosts:\", \"\"} |\n [{\"\", webhelpers:safe_html_string(\"~.0p\", [Host])} || Host <- Hosts]]\n end,\n comm:send_local(Requestor, {web_debug_info_reply, KeyValueList}),\n State.\n\n%% @doc Gets the interval to trigger re-registering the node set in\n%% scalaris.cfg and converts it to seconds.\n-spec get_base_interval() -> Seconds::pos_integer().\nget_base_interval() ->\n config:read(reregister_interval) div 1000.\n\n%% @doc pid of the mgmt server (may be invalid)\n-spec mgmtServer() -> comm:mypid() | any().\nmgmtServer() ->\n config:read(mgmt_server).\n","avg_line_length":38.0211267606,"max_line_length":154,"alphanum_fraction":0.6282644934} +{"size":3858,"ext":"erl","lang":"Erlang","max_stars_count":24.0,"content":"%%\n%% Licensed to the Apache Software Foundation (ASF) under one\n%% or more contributor license agreements. See the NOTICE file\n%% distributed with this work for additional information\n%% regarding copyright ownership. The ASF licenses this file\n%% to you under the Apache License, Version 2.0 (the\n%% \"License\"); you may not use this file except in compliance\n%% with the License. You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing,\n%% software distributed under the License is distributed on an\n%% \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n%% KIND, either express or implied. See the License for the\n%% specific language governing permissions and limitations\n%% under the License.\n%%\n\n-module(thrift_framed_transport).\n\n-behaviour(thrift_transport).\n\n%% constructor\n-export([new\/1]).\n%% protocol callbacks\n-export([read\/2, read_exact\/2, write\/2, flush\/1, close\/1]).\n\n\n-record(t_framed, {\n wrapped,\n read_buffer,\n write_buffer\n}).\n\n-type state() :: #t_framed{}.\n\n\n-spec new(Transport::thrift_transport:t_transport()) ->\n thrift_transport:t_transport().\n\nnew(Wrapped) ->\n State = #t_framed{\n wrapped = Wrapped,\n read_buffer = [],\n write_buffer = []\n },\n thrift_transport:new(?MODULE, State).\n\n\n-include(\"thrift_transport_behaviour.hrl\").\n\n\nread(State = #t_framed{wrapped = Wrapped, read_buffer = Buffer}, Len)\nwhen is_integer(Len), Len >= 0 ->\n Binary = iolist_to_binary(Buffer),\n case Binary of\n <<>> when Len > 0 ->\n case next_frame(Wrapped) of\n {NewState, {ok, Frame}} ->\n NewBinary = iolist_to_binary([Binary, Frame]),\n Give = min(iolist_size(NewBinary), Len),\n {Result, Remaining} = split_binary(NewBinary, Give),\n {State#t_framed{wrapped = NewState, read_buffer = Remaining}, {ok, Result}};\n Error -> Error\n end;\n %% read of zero bytes\n <<>> -> {State, {ok, <<>>}};\n %% read buffer is nonempty\n _ ->\n Give = min(iolist_size(Binary), Len),\n {Result, Remaining} = split_binary(Binary, Give),\n {State#t_framed{read_buffer = Remaining}, {ok, Result}}\n end.\n\n\nread_exact(State = #t_framed{wrapped = Wrapped, read_buffer = Buffer}, Len)\nwhen is_integer(Len), Len >= 0 ->\n Binary = iolist_to_binary(Buffer),\n case iolist_size(Binary) of\n %% read buffer is larger than requested read size\n X when X >= Len ->\n {Result, Remaining} = split_binary(Binary, Len),\n {State#t_framed{read_buffer = Remaining}, {ok, Result}};\n %% read buffer is insufficient for requested read size\n _ ->\n case next_frame(Wrapped) of\n {NewState, {ok, Frame}} ->\n read_exact(\n State#t_framed{wrapped = NewState, read_buffer = [Buffer, Frame]},\n Len\n );\n {NewState, Error} ->\n {State#t_framed{wrapped = NewState}, Error}\n end\n end.\n\nnext_frame(Transport) ->\n case thrift_transport:read_exact(Transport, 4) of\n {NewState, {ok, <>}} ->\n thrift_transport:read_exact(NewState, FrameLength);\n Error -> Error\n end.\n\n\nwrite(State = #t_framed{write_buffer = Buffer}, Data) ->\n {State#t_framed{write_buffer = [Buffer, Data]}, ok}.\n\n\nflush(State = #t_framed{write_buffer = Buffer, wrapped = Wrapped}) ->\n case iolist_size(Buffer) of\n %% if write buffer is empty, do nothing\n 0 -> {State, ok};\n FrameLen ->\n Data = [<>, Buffer],\n {Written, Response} = thrift_transport:write(Wrapped, Data),\n {Flushed, ok} = thrift_transport:flush(Written),\n {State#t_framed{wrapped = Flushed, write_buffer = []}, Response}\n end.\n\n\nclose(State = #t_framed{wrapped = Wrapped}) ->\n {Closed, Result} = thrift_transport:close(Wrapped),\n {State#t_framed{wrapped = Closed}, Result}.\n\n","avg_line_length":30.619047619,"max_line_length":86,"alphanum_fraction":0.6632970451} +{"size":8169,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% A bunch of helpers to help to deal with errors in Elixir source code.\n%% This is not exposed in the Elixir language.\n%%\n%% Note that this is also called by the Erlang backend, so we also support\n%% the line number to be none (as it may happen in some erlang errors).\n-module(elixir_errors).\n-export([compile_error\/3, compile_error\/4, warning_prefix\/0,\n form_error\/4, form_warn\/4, parse_error\/4, erl_warn\/3, io_warn\/4]).\n-include(\"elixir.hrl\").\n\n%% Low-level warning, should be used only from Erlang passes.\n-spec erl_warn(non_neg_integer() | none, unicode:chardata(), unicode:chardata()) -> ok.\nerl_warn(none, File, Warning) ->\n erl_warn(0, File, Warning);\nerl_warn(Line, File, Warning) when is_integer(Line), is_binary(File) ->\n io_warn(Line, File, Warning, [Warning, \"\\n \", file_format(Line, File), $\\n]).\n\n%% Low-level warning, all other warnings are built on top of it.\n-spec io_warn(non_neg_integer(), unicode:chardata() | nil, unicode:chardata(), unicode:chardata()) -> ok.\nio_warn(Line, File, LogMessage, PrintMessage) when is_integer(Line), is_binary(File) or (File == nil) ->\n send_warning(Line, File, LogMessage),\n print_warning(PrintMessage).\n\n-spec warning_prefix() -> binary().\nwarning_prefix() ->\n case application:get_env(elixir, ansi_enabled) of\n {ok, true} -> <<\"\\e[33mwarning: \\e[0m\">>;\n _ -> <<\"warning: \">>\n end.\n\n%% General forms handling.\n\n-spec form_error(list(), binary() | #{file := binary(), _ => _}, module(), any()) -> no_return().\nform_error(Meta, #{file := File}, Module, Desc) ->\n compile_error(Meta, File, Module:format_error(Desc));\nform_error(Meta, File, Module, Desc) ->\n compile_error(Meta, File, Module:format_error(Desc)).\n\n-spec form_warn(list(), binary() | #{file := binary(), _ => _}, module(), any()) -> ok.\nform_warn(Meta, File, Module, Desc) when is_list(Meta), is_binary(File) ->\n do_form_warn(Meta, File, #{}, Module:format_error(Desc));\nform_warn(Meta, #{file := File} = E, Module, Desc) when is_list(Meta) ->\n do_form_warn(Meta, File, E, Module:format_error(Desc)).\n\ndo_form_warn(Meta, GivenFile, E, Warning) ->\n [{file, File}, {line, Line}] = meta_location(Meta, GivenFile),\n\n Location =\n case E of\n #{function := {Name, Arity}, module := Module} ->\n [file_format(Line, File), \": \", 'Elixir.Exception':format_mfa(Module, Name, Arity)];\n #{module := Module} when Module \/= nil ->\n [file_format(Line, File), \": \", elixir_aliases:inspect(Module)];\n #{} ->\n file_format(Line, File)\n end,\n\n io_warn(Line, File, Warning, [Warning, \"\\n \", Location, $\\n]).\n\n%% Compilation error.\n\n-spec compile_error(list(), binary(), binary() | unicode:charlist()) -> no_return().\n-spec compile_error(list(), binary(), string(), list()) -> no_return().\n\ncompile_error(Meta, File, Message) when is_binary(Message) ->\n MetaLocation = meta_location(Meta, File),\n raise('Elixir.CompileError', Message, MetaLocation);\ncompile_error(Meta, File, Message) when is_list(Message) ->\n MetaLocation = meta_location(Meta, File),\n raise('Elixir.CompileError', elixir_utils:characters_to_binary(Message), MetaLocation).\n\ncompile_error(Meta, File, Format, Args) when is_list(Format) ->\n compile_error(Meta, File, io_lib:format(Format, Args)).\n\n%% Tokenization parsing\/errors.\n\n-spec parse_error(elixir:keyword(), binary() | {binary(), binary()},\n binary(), binary()) -> no_return().\nparse_error(Location, File, Error, <<>>) ->\n Message = case Error of\n <<\"syntax error before: \">> -> <<\"syntax error: expression is incomplete\">>;\n _ -> Error\n end,\n raise(Location, File, 'Elixir.TokenMissingError', Message);\n\n%% Show a nicer message for end of line\nparse_error(Location, File, <<\"syntax error before: \">>, <<\"eol\">>) ->\n raise(Location, File, 'Elixir.SyntaxError',\n <<\"unexpectedly reached end of line. The current expression is invalid or incomplete\">>);\n\n\n%% Show a nicer message for keywords pt1 (Erlang keywords show up wrapped in single quotes)\nparse_error(Location, File, <<\"syntax error before: \">>, Keyword)\n when Keyword == <<\"'not'\">>;\n Keyword == <<\"'and'\">>;\n Keyword == <<\"'or'\">>;\n Keyword == <<\"'when'\">>;\n Keyword == <<\"'after'\">>;\n Keyword == <<\"'catch'\">>;\n Keyword == <<\"'end'\">> ->\n raise_reserved(Location, File, binary_part(Keyword, 1, byte_size(Keyword) - 2));\n\n%% Show a nicer message for keywords pt2 (Elixir keywords show up as is)\nparse_error(Location, File, <<\"syntax error before: \">>, Keyword)\n when Keyword == <<\"fn\">>;\n Keyword == <<\"else\">>;\n Keyword == <<\"rescue\">>;\n Keyword == <<\"true\">>;\n Keyword == <<\"false\">>;\n Keyword == <<\"nil\">>;\n Keyword == <<\"in\">> ->\n raise_reserved(Location, File, Keyword);\n\n%% Produce a human-readable message for errors before a sigil\nparse_error(Location, File, <<\"syntax error before: \">>, <<\"{sigil,\", _Rest\/binary>> = Full) ->\n {sigil, _, Sigil, [Content | _], _, _, _} = parse_erl_term(Full),\n Content2 = case is_binary(Content) of\n true -> Content;\n false -> <<>>\n end,\n Message = <<\"syntax error before: sigil \\~\", Sigil, \" starting with content '\", Content2\/binary, \"'\">>,\n raise(Location, File, 'Elixir.SyntaxError', Message);\n\n%% Binaries (and interpolation) are wrapped in [<<...>>]\nparse_error(Location, File, Error, <<\"[\", _\/binary>> = Full) when is_binary(Error) ->\n Term = case parse_erl_term(Full) of\n [H | _] when is_binary(H) -> <<$\", H\/binary, $\">>;\n _ -> <<$\">>\n end,\n raise(Location, File, 'Elixir.SyntaxError', <>);\n\n%% Given a string prefix and suffix to insert the token inside the error message rather than append it\nparse_error(Location, File, {ErrorPrefix, ErrorSuffix}, Token) when is_binary(ErrorPrefix), is_binary(ErrorSuffix), is_binary(Token) ->\n Message = <>,\n raise(Location, File, 'Elixir.SyntaxError', Message);\n\n%% Misplaced char tokens (for example, {char, _, 97}) are translated by Erlang into\n%% the char literal (i.e., the token in the previous example becomes $a),\n%% because {char, _, _} is a valid Erlang token for an Erlang char literal. We\n%% want to represent that token as ?a in the error, according to the Elixir\n%% syntax.\nparse_error(Location, File, <<\"syntax error before: \">>, <<$$, Char\/binary>>) ->\n Message = <<\"syntax error before: ?\", Char\/binary>>,\n raise(Location, File, 'Elixir.SyntaxError', Message);\n\n%% Everything else is fine as is\nparse_error(Location, File, Error, Token) when is_binary(Error), is_binary(Token) ->\n Message = <>,\n raise(Location, File, 'Elixir.SyntaxError', Message).\n\nparse_erl_term(Term) ->\n {ok, Tokens, _} = erl_scan:string(binary_to_list(Term)),\n {ok, Parsed} = erl_parse:parse_term(Tokens ++ [{dot, 1}]),\n Parsed.\n\nraise_reserved(Location, File, Keyword) ->\n raise(Location, File, 'Elixir.SyntaxError',\n <<\"syntax error before: \", Keyword\/binary, \". \\\"\", Keyword\/binary, \"\\\" is a \"\n \"reserved word in Elixir and therefore its usage is limited. For instance, \"\n \"it can't be used as a variable or be defined nor invoked as a regular function\">>).\n\n%% Helpers\n\nprint_warning(Message) ->\n io:put_chars(standard_error, [warning_prefix(), Message, $\\n]),\n ok.\n\nsend_warning(Line, File, Message) ->\n case get(elixir_compiler_pid) of\n undefined -> ok;\n CompilerPid -> CompilerPid ! {warning, File, Line, Message}\n end,\n ok.\n\nfile_format(0, File) ->\n io_lib:format(\"~ts\", [elixir_utils:relative_to_cwd(File)]);\n\nfile_format(Line, File) ->\n io_lib:format(\"~ts:~w\", [elixir_utils:relative_to_cwd(File), Line]).\n\nmeta_location(Meta, File) ->\n case elixir_utils:meta_keep(Meta) of\n {F, L} -> [{file, F}, {line, L}];\n nil -> [{file, File}, {line, ?line(Meta)}]\n end.\n\nraise(Location, File, Kind, Message) when is_binary(File) ->\n raise(Kind, Message, [{file, File} | Location]).\n\nraise(Kind, Message, Opts) when is_binary(Message) ->\n Stacktrace = try throw(ok) catch _:_:Stack -> Stack end,\n Exception = Kind:exception([{description, Message} | Opts]),\n erlang:raise(error, Exception, tl(Stacktrace)).","avg_line_length":42.3264248705,"max_line_length":135,"alphanum_fraction":0.6600563104} +{"size":1919,"ext":"erl","lang":"Erlang","max_stars_count":79.0,"content":"%% Generated with 'testgen v0.2.0'\n%% Revision 1 of the exercises generator was used\n%% https:\/\/github.com\/exercism\/problem-specifications\/raw\/42dd0cea20498fd544b152c4e2c0a419bb7e266a\/exercises\/pangram\/canonical-data.json\n%% This file is automatically generated from the exercises canonical data.\n\n-module(pangram_tests).\n\n-include_lib(\"erl_exercism\/include\/exercism.hrl\").\n-include_lib(\"eunit\/include\/eunit.hrl\").\n\n\n\n\n'1_empty_sentence_test_'() ->\n {\"empty sentence\", ?_assertNot(pangram:is_pangram([]))}.\n\n'2_perfect_lower_case_test_'() ->\n {\"perfect lower case\",\n ?_assert(pangram:is_pangram(\"abcdefghijklmnopqrstuvwxyz\"))}.\n\n'3_only_lower_case_test_'() ->\n {\"only lower case\",\n ?_assert(pangram:is_pangram(\"the quick brown fox jumps over the lazy \"\n\t\t\t\t \"dog\"))}.\n\n'4_missing_the_letter_x_test_'() ->\n {\"missing the letter 'x'\",\n ?_assertNot(pangram:is_pangram(\"a quick movement of the enemy will jeopardize \"\n\t\t\t\t \"five gunboats\"))}.\n\n'5_missing_the_letter_h_test_'() ->\n {\"missing the letter 'h'\",\n ?_assertNot(pangram:is_pangram(\"five boxing wizards jump quickly at it\"))}.\n\n'6_with_underscores_test_'() ->\n {\"with underscores\",\n ?_assert(pangram:is_pangram(\"the_quick_brown_fox_jumps_over_the_lazy_dog\"))}.\n\n'7_with_numbers_test_'() ->\n {\"with numbers\",\n ?_assert(pangram:is_pangram(\"the 1 quick brown fox jumps over the \"\n\t\t\t\t \"2 lazy dogs\"))}.\n\n'8_missing_letters_replaced_by_numbers_test_'() ->\n {\"missing letters replaced by numbers\",\n ?_assertNot(pangram:is_pangram(\"7h3 qu1ck brown fox jumps ov3r 7h3 lazy \"\n\t\t\t\t \"dog\"))}.\n\n'9_mixed_case_and_punctuation_test_'() ->\n {\"mixed case and punctuation\",\n ?_assert(pangram:is_pangram(\"\\\"Five quacking Zephyrs jolt my wax \"\n\t\t\t\t \"bed.\\\"\"))}.\n\n'10_case_insensitive_test_'() ->\n {\"case insensitive\",\n ?_assertNot(pangram:is_pangram(\"the quick brown fox jumps over with \"\n\t\t\t\t \"lazy FX\"))}.\n","avg_line_length":33.0862068966,"max_line_length":136,"alphanum_fraction":0.7076602397} +{"size":7451,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(shackle_tcp_server).\n-include(\"shackle_internal.hrl\").\n\n-compile(inline).\n-compile({inline_size, 512}).\n\n-export([\n start_link\/4,\n init\/3,\n handle_msg\/2,\n terminate\/2\n]).\n\n-record(state, {\n client :: client(),\n ip :: inet:ip_address() | inet:hostname(),\n name :: server_name(),\n parent :: pid(),\n pool_name :: pool_name(),\n port :: inet:port_number(),\n reconnect_state :: undefined | reconnect_state(),\n socket :: undefined | inet:socket(),\n socket_options :: [gen_tcp:connect_option()],\n timer_ref :: undefined | reference()\n}).\n\n-type init_opts() :: {pool_name(), client(), client_options()}.\n-type state() :: #state {}.\n\n%% public\n-spec start_link(server_name(), pool_name(), client(), client_options()) ->\n {ok, pid()}.\n\nstart_link(Name, PoolName, Client, ClientOptions) ->\n Args = {PoolName, Client, ClientOptions},\n metal:start_link(?MODULE, Name, Args).\n\n-spec init(server_name(), pid(), init_opts()) ->\n no_return().\n\ninit(Name, Parent, Opts) ->\n {PoolName, Client, ClientOptions} = Opts,\n self() ! ?MSG_CONNECT,\n ok = shackle_backlog:new(Name),\n\n Ip = ?LOOKUP(ip, ClientOptions, ?DEFAULT_IP),\n Port = ?LOOKUP(port, ClientOptions),\n ReconnectState = shackle_utils:reconnect_state(ClientOptions),\n SocketOptions = ?LOOKUP(socket_options, ClientOptions,\n ?DEFAULT_SOCKET_OPTS),\n\n {ok, {#state {\n client = Client,\n ip = Ip,\n name = Name,\n parent = Parent,\n pool_name = PoolName,\n port = Port,\n reconnect_state = ReconnectState,\n socket_options = SocketOptions\n }, undefined}}.\n\n-spec handle_msg(term(), {state(), client_state()}) ->\n {ok, term()}.\n\nhandle_msg(#cast {} = Cast, {#state {\n socket = undefined,\n name = Name\n } = State, ClientState}) ->\n\n shackle_utils:reply(Name, {error, no_socket}, Cast),\n {ok, {State, ClientState}};\nhandle_msg(#cast {\n request = Request,\n timeout = Timeout\n } = Cast, {#state {\n client = Client,\n name = Name,\n pool_name = PoolName,\n socket = Socket\n } = State, ClientState}) ->\n\n {ok, ExtRequestId, Data, ClientState2} =\n Client:handle_request(Request, ClientState),\n\n case gen_tcp:send(Socket, Data) of\n ok ->\n Msg = {timeout, ExtRequestId},\n TimerRef = erlang:send_after(Timeout, self(), Msg),\n shackle_queue:add(ExtRequestId, Cast, TimerRef),\n {ok, {State, ClientState2}};\n {error, Reason} ->\n shackle_utils:warning_msg(PoolName, \"send error: ~p\", [Reason]),\n gen_tcp:close(Socket),\n shackle_utils:reply(Name, {error, socket_closed}, Cast),\n close(State, ClientState2)\n end;\nhandle_msg({tcp, Socket, Data}, {#state {\n client = Client,\n name = Name,\n pool_name = PoolName,\n socket = Socket\n } = State, ClientState}) ->\n\n case Client:handle_data(Data, ClientState) of\n {ok, Replies, ClientState2} ->\n shackle_utils:process_responses(Replies, Name),\n {ok, {State, ClientState2}};\n {error, Reason, ClientState2} ->\n shackle_utils:warning_msg(PoolName,\n \"handle_data error: ~p\", [Reason]),\n gen_tcp:close(Socket),\n close(State, ClientState2)\n end;\nhandle_msg({timeout, ExtRequestId}, {#state {\n name = Name\n } = State, ClientState}) ->\n\n case shackle_queue:remove(Name, ExtRequestId) of\n {ok, Cast, _TimerRef} ->\n shackle_utils:reply(Name, {error, timeout}, Cast);\n {error, not_found} ->\n ok\n end,\n {ok, {State, ClientState}};\nhandle_msg({tcp_closed, Socket}, {#state {\n socket = Socket,\n pool_name = PoolName\n } = State, ClientState}) ->\n\n shackle_utils:warning_msg(PoolName, \"connection closed\", []),\n close(State, ClientState);\nhandle_msg({tcp_error, Socket, Reason}, {#state {\n socket = Socket,\n pool_name = PoolName\n } = State, ClientState}) ->\n\n shackle_utils:warning_msg(PoolName, \"connection error: ~p\", [Reason]),\n gen_tcp:close(Socket),\n close(State, ClientState);\nhandle_msg(?MSG_CONNECT, {#state {\n client = Client,\n ip = Ip,\n pool_name = PoolName,\n port = Port,\n reconnect_state = ReconnectState,\n socket_options = SocketOptions\n } = State, ClientState}) ->\n\n case connect(PoolName, Ip, Port, SocketOptions) of\n {ok, Socket} ->\n case shackle_utils:client_setup(Client, PoolName, Socket) of\n {ok, ClientState2} ->\n ReconnectState2 =\n shackle_utils:reconnect_state_reset(ReconnectState),\n\n {ok, {State#state {\n reconnect_state = ReconnectState2,\n socket = Socket\n }, ClientState2}};\n {error, _Reason, ClientState2} ->\n gen_tcp:close(Socket),\n reconnect(State, ClientState2)\n end;\n {error, _Reason} ->\n reconnect(State, ClientState)\n end;\nhandle_msg(Msg, {#state {\n pool_name = PoolName\n } = State, ClientState}) ->\n\n shackle_utils:warning_msg(PoolName, \"unknown msg: ~p\", [Msg]),\n {ok, {State, ClientState}}.\n\n-spec terminate(term(), term()) ->\n ok.\n\nterminate(_Reason, {#state {\n client = Client,\n name = Name,\n timer_ref = TimerRef\n }, ClientState}) ->\n\n shackle_utils:cancel_timer(TimerRef),\n ok = Client:terminate(ClientState),\n shackle_utils:reply_all(Name, {error, shutdown}),\n shackle_backlog:delete(Name),\n ok.\n\n%% private\nclose(#state {name = Name} = State, ClientState) ->\n shackle_utils:reply_all(Name, {error, socket_closed}),\n reconnect(State, ClientState).\n\nconnect(PoolName, Ip, Port, SocketOptions) ->\n case inet:getaddrs(Ip, inet) of\n {ok, Addrs} ->\n Ip2 = shackle_utils:random_element(Addrs),\n case gen_tcp:connect(Ip2, Port, SocketOptions,\n ?DEFAULT_CONNECT_TIMEOUT) of\n {ok, Socket} ->\n {ok, Socket};\n {error, Reason} ->\n shackle_utils:warning_msg(PoolName,\n \"connect error: ~p\", [Reason]),\n {error, Reason}\n end;\n {error, Reason} ->\n shackle_utils:warning_msg(PoolName,\n \"getaddrs error: ~p\", [Reason]),\n {error, Reason}\n end.\n\nreconnect(State, undefined) ->\n reconnect_timer(State, undefined);\nreconnect(#state {\n client = Client\n } = State, ClientState) ->\n\n ok = Client:terminate(ClientState),\n reconnect_timer(State, ClientState).\n\nreconnect_timer(#state {\n reconnect_state = undefined\n } = State, ClientState) ->\n\n {ok, {State#state {\n socket = undefined\n }, ClientState}};\nreconnect_timer(#state {\n reconnect_state = ReconnectState\n } = State, ClientState) ->\n\n ReconnectState2 = shackle_backoff:timeout(ReconnectState),\n #reconnect_state {current = Current} = ReconnectState2,\n TimerRef = erlang:send_after(Current, self(), ?MSG_CONNECT),\n\n {ok, {State#state {\n reconnect_state = ReconnectState2,\n socket = undefined,\n timer_ref = TimerRef\n }, ClientState}}.\n","avg_line_length":30.6625514403,"max_line_length":76,"alphanum_fraction":0.5795195276} +{"size":240,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(rebar3_deps).\n-export([start\/0]).\n-export([test\/0]).\n\nstart()->\n ok = application:start(xmerl),\n ok = application:start(jiffy),\n ok = application:start(rebar3_deps).\n\ntest() ->\n Result = <<\"[1]\">>,\n Result = jiffy:encode([1]).\n","avg_line_length":18.4615384615,"max_line_length":38,"alphanum_fraction":0.6208333333} +{"size":527,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%% @doc Links repository\n-module(erlorg_links_repo).\n-author('juan@inaka.net').\n\n-export([create\/5]).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% API\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n-spec create(binary(), binary(), binary(), integer(), integer()) ->\n erlorg_links:link().\ncreate(Title, Url, Description, Order, CategoryId) ->\n Link = erlorg_links:new(Title, Url, Description, Order, CategoryId),\n sumo:persist(erlorg_links, Link).\n","avg_line_length":32.9375,"max_line_length":80,"alphanum_fraction":0.4800759013} +{"size":37172,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2017-2020. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n%%\n\n-module(engine_SUITE).\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n\n%% Note: This directive should only be used in test suites.\n-compile(export_all).\n\n%%--------------------------------------------------------------------\n%% Common Test interface functions -----------------------------------\n%%--------------------------------------------------------------------\nsuite() ->\n [{ct_hooks,[ts_install_cth]},\n {timetrap,{seconds, 10}}\n ].\n\nall() ->\n [\n get_all_possible_methods,\n engine_load_all_methods,\n engine_load_some_methods,\n multiple_engine_load,\n engine_list,\n get_id_and_name,\n engine_by_id,\n bad_arguments,\n unknown_engine,\n pre_command_fail_bad_value,\n pre_command_fail_bad_key,\n failed_engine_init,\n ctrl_cmd_string,\n ctrl_cmd_string_optional,\n ensure_load,\n {group, engine_stored_key},\n {group, engine_fakes_rsa}\n ].\n\ngroups() ->\n [{engine_stored_key, [],\n [\n sign_verify_rsa,\n sign_verify_dsa,\n sign_verify_ecdsa,\n sign_verify_rsa_pwd,\n sign_verify_rsa_pwd_bad_pwd,\n priv_encrypt_pub_decrypt_rsa,\n priv_encrypt_pub_decrypt_rsa_pwd,\n pub_encrypt_priv_decrypt_rsa,\n pub_encrypt_priv_decrypt_rsa_pwd,\n get_pub_from_priv_key_rsa,\n get_pub_from_priv_key_rsa_pwd,\n get_pub_from_priv_key_rsa_pwd_no_pwd,\n get_pub_from_priv_key_rsa_pwd_bad_pwd,\n get_pub_from_priv_key_dsa,\n get_pub_from_priv_key_ecdsa\n ]},\n {engine_fakes_rsa, [], [sign_verify_rsa_fake\n ]}\n ].\n\n\ninit_per_suite(Config) ->\n try {os:type(), crypto:info_lib()} of\n {_, [{_,_, <<\"OpenSSL 1.0.1s-freebsd 1 Mar 2016\">>}]} ->\n {skip, \"Problem with engine on OpenSSL 1.0.1s-freebsd\"};\n\n {{unix,darwin}, _} ->\n {skip, \"Engine unsupported on Darwin\"};\n \n {{win32,_}, _} ->\n {skip, \"Engine unsupported on Windows\"};\n \n {OS, Res} ->\n ct:log(\"crypto:info_lib() -> ~p\\nos:type() -> ~p\", [Res,OS]),\n try crypto:start() of\n ok ->\n Config;\n {error,{already_started,crypto}} ->\n Config\n catch _:_ ->\n {skip, \"Crypto did not start\"}\n end\n catch _:_ ->\n\t {skip, \"Crypto not loaded\"}\n end.\n\nend_per_suite(_Config) ->\n ok.\n\n%%--------------------------------------------------------------------\ninit_per_group(engine_stored_key, Config) ->\n group_load_engine(Config, [engine_method_rsa]);\ninit_per_group(engine_fakes_rsa, Config) ->\n case crypto:info_lib() of\n [{<<\"OpenSSL\">>,LibVer,_}] when is_integer(LibVer), LibVer >= 16#10100000 ->\n group_load_engine(Config, []);\n _ ->\n {skip, \"Too low OpenSSL cryptolib version\"}\n end;\ninit_per_group(_Group, Config0) ->\n Config0.\n\n\ngroup_load_engine(Config, ExcludeMthds) ->\n case load_storage_engine(Config, ExcludeMthds) of\n {ok, E} ->\n KeyDir = key_dir(Config),\n [{storage_engine,E}, {storage_dir,KeyDir} | Config];\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {error, notsup} ->\n {skip, \"Engine not supported on this SSL version\"};\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"};\n Other ->\n ct:log(\"Engine load failed: ~p\",[Other]),\n {fail, \"Engine load failed\"}\n end.\n\n\n\n\n\nend_per_group(_, Config) ->\n case proplists:get_value(storage_engine, Config) of\n undefined ->\n ok;\n E ->\n ok = crypto:engine_unload(E)\n end.\n\n%%--------------------------------------------------------------------\ninit_per_testcase(Case, Config) ->\n case string:tokens(atom_to_list(Case),\"_\") of\n [\"sign\",\"verify\",Type|_] ->\n skip_if_unsup(list_to_atom(Type), Config);\n\n [\"priv\",\"encrypt\",\"pub\",\"decrypt\",Type|_] ->\n skip_if_unsup(list_to_atom(Type), Config);\n\n [\"get\",\"pub\",\"from\",\"priv\",\"key\",Type|_] ->\n skip_if_unsup(list_to_atom(Type), Config);\n\n _ ->\n Config\n end.\n\nend_per_testcase(_Case, _Config) ->\n ok.\n\n%%-------------------------------------------------------------------------\n%% Test cases starts here.\n%%-------------------------------------------------------------------------\nget_all_possible_methods() ->\n [{doc, \"Just fetch all possible engine methods supported.\"}].\n\nget_all_possible_methods(Config) when is_list(Config) ->\n try\n List = crypto:engine_get_all_methods(),\n true = erlang:is_list(List),\n ct:log(\"crypto:engine_get_all_methods() -> ~p\\n\", [List]),\n ok\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\nengine_load_all_methods()->\n [{doc, \"Use a dummy md5 engine that does not implement md5\"\n \"but rather returns a static binary to test that crypto:engine_load \"\n \"functions works.\"}].\n\nengine_load_all_methods(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n Md5Hash1 = <<106,30,3,246,166,222,229,158,244,217,241,179,50,232,107,109>>,\n Md5Hash1 = crypto:hash(md5, \"Don't panic\"),\n Md5Hash2 = <<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>>,\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_still_original_engine);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:engine_unload(E),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash2 ->\n ct:fail(fail_to_unload_still_test_engine);\n Md5Hash1 ->\n ok;\n _ ->\n ct:fail(fail_to_unload_engine)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\nengine_load_some_methods()->\n [{doc, \"Use a dummy md5 engine that does not implement md5\"\n \"but rather returns a static binary to test that crypto:engine_load \"\n \"functions works.\"}].\n\nengine_load_some_methods(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n Md5Hash1 = <<106,30,3,246,166,222,229,158,244,217,241,179,50,232,107,109>>,\n Md5Hash1 = crypto:hash(md5, \"Don't panic\"),\n Md5Hash2 = <<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>>,\n EngineMethods = crypto:engine_get_all_methods() --\n [engine_method_dh, engine_method_rand,\n engine_method_ciphers, engine_method_store,\n engine_method_pkey_meths, engine_method_pkey_asn1_meths],\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n [],\n EngineMethods) of\n {ok, E} ->\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_engine_still_original);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:engine_unload(E),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash2 ->\n ct:fail(fail_to_unload_still_test_engine);\n Md5Hash1 ->\n ok;\n _ ->\n ct:fail(fail_to_unload_engine)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\nmultiple_engine_load()->\n [{doc, \"Use a dummy md5 engine that does not implement md5\"\n \"but rather returns a static binary to test that crypto:engine_load \"\n \"functions works when called multiple times.\"}].\n\nmultiple_engine_load(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n Md5Hash1 = <<106,30,3,246,166,222,229,158,244,217,241,179,50,232,107,109>>,\n Md5Hash1 = crypto:hash(md5, \"Don't panic\"),\n Md5Hash2 = <<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>>,\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n {ok, E1} = crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []),\n {ok, E2} = crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_still_original_engine);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:engine_unload(E2),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_still_original_engine);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:engine_unload(E),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_still_original_engine);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:engine_unload(E1),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash2 ->\n ct:fail(fail_to_unload_still_test_engine);\n Md5Hash1 ->\n ok;\n _ ->\n ct:fail(fail_to_unload_engine)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\nengine_list()->\n [{doc, \"Test add and remove engine ID to the SSL internal engine list.\"}].\n\nengine_list(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n EngineList0 = crypto:engine_list(),\n false = lists:member(<<\"MD5\">>, EngineList0),\n ok = crypto:engine_add(E),\n [<<\"MD5\">>] = lists:subtract(crypto:engine_list(), EngineList0),\n ok = crypto:engine_remove(E),\n EngineList0 = crypto:engine_list(),\n ok = crypto:engine_unload(E);\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\nget_id_and_name()->\n [{doc, \"Test fetching id and name from an engine.\"}].\n\nget_id_and_name(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n <<\"MD5\">> = crypto:engine_get_id(E),\n <<\"MD5 test engine\">> = crypto:engine_get_name(E),\n ok = crypto:engine_unload(E);\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\nengine_by_id()->\n [{doc, \"Test fetching a new reference the the engine when the\"\n \"engine id is added to the SSL engine list.\"}].\n\nengine_by_id(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n case crypto:engine_by_id(<<\"MD5\">>) of\n {error,bad_engine_id} ->\n ok;\n {ok, _} ->\n ct:fail(fail_engine_found)\n end,\n ok = crypto:engine_add(E),\n {ok, _E1} = crypto:engine_by_id(<<\"MD5\">>),\n ok = crypto:engine_remove(E),\n ok = crypto:engine_unload(E);\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\n%%-------------------------------------------------------------------------\n%% Error cases\nbad_arguments()->\n [{doc, \"Test different arguments in bad format.\"}].\n\nbad_arguments(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n try\n crypto:engine_load(fail_engine, [], [])\n of\n X1 ->\n ct:fail(\"1 Got ~p\",[X1])\n catch\n error:badarg ->\n ok\n end,\n try\n crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n 1,\n {<<\"ID\">>, <<\"MD5\">>},\n <<\"LOAD\">>],\n [])\n of\n {error,bad_engine_id} ->\n throw(dynamic_engine_unsupported);\n X2 ->\n ct:fail(\"2 Got ~p\",[X2])\n catch\n error:badarg ->\n ok\n end,\n try\n crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n {'ID', <<\"MD5\">>},\n <<\"LOAD\">>],\n [])\n of\n {error,bad_engine_id} -> % should have happend in the previous try...catch end!\n throw(dynamic_engine_unsupported);\n X3 ->\n ct:fail(\"3 Got ~p\",[X3])\n catch\n error:badarg ->\n ok\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"};\n throw:dynamic_engine_unsupported ->\n {skip, \"Dynamic Engine not supported\"}\n end\n end.\n\nunknown_engine() ->\n [{doc, \"Try to load a non existent engine.\"}].\n\nunknown_engine(Config) when is_list(Config) ->\n try\n {error, bad_engine_id} = crypto:engine_load(<<\"fail_engine\">>, [], []),\n ok\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\npre_command_fail_bad_value() ->\n [{doc, \"Test pre command due to bad value\"}].\n\npre_command_fail_bad_value(Config) when is_list(Config) ->\n DataDir = unicode:characters_to_binary(code:priv_dir(crypto)),\n try\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>,\n <>\/binary >>},\n {<<\"ID\">>, <<\"MD5\">>},\n <<\"LOAD\">>],\n []) of\n {error, ctrl_cmd_failed} ->\n ok;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\npre_command_fail_bad_key() ->\n [{doc, \"Test pre command due to bad key\"}].\n\npre_command_fail_bad_key(Config) when is_list(Config) ->\n try\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_WRONG_PATH\">>, Engine},\n {<<\"ID\">>, <<\"MD5\">>},\n <<\"LOAD\">>],\n []) of\n {error, ctrl_cmd_failed} ->\n ok;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\nfailed_engine_init()->\n [{doc, \"Test failing engine init due to missed pre command\"}].\n\nfailed_engine_init(Config) when is_list(Config) ->\n try\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n {<<\"ID\">>, <<\"MD5\">>}],\n []) of\n {error, engine_init_failed} ->\n ok;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\n\n%%-------------------------------------------------------------------------\n%% Test the optional flag in ctrl comands\nctrl_cmd_string()->\n [{doc, \"Test that a not known optional ctrl comand do not fail\"}].\nctrl_cmd_string(Config) when is_list(Config) ->\n try\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n {<<\"ID\">>, <<\"MD5\">>},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n case crypto:engine_ctrl_cmd_string(E, <<\"TEST\">>, <<\"17\">>) of\n ok ->\n ok = crypto:engine_unload(E),\n ct:fail(fail_ctrl_cmd_should_fail);\n {error,ctrl_cmd_failed} ->\n ok = crypto:engine_unload(E)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\nctrl_cmd_string_optional()->\n [{doc, \"Test that a not known optional ctrl comand do not fail\"}].\nctrl_cmd_string_optional(Config) when is_list(Config) ->\n try\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n case crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n {<<\"ID\">>, <<\"MD5\">>},\n <<\"LOAD\">>],\n []) of\n {ok, E} ->\n case crypto:engine_ctrl_cmd_string(E, <<\"TEST\">>, <<\"17\">>, true) of\n ok ->\n ok = crypto:engine_unload(E);\n Err ->\n ct:log(\"Error: ~p\",[Err]),\n ok = crypto:engine_unload(E),\n ct:fail(fail_ctrl_cmd_string)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end.\n\nensure_load()->\n [{doc, \"Test the special ensure load function.\"}].\n\nensure_load(Config) when is_list(Config) ->\n case crypto:get_test_engine() of\n {error, notexist} ->\n {skip, \"OTP Test engine not found\"};\n {ok, Engine} ->\n try\n Md5Hash1 = <<106,30,3,246,166,222,229,158,244,217,241,179,50,232,107,109>>,\n Md5Hash1 = crypto:hash(md5, \"Don't panic\"),\n Md5Hash2 = <<0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15>>,\n case crypto:ensure_engine_loaded(<<\"MD5\">>, Engine) of\n {ok, E} ->\n {ok, _E1} = crypto:ensure_engine_loaded(<<\"MD5\">>, Engine),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash1 ->\n ct:fail(fail_to_load_still_original_engine);\n Md5Hash2 ->\n ok;\n _ ->\n ct:fail(fail_to_load_engine)\n end,\n ok = crypto:ensure_engine_unloaded(E),\n case crypto:hash(md5, \"Don't panic\") of\n Md5Hash2 ->\n ct:fail(fail_to_unload_still_test_engine);\n Md5Hash1 ->\n ok;\n _ ->\n ct:fail(fail_to_unload_engine)\n end;\n {error, bad_engine_id} ->\n {skip, \"Dynamic Engine not supported\"}\n end\n catch\n error:notsup ->\n {skip, \"Engine not supported on this SSL version\"}\n end\n end.\n\n%%%----------------------------------------------------------------\n%%% Pub\/priv key storage tests. Those are for testing the crypto.erl\n%%% support for using priv\/pub keys stored in an engine.\n\nsign_verify_rsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key.pem\")},\n sign_verify(rsa, sha, Priv, Pub).\n\nsign_verify_rsa_fake(Config) ->\n %% Use fake engine rsa implementation\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key.pem\")},\n sign_verify_fake(rsa, sha256, Priv, Pub).\n\nsign_verify_dsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"dsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"dsa_public_key.pem\")},\n sign_verify(dss, sha, Priv, Pub).\n\nsign_verify_ecdsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"ecdsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"ecdsa_public_key.pem\")},\n sign_verify(ecdsa, sha, Priv, Pub).\n\nsign_verify_rsa_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"password\"},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key_pwd.pem\")},\n sign_verify(rsa, sha, Priv, Pub).\n\nsign_verify_rsa_pwd_bad_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"Bad password\"},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key_pwd.pem\")},\n try sign_verify(rsa, sha, Priv, Pub) of\n _ -> {fail, \"PWD prot pubkey sign succeded with no pwd!\"}\n catch\n error:badarg -> ok\n end.\n\npriv_encrypt_pub_decrypt_rsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key.pem\")},\n priv_enc_pub_dec(rsa, Priv, Pub, rsa_pkcs1_padding).\n\npriv_encrypt_pub_decrypt_rsa_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"password\"},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key_pwd.pem\")},\n priv_enc_pub_dec(rsa, Priv, Pub, rsa_pkcs1_padding).\n\npub_encrypt_priv_decrypt_rsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key.pem\")},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key.pem\")},\n pub_enc_priv_dec(rsa, Pub, Priv, rsa_pkcs1_padding).\n\npub_encrypt_priv_decrypt_rsa_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"password\"},\n Pub = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_public_key_pwd.pem\")},\n pub_enc_priv_dec(rsa, Pub, Priv, rsa_pkcs1_padding).\n\nget_pub_from_priv_key_rsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key.pem\")},\n case crypto:privkey_to_pubkey(rsa, Priv) of\n {error, not_found} ->\n {fail, \"Key not found\"};\n {error, notsup} ->\n {skip, \"RSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"rsa Pub = ~p\",[Pub]),\n sign_verify(rsa, sha, Priv, Pub)\n end.\n\nget_pub_from_priv_key_rsa_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"password\"},\n case crypto:privkey_to_pubkey(rsa, Priv) of\n {error, not_found} ->\n {fail, \"Key not found\"};\n {error, notsup} ->\n {skip, \"RSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"rsa Pub = ~p\",[Pub]),\n sign_verify(rsa, sha, Priv, Pub)\n end.\n\nget_pub_from_priv_key_rsa_pwd_no_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\")},\n case crypto:privkey_to_pubkey(rsa, Priv) of\n {error, not_found} ->\n ok;\n {error, notsup} ->\n {skip, \"RSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"rsa Pub = ~p\",[Pub]),\n {fail, \"PWD prot pubkey fetch succeded although no pwd!\"}\n end.\n\nget_pub_from_priv_key_rsa_pwd_bad_pwd(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"rsa_private_key_pwd.pem\"),\n password => \"Bad password\"},\n case crypto:privkey_to_pubkey(rsa, Priv) of\n {error, not_found} ->\n ok;\n {error, notsup} ->\n {skip, \"RSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"rsa Pub = ~p\",[Pub]),\n {fail, \"PWD prot pubkey fetch succeded with bad pwd!\"}\n end.\n\nget_pub_from_priv_key_dsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"dsa_private_key.pem\")},\n case crypto:privkey_to_pubkey(dss, Priv) of\n {error, not_found} ->\n {fail, \"Key not found\"};\n {error, notsup} ->\n {skip, \"DSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"dsa Pub = ~p\",[Pub]),\n sign_verify(dss, sha, Priv, Pub)\n end.\n\nget_pub_from_priv_key_ecdsa(Config) ->\n Priv = #{engine => engine_ref(Config),\n key_id => key_id(Config, \"ecdsa_private_key.pem\")},\n case crypto:privkey_to_pubkey(ecdsa, Priv) of\n {error, not_found} ->\n {fail, \"Key not found\"};\n {error, notsup} ->\n {skip, \"ECDSA not supported\"};\n {error, Error} ->\n {fail, {wrong_error,Error}};\n Pub ->\n ct:log(\"ecdsa Pub = ~p\",[Pub]),\n sign_verify(ecdsa, sha, Priv, Pub)\n end.\n\n%%%================================================================\n%%% Help for engine_stored_pub_priv_keys* test cases\n%%%\nskip_if_unsup(Type, Config) ->\n case pkey_supported(Type) of\n false ->\n {skip, \"Unsupported in this cryptolib\"};\n true ->\n Config\n end.\n\n\npkey_supported(Type) ->\n lists:member(Type, proplists:get_value(public_keys, crypto:supports(), [])).\n\n\nload_storage_engine(Config) ->\n load_storage_engine(Config, []).\n\nload_storage_engine(_Config, ExcludeMthds) ->\n case crypto:get_test_engine() of\n {ok, Engine} ->\n try crypto:engine_load(<<\"dynamic\">>,\n [{<<\"SO_PATH\">>, Engine},\n <<\"LOAD\">>],\n [],\n crypto:engine_get_all_methods() -- ExcludeMthds\n )\n catch\n error:notsup ->\n {error, notsup}\n end;\n\n {error, Error} ->\n {error, Error}\n end.\n\n\nkey_dir(Config) ->\n DataDir = unicode:characters_to_binary(proplists:get_value(data_dir, Config)),\n filename:join(DataDir, \"pkcs8\").\n\n\nengine_ref(Config) ->\n proplists:get_value(storage_engine, Config).\n\nkey_id(Config, File) ->\n filename:join(proplists:get_value(storage_dir,Config), File).\n\npubkey_alg_supported(Alg) ->\n lists:member(Alg,\n proplists:get_value(public_keys, crypto:supports())).\n\n\npub_enc_priv_dec(Alg, KeyEnc, KeyDec, Padding) ->\n case pubkey_alg_supported(Alg) of\n true ->\n PlainText = <<\"Hej p\u00e5 dig\">>,\n CryptoText = crypto:public_encrypt(Alg, PlainText, KeyEnc, Padding),\n case crypto:private_decrypt(Alg, CryptoText, KeyDec, Padding) of\n PlainText -> ok;\n _ -> {fail, \"Encrypt-decrypt error\"}\n end;\n false ->\n {skip, lists:concat([Alg,\" is not supported by cryptolib\"])}\n end.\n\npriv_enc_pub_dec(Alg, KeyEnc, KeyDec, Padding) ->\n case pubkey_alg_supported(Alg) of\n true ->\n PlainText = <<\"Hej p\u00e5 dig\">>,\n CryptoText = crypto:private_encrypt(Alg, PlainText, KeyEnc, Padding),\n case crypto:public_decrypt(Alg, CryptoText, KeyDec, Padding) of\n PlainText -> ok;\n _ -> {fail, \"Encrypt-decrypt error\"}\n end;\n false ->\n {skip, lists:concat([Alg,\" is not supported by cryptolib\"])}\n end.\n\nsign_verify(Alg, Sha, KeySign, KeyVerify) ->\n case pubkey_alg_supported(Alg) of\n true ->\n PlainText = <<\"Hej p\u00e5 dig\">>,\n Signature = crypto:sign(Alg, Sha, PlainText, KeySign),\n case is_fake(Signature) of\n true ->\n ct:pal(\"SIG ~p ~p size ~p~n~p\",[Alg,Sha,size(Signature),Signature]),\n {fail, \"Faked RSA impl used!!\"};\n false ->\n case crypto:verify(Alg, Sha, PlainText, Signature, KeyVerify) of\n true -> ok;\n _ -> {fail, \"Sign-verify error\"}\n end\n end;\n false ->\n {skip, lists:concat([Alg,\" is not supported by cryptolib\"])}\n end.\n\n\n%%% Use fake engine rsa implementation\nsign_verify_fake(Alg, Sha, KeySign, KeyVerify) ->\n case pubkey_alg_supported(Alg) of\n true ->\n PlainText = <<\"Fake me!\">>,\n Signature = crypto:sign(Alg, Sha, PlainText, KeySign),\n case is_fake(Signature) of\n true ->\n case crypto:verify(Alg, Sha, PlainText, Signature, KeyVerify) of\n true -> ok;\n _ -> {fail, \"Sign-verify error\"}\n end;\n false ->\n ct:pal(\"SIG ~p ~p size ~p~n~p\",[Alg,Sha,size(Signature),Signature]),\n {fail, \"Faked impl not used\"}\n end;\n false ->\n {skip, lists:concat([Alg,\" is not supported by cryptolib\"])}\n end.\n\n\nis_fake(Sig) -> is_fake(Sig, 0).\n\nis_fake(<<>>, _) -> true;\nis_fake(<>, B) -> is_fake(Rest, B+1);\nis_fake(_, _) -> false.\n\n\n \n","avg_line_length":37.3587939698,"max_line_length":102,"alphanum_fraction":0.4604541052} +{"size":34485,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% @author Marc Worrell \n%% @copyright 2009-2015 Marc Worrell\n\n%% @doc Module supervisor. Uses a z_supervisor. Starts\/restarts module processes.\n\n%% Copyright 2009-2015 Marc Worrell\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%% \n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%% \n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n-module(z_module_manager).\n-author('Marc Worrell ').\n-behaviour(gen_server).\n\n-compile([{parse_transform, lager_transform}]).\n\n%% External exports\n%% gen_server exports\n-export([init\/1, handle_call\/3, handle_cast\/2, handle_info\/2, terminate\/2, code_change\/3]).\n-export([start_link\/1]).\n\n%% API exports\n-export([\n upgrade\/1,\n deactivate\/2,\n activate\/2,\n restart\/2,\n module_reloaded\/2,\n active\/1,\n active\/2,\n active_dir\/1,\n get_provided\/1,\n get_modules\/1,\n get_modules_status\/1,\n whereis\/2,\n all\/1,\n scan\/1,\n prio\/1,\n prio_sort\/1,\n dependency_sort\/1,\n dependencies\/1,\n startable\/2,\n module_exists\/1,\n title\/1,\n reinstall\/2\n ]).\n\n-include_lib(\"zotonic.hrl\").\n\n%% The default module priority\n-define(MOD_PRIO, 500).\n\n%% Give a module a minute to start\n-define(MODULE_START_TIMEOUT, 60000).\n\n%% Module manager state\n-record(state, {\n context :: #context{},\n sup :: pid(),\n module_exports = [] :: list({atom(), list()}),\n module_schema = [] :: list({atom(), integer()|undefined}),\n start_wait = none :: none | {atom(), pid(), erlang:timestamp()}, \n start_queue = [] :: list(),\n start_error = [] :: list()\n }).\n\n\n%%====================================================================\n%% API\n%%====================================================================\n%% @spec start_link(SiteProps::proplist()) -> {ok,Pid} | ignore | {error,Error}\n%% @doc Starts the module manager\nstart_link(SiteProps) ->\n Context = z_acl:sudo(z_context:new(proplists:get_value(host, SiteProps))),\n gen_server:start_link({local, name(Context)}, ?MODULE, [{context, Context} | SiteProps], []).\n\n\n%% @spec upgrade(#context{}) -> ok\n%% @doc Reload the list of all modules, add processes if necessary.\nupgrade(Context) ->\n flush(Context),\n gen_server:cast(name(Context), upgrade).\n\n\n%% @doc Deactivate a module. The module is marked as deactivated and stopped when it was running.\n%% @spec deactivate(Module, #context{}) -> ok\ndeactivate(Module, Context) ->\n flush(Context),\n case z_db:q(\"update module set is_active = false, modified = now() where name = $1\", [Module], Context) of\n 1 -> upgrade(Context);\n 0 -> ok\n end.\n\n\n%% @doc Activate a module. The module is marked as active and started as a child of the module z_supervisor.\n%% The module manager can be checked later to see if the module started or not.\n%% @spec activate(Module, #context{}) -> void()\nactivate(Module, Context) ->\n flush(Context),\n Scanned = scan(Context),\n {Module, _Dirname} = proplists:lookup(Module, Scanned),\n F = fun(Ctx) ->\n case z_db:q(\"update module set is_active = true, modified = now() where name = $1\", [Module], Ctx) of\n 0 -> z_db:q(\"insert into module (name, is_active) values ($1, true)\", [Module], Ctx);\n 1 -> 1\n end\n end,\n 1 = z_db:transaction(F, Context),\n upgrade(Context).\n\n\n%% @doc Restart a module, activates the module if it was not activated.\nrestart(Module, Context) ->\n case z_db:q(\"select true from module where name = $1 and is_active = true\", [Module], Context) of\n [{true}] -> \n gen_server:cast(name(Context), {restart_module, Module});\n _ ->\n activate(Module, Context)\n end.\n\n\n%% @doc Check all observers of a module, ensure that they are all active. Used after a module has been reloaded\nmodule_reloaded(Module, Context) ->\n gen_server:cast(name(Context), {module_reloaded, Module}).\n\n\n%% @doc Return the list of active modules.\n%% @spec active(#context{}) -> [ atom() ]\nactive(Context) ->\n case z_db:has_connection(Context) of\n true ->\n F = fun() -> \n Modules = z_db:q(\"select name from module where is_active = true order by name\", Context),\n [ z_convert:to_atom(M) || {M} <- Modules ]\n end,\n z_depcache:memo(F, {?MODULE, active, Context#context.host}, Context);\n false ->\n case m_site:get(modules, Context) of\n L when is_list(L) -> L;\n _ -> []\n end\n end.\n\n\n\n%% @doc Return whether a specific module is active.\n-spec active(Module::atom(), #context{}) -> boolean().\nactive(Module, Context) ->\n case z_db:has_connection(Context) of\n true ->\n F = fun() ->\n case z_db:q(\"select true from module where name = $1 and is_active = true\", [Module], Context) of\n [{true}] -> true;\n _ -> false\n end\n end,\n z_depcache:memo(F, {?MODULE, {active, Module}, Context#context.host}, Context);\n false ->\n lists:member(Module, active(Context))\n end.\n\n\n%% @doc Return the list of all active modules and their directories\n%% @spec active_dir(#context{}) -> [ {atom, Dir} ]\nactive_dir(Context) ->\n Active = active(Context),\n All = scan(Context),\n [ {M, proplists:get_value(M, All)} || M <- Active ].\n\n\n%% @doc Return the list of all modules running.\nget_modules(Context) ->\n gen_server:call(name(Context), get_modules).\n\n\n%% @doc Return the list of all provided functionalities in running modules.\nget_provided(Context) ->\n gen_server:call(name(Context), get_provided).\n\n\n%% @doc Return the status of all running modules.\nget_modules_status(Context) ->\n gen_server:call(name(Context), get_modules_status).\n\n\n%% @doc Return the pid of a running module\nwhereis(Module, Context) ->\n gen_server:call(name(Context), {whereis, Module}).\n\n\n%% @doc Return the list of all modules in the database.\n%% @spec all(#context{}) -> [ atom() ]\nall(Context) ->\n Modules = z_db:q(\"select name from module order by name\", Context),\n [ z_convert:to_atom(M) || {M} <- Modules ].\n\n\n%% @doc Scan for a list of modules present in the site's module directories. A module is always a directory,\n%% the name of the directory is the same as the name of the module.\n%% @spec scan(#context{}) -> [ {atom(), dirname()} ]\nscan(#context{host=Host}) ->\n All = [\n %% Zotonic modules\n [z_utils:lib_dir(modules), \"mod_*\"],\n\n %% User-installed Zotonic sites\n [z_path:user_sites_dir(), Host, \"modules\", \"mod_*\"],\n [z_path:user_sites_dir(), Host],\n\n %% User-installed modules\n [z_path:user_modules_dir(), \"mod_*\"],\n\n %% Backward compatibility\n [z_utils:lib_dir(priv), \"sites\", Host, \"modules\", \"mod_*\"],\n [z_utils:lib_dir(priv), \"sites\", Host],\n [z_utils:lib_dir(priv), \"modules\", \"mod_*\"]\n \n ],\n Files = lists:foldl(fun(L, Acc) -> L ++ Acc end, [], [filelib:wildcard(filename:join(P)) || P <- All]),\n [ {z_convert:to_atom(filename:basename(F)), F} || F <- Files ].\n\n\n%% @doc Return the priority of a module. Default priority is 500, lower is higher priority. \n%% Never crash on a missing module.\n%% @spec prio(Module) -> integer()\nprio(Module) ->\n try\n Info = erlang:get_module_info(Module, attributes),\n case proplists:get_value(mod_prio, Info) of\n [Prio] -> Prio;\n _ -> ?MOD_PRIO\n end\n catch\n _M:_E -> ?MOD_PRIO\n end.\n\n\n%% @doc Sort the results of a scan on module priority first, module name next. \n%% The list is made up of {module, Values} tuples\n%% @spec prio_sort(proplist()) -> proplist()\nprio_sort([{_,_}|_]=ModuleProps) ->\n WithPrio = [ {z_module_manager:prio(M), {M, X}} || {M, X} <- ModuleProps ],\n Sorted = lists:sort(WithPrio),\n [ X || {_Prio, X} <- Sorted ];\n\n%% @doc Sort the results of a scan on module priority first, module name next. \n%% The list is made up of module atoms.\n%% @spec prio_sort(proplist()) -> proplist()\nprio_sort(Modules) ->\n WithPrio = [ {z_module_manager:prio(M), M} || M <- Modules ],\n Sorted = lists:sort(WithPrio),\n [ M || {_Prio, M} <- Sorted ].\n\n\n%% @doc Sort all modules on their dependencies (with sub sort the module's priority)\ndependency_sort(#context{} = Context) ->\n dependency_sort(active(Context));\ndependency_sort(Modules) when is_list(Modules) ->\n Ms = [ dependencies(M) || M <- prio_sort(Modules) ],\n z_toposort:sort(Ms).\n\n\n%% @doc Return a module's dependencies as a tuple usable for z_toposort:sort\/1.\ndependencies({M, X}) ->\n {_, Ds, Ps} = dependencies(M),\n {{M,X}, Ds, Ps};\ndependencies(M) when is_atom(M) ->\n try\n Info = erlang:get_module_info(M, attributes),\n Depends = proplists:get_value(mod_depends, Info, [base]),\n Provides = [ M | proplists:get_value(mod_provides, Info, []) ],\n {M, Depends, Provides}\n catch\n _M:_E -> {M, [], []}\n end.\n\n\nstartable(M, #context{} = Context) ->\n Provided = get_provided(Context),\n startable(M, Provided);\nstartable(Module, Dependencies) when is_list(Dependencies) ->\n case is_module(Module) of\n true ->\n case dependencies(Module) of\n {Module, Depends, _Provides} ->\n Missing = lists:foldl(fun(Dep, Ms) ->\n case lists:member(Dep, Dependencies) of\n true -> Ms;\n false -> [Dep|Ms]\n end\n end,\n [],\n Depends),\n case Missing of\n [] -> ok;\n _ -> {error, {missing_dependencies, Missing}}\n end;\n _ ->\n {error, could_not_derive_dependencies}\n end;\n false ->\n {error, not_found}\n end.\n\n\nget_start_error_reason({error, not_found}) ->\n \"Module not found\";\nget_start_error_reason({error, {missing_dependencies, Missing}}) ->\n \"Missing dependencies: \" ++ binary_to_list(iolist_to_binary(io_lib:format(\"~p\", [Missing])));\nget_start_error_reason({error, could_not_derive_dependencies}) ->\n \"Could not derive dependencies\".\n\n\n\n\n%% @doc Check if the code of a module exists. The database can hold module references to non-existing modules.\nmodule_exists(M) ->\n case code:ensure_loaded(M) of\n {module,M} -> true;\n {error, _} -> false\n end.\n\n\n%% @doc Get the title of a module.\ntitle(M) ->\n try\n proplists:get_value(mod_title, M:module_info(attributes))\n catch\n _M:_E -> undefined\n end.\n\n\n%% @doc Get the schema version of a module.\nmod_schema(M) ->\n try\n {mod_schema, [S]} = proplists:lookup(mod_schema, M:module_info(attributes)),\n S\n catch\n _M:_E -> undefined\n end.\n\ndb_schema_version(M, Context) ->\n z_db:q1(\"SELECT schema_version FROM module WHERE name = $1\", [M], Context).\n\nset_db_schema_version(M, V, Context) ->\n 1 = z_db:q(\"UPDATE module SET schema_version = $1 WHERE name = $2\", [V, M], Context),\n ok.\n\n\n\n%%====================================================================\n%% gen_server callbacks\n%%====================================================================\n\n\n%% @spec init(Args) -> {ok, State} |\n%% {ok, State, Timeout} |\n%% ignore |\n%% {stop, Reason}\n%% @doc Initiates the server.\ninit(Args) ->\n Context = proplists:get_value(context, Args),\n lager:md([\n {site, z_context:site(Context)},\n {module, ?MODULE}\n ]),\n {ok, Sup} = z_supervisor:start_link([]),\n z_supervisor:set_manager_pid(Sup, self()),\n {ok, #state{context=Context, sup=Sup}}.\n\n\n%% @spec handle_call(Request, From, State) -> {reply, Reply, State} |\n%% {reply, Reply, State, Timeout} |\n%% {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, Reply, State} |\n%% {stop, Reason, State}\n%% @doc Return a list of all enabled modules managed by the z_supervisor\nhandle_call(get_modules, _From, State) ->\n All = handle_get_modules(State),\n {reply, All, State};\n\n%% @doc Return the list of all provided services by the modules.\nhandle_call(get_provided, _From, State) ->\n Provided = handle_get_provided(State),\n {reply, Provided, State};\n\n%% @doc Return all running modules and their status\nhandle_call(get_modules_status, _From, State) ->\n {reply, z_supervisor:which_children(State#state.sup), State};\n\n%% @doc Return the pid of a running module\nhandle_call({whereis, Module}, _From, State) ->\n Running = proplists:get_value(running, z_supervisor:which_children(State#state.sup)),\n Ret = case lists:keysearch(Module, 1, Running) of\n {value, {Module, _, Pid, _}} -> {ok, Pid};\n false -> {error, not_running}\n end,\n {reply, Ret, State};\n\n%% @doc Trap unknown calls\nhandle_call(Message, _From, State) ->\n {stop, {unknown_call, Message}, State}.\n\n\n%% @spec handle_cast(Msg, State) -> {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, State}\n%% @doc Sync enabled modules with loaded modules\nhandle_cast(upgrade, State) ->\n State1 = handle_upgrade(State),\n {noreply, State1};\n\n%% @doc Sync enabled modules with loaded modules\nhandle_cast(start_next, State) ->\n State1 = handle_start_next(State),\n {noreply, State1};\n\n%% @doc Restart a running module.\nhandle_cast({restart_module, Module}, State) ->\n State1 = handle_restart_module(Module, State),\n {noreply, State1};\n\n%% @doc New child process started, add the event listeners\n%% @todo When this is an automatic restart, start all depending modules\nhandle_cast({supervisor_child_started, ChildSpec, Pid}, State) ->\n Module = ChildSpec#child_spec.name,\n lager:debug(\"[~p] Module ~p started\", [z_context:site(State#state.context), Module]),\n State1 = handle_start_child_result(Module, {ok, Pid}, State),\n {noreply, State1};\n\n%% @doc Handle errors, success is handled by the supervisor_child_started above.\nhandle_cast({start_child_result, Module, {error, _} = Error}, State) ->\n State1 = handle_start_child_result(Module, Error, State),\n lager:error(\"[~p] Module ~p start error ~p\", [z_context:site(State#state.context), Module, Error]),\n {noreply, State1};\nhandle_cast({start_child_result, _Module, {ok, _}}, State) ->\n {noreply, State};\n\n%% @doc Existing child process stopped, remove the event listeners\nhandle_cast({supervisor_child_stopped, ChildSpec, Pid}, State) ->\n Module = ChildSpec#child_spec.name,\n remove_observers(Module, Pid, State),\n lager:debug(\"[~p] Module ~p stopped\", [z_context:site(State#state.context), Module]),\n z_notifier:notify(#module_deactivate{module=Module}, State#state.context), \n stop_children_with_missing_depends(State),\n {noreply, State};\n\n%% @doc Check all observers of a module. Add new ones, remove non-existing ones.\n%% This is called after a code reload of a module.\nhandle_cast({module_reloaded, Module}, State) ->\n lager:debug(\"[~p] checking observers of (re-)loaded module ~p\", [z_context:site(State#state.context), Module]),\n State1 = refresh_module_exports(Module, refresh_module_schema(Module, State)),\n OldExports = proplists:get_value(Module, State#state.module_exports),\n NewExports = proplists:get_value(Module, State1#state.module_exports),\n OldSchema = proplists:get_value(Module, State#state.module_schema),\n NewSchema = proplists:get_value(Module, State1#state.module_schema),\n case {OldExports, OldSchema} of\n {NewExports, NewSchema} ->\n {noreply, State1};\n {undefined, undefined} ->\n % Assume this load is because of the first start, otherwise there would be some exports known.\n {noreply, State1};\n _Changed ->\n % Exports or schema changed, assume the worst and restart the complete module\n lager:info(\"[~p] exports or schema of (re-)loaded module ~p changed, restarting module\", [z_context:site(State#state.context), Module]),\n State2 = handle_restart_module(Module, State1),\n {noreply, State2}\n end;\n\n%% @doc Trap unknown casts\nhandle_cast(Message, State) ->\n lager:error(\"z_module_manager: unknown cast ~p in state ~p\", [Message, State]),\n {stop, {unknown_cast, Message}, State}.\n\n\n%% @spec handle_info(Info, State) -> {noreply, State} |\n%% {noreply, State, Timeout} |\n%% {stop, Reason, State}\n%% @doc Handling all non call\/cast messages\nhandle_info(_Info, State) ->\n {noreply, State}.\n\n\n%% @spec terminate(Reason, State) -> void()\n%% @doc This function is called by a gen_server when it is about to\n%% terminate. It should be the opposite of Module:init\/1 and do any necessary\n%% cleaning up. When it returns, the gen_server terminates with Reason.\n%% The return value is ignored.\nterminate(_Reason, _State) ->\n ok.\n\n%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}\n%% @doc Convert process state when code is changed\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\n\n%%====================================================================\n%% support functions\n%%====================================================================\n\n\n%% @doc Return the name for this site's module manager\nname(Context) ->\n name(?MODULE, Context).\nname(Module, #context{host=Host}) ->\n z_utils:name_for_host(Module, Host).\n\nflush(Context) ->\n z_depcache:flush({?MODULE, active, Context#context.host}, Context).\n\nhandle_restart_module(Module, #state{context=Context, sup=ModuleSup} = State) ->\n z_supervisor:delete_child(ModuleSup, Module),\n z_supervisor:add_child_async(ModuleSup, module_spec(Module, Context)),\n handle_upgrade(State).\n\n\nhandle_upgrade(#state{context=Context, sup=ModuleSup} = State) ->\n ValidModules = valid_modules(Context),\n z_depcache:flush(z_modules, Context),\n\n ChildrenPids = handle_get_modules_pid(State),\n Old = sets:from_list([Name || {Name, _} <- ChildrenPids]),\n New = sets:from_list(ValidModules),\n Kill = sets:subtract(Old, New),\n Create = sets:subtract(New, Old),\n\n Running = z_supervisor:running_children(State#state.sup),\n Start = sets:to_list(sets:subtract(New, sets:from_list(Running))),\n {ok, StartList} = dependency_sort(Start),\n lager:debug(\"[~p] Stopping modules: ~p\", [z_context:site(Context), sets:to_list(Kill)]),\n lager:debug(\"[~p] Starting modules: ~p\", [z_context:site(Context), Start]),\n sets:fold(fun (Module, ok) ->\n z_supervisor:delete_child(ModuleSup, Module),\n ok\n end, ok, Kill),\n\n sets:fold(fun (Module, ok) ->\n z_supervisor:add_child_async(ModuleSup, module_spec(Module, Context)),\n ok\n end, ok, Create),\n\n % 1. Put all to be started modules into a start list (add to State)\n % 2. Let the module manager start them one by one (if startable)\n % 3. Log any start errors, suppress modules that have errors.\n % 4. Log non startable modules (remaining after all startable modules have started)\n case {StartList, sets:size(Kill)} of\n {[], 0} -> \n State#state{start_queue=[]};\n _ ->\n gen_server:cast(self(), start_next),\n State#state{start_queue=StartList}\n end.\n\nhandle_start_next(#state{context=Context, start_queue=[]} = State) ->\n % Signal modules are loaded, and load all translations.\n z_notifier:notify(module_ready, Context),\n lager:debug(\"[~p] Finished starting modules\", [z_context:site(Context)]),\n spawn_link(fun() -> z_trans_server:load_translations(Context) end),\n State;\nhandle_start_next(#state{context=Context, sup=ModuleSup, start_queue=Starting} = State) ->\n % Filter all children on the capabilities of the loaded modules.\n Provided = handle_get_provided(State),\n case lists:filter(fun(M) -> is_startable(M, Provided) end, Starting) of\n [] ->\n [\n begin\n StartErrorReason = get_start_error_reason(startable(M, Provided)),\n Msg = iolist_to_binary(io_lib:format(\"Could not start ~p: ~s\", [M, StartErrorReason])),\n z_session_manager:broadcast(#broadcast{type=\"error\", message=Msg, title=\"Module manager\", stay=false}, z_acl:sudo(Context)),\n lager:error(\"[~p] ~s\", [z_context:site(Context), Msg])\n end || M <- Starting\n ],\n\n % Add non-started modules to the list with errors.\n CleanedUpErrors = lists:foldl(fun(M,Acc) -> \n proplists:delete(M,Acc) \n end,\n State#state.start_error,\n Starting),\n\n handle_start_next(State#state{\n start_error=[ {M, case is_module(M) of false -> not_found; true -> dependencies_error end} \n || M <- Starting \n ] ++ CleanedUpErrors,\n start_queue=[]\n });\n [Module|_] ->\n State1 = refresh_module_exports(Module, refresh_module_schema(Module, State)),\n {Module, Exports} = lists:keyfind(Module, 1, State1#state.module_exports),\n case start_child(self(), Module, ModuleSup, module_spec(Module, Context), Exports, Context) of\n {ok, StartHelperPid} -> \n State1#state{\n start_error=proplists:delete(Module, State1#state.start_error),\n start_wait={Module, StartHelperPid, os:timestamp()},\n start_queue=lists:delete(Module, Starting)\n };\n {error, Reason} -> \n handle_start_next(\n State1#state{\n start_error=[ {Module, Reason} | proplists:delete(Module, State1#state.start_error) ],\n start_queue=lists:delete(Module, Starting)\n })\n end\n end.\n\n%% @doc Check if all module dependencies are running.\nis_startable(Module, Dependencies) ->\n startable(Module, Dependencies) =:= ok.\n\n%% @doc Check if we can load the module\nis_module(Module) ->\n try \n {ok, _} = z_utils:ensure_existing_module(Module),\n true\n catch \n M:E -> \n lager:error(\"Can not fetch module info for module ~p, error: ~p:~p\", [Module, M, E]),\n false\n end.\n\n%% @doc Try to add and start the child, do not crash on missing modules. Run as a separate process.\n%% @todo Add some preflight tests\nstart_child(ManagerPid, Module, ModuleSup, Spec, Exports, Context) ->\n StartPid = spawn_link(\n fun() ->\n Result = case catch manage_schema(Module, Exports, Context) of\n ok ->\n % Try to start it\n z_supervisor:start_child(ModuleSup, Spec#child_spec.name, ?MODULE_START_TIMEOUT);\n Error ->\n lager:error(\"[~p] Error starting module ~p, Schema initialization error:~n~p~n\", \n [z_context:site(Context), Module, Error]),\n {error, {schema_init, Error}}\n end,\n gen_server:cast(ManagerPid, {start_child_result, Module, Result})\n end\n ),\n {ok, StartPid}.\n\n\n\nhandle_start_child_result(Module, Result, State) ->\n % Where we waiting for this child? If so, start the next.\n {State1,IsWaiting} = case State#state.start_wait of\n {Module, _Pid, _NowStarted} ->\n {State#state{start_wait=none}, true};\n _Other ->\n {State, false}\n end,\n ReturnState = case Result of\n {ok, Pid} ->\n % Remove any registered errors for the started module\n State2 = State1#state{start_error=lists:keydelete(Module, 1, State1#state.start_error)},\n add_observers(Module, Pid, State2),\n z_notifier:notify(#module_activate{module=Module, pid=Pid}, State2#state.context),\n State2;\n {error, _Reason} = Error ->\n % Add a start error for this module\n State1#state{\n start_error=[ {Module, Error} | lists:keydelete(Module, 1, State1#state.start_error) ]\n }\n end,\n case IsWaiting of\n true -> gen_server:cast(self(), start_next);\n false -> ok\n end,\n ReturnState.\n\n\n%% @doc Return the list of all provided services.\nhandle_get_provided(State) ->\n get_provided_for_modules(handle_get_running(State)).\n\nget_provided_for_modules(Modules) ->\n lists:flatten(\n [ case dependencies(M) of\n {_, _, Provides} -> Provides;\n _ -> []\n end\n || M <- Modules ]). \n\n\nstop_children_with_missing_depends(State) ->\n Modules = handle_get_modules(State),\n Provided = get_provided_for_modules(Modules),\n case lists:filter(fun(M) -> not is_startable(M, Provided) end, Modules) of\n [] ->\n [];\n Unstartable ->\n lager:warning(\"[~p] Stopping child modules ~p\", \n [z_context:site(State#state.context), Unstartable]),\n [ z_supervisor:stop_child(State#state.sup, M) || M <- Unstartable ]\n end.\n\n\n%% @doc Return the list of module names currently managed by the z_supervisor.\nhandle_get_modules(State) ->\n [ Name || {Name,_Pid} <- handle_get_modules_pid(State) ].\n\n%% @doc Return the list of module names currently managed and running by the z_supervisor.\nhandle_get_running(State) ->\n z_supervisor:running_children(State#state.sup).\n\n%% @doc Return the list of module names and their pid currently managed by the z_supervisor.\nhandle_get_modules_pid(State) ->\n lists:flatten(\n lists:map(fun({_State,Children}) ->\n [ {Name,Pid} || {Name,_Spec,Pid,_Time} <- Children ]\n end,\n z_supervisor:which_children(State#state.sup))).\n\n%% @doc Get a list of all valid modules\nvalid_modules(Context) ->\n Ms0 = lists:filter(fun module_exists\/1, active(Context)),\n lists:filter(fun(Mod) -> valid(Mod, Context) end, Ms0).\n\n\n%% @doc Return the z_supervisor child spec for a module\nmodule_spec(ModuleName, Context) ->\n {ok, Cfg} = z_sites_manager:get_site_config(z_context:site(Context)),\n Args = [ {context, Context}, {module, ModuleName} | Cfg ],\n ChildModule = gen_server_module(ModuleName),\n #child_spec{\n name=ModuleName,\n mfa={ChildModule, start_link, [Args]}\n }.\n\n\n%% When a module does not implement a gen_server then we use a dummy gen_server.\ngen_server_module(M) ->\n case has_behaviour(M, gen_server) orelse has_behaviour(M, supervisor) of\n true -> M;\n false -> z_module_dummy\n end.\n\nhas_behaviour(M, Behaviour) ->\n case proplists:get_value(behaviour, erlang:get_module_info(M, attributes)) of\n L when is_list(L) ->\n lists:member(Behaviour, L);\n undefined ->\n false\n end.\n\n\n%% @doc Check whether given module is valid for the given host\n%% @spec valid(atom(), #context{}) -> bool()\nvalid(M, Context) ->\n lists:member(M, [Mod || {Mod,_} <- scan(Context)]).\n\n\n%% @doc Manage the upgrade\/install of this module.\nmanage_schema(Module, Exports, Context) ->\n Target = mod_schema(Module),\n Current = db_schema_version(Module, Context),\n case {proplists:get_value(manage_schema, Exports), Target =\/= undefined} of\n {undefined, false} ->\n ok; %% No manage_schema function, and no target schema\n {undefined, true} ->\n throw({error, {\"Schema version defined in module but no manage_schema\/2 function.\", Module}});\n {2, _} ->\n %% Module has manage_schema function\n manage_schema(Module, Current, Target, Context)\n end.\n\n%% @doc Fetch the list of exported functions of a module.\nrefresh_module_exports(Module, #state{module_exports=Exports} = State) ->\n Exports1 = lists:keydelete(Module, 1, Exports),\n State#state{\n module_exports=[{Module, erlang:get_module_info(Module, exports)} | Exports1]\n }.\n\n%% @doc Fetch the list of exported functions of a module.\nrefresh_module_schema(Module, #state{module_schema=Schemas} = State) ->\n Schemas1 = lists:keydelete(Module, 1, Schemas),\n State#state{\n module_schema=[{Module, mod_schema(Module)} | Schemas1]\n }.\n\n%% @doc Database version equals target version; ignore\nmanage_schema(_Module, Version, Version, _Context) ->\n ok;\n\n%% @doc Upgrading to undefined schema version..?\nmanage_schema(_Module, _Current, undefined, _Context) ->\n ok; %% or?: throw({error, {upgrading_to_empty_schema_version, Module}});\n\n%% @doc Installing a schema\nmanage_schema(Module, undefined, Target, Context) ->\n SchemaRet = z_db:transaction(\n fun(C) ->\n Module:manage_schema(install, C)\n end,\n Context),\n case SchemaRet of\n #datamodel{} ->\n ok = z_datamodel:manage(Module, SchemaRet, Context);\n ok -> \n ok\n end,\n ok = set_db_schema_version(Module, Target, Context),\n z_db:flush(Context),\n ok;\n\n%% @doc Attempting a schema downgrade.\nmanage_schema(Module, Current, Target, _Context) when\n is_integer(Current) andalso is_integer(Target)\n andalso Current > Target ->\n throw({error, {\"Module downgrades currently not supported.\", Module}});\n\n%% @doc Do a single upgrade step.\nmanage_schema(Module, Current, Target, Context) when\n is_integer(Current) andalso is_integer(Target) ->\n SchemaRet = z_db:transaction(\n fun(C) ->\n Module:manage_schema({upgrade, Current+1}, C)\n end,\n Context),\n case SchemaRet of\n #datamodel{} ->\n ok = z_datamodel:manage(Module, SchemaRet, Context);\n ok -> \n ok\n end,\n ok = set_db_schema_version(Module, Current+1, Context),\n z_db:flush(Context),\n manage_schema(Module, Current+1, Target, Context);\n\n%% @doc Invalid version numbering\nmanage_schema(_, Current, Target, _) ->\n throw({error, {\"Invalid schema version numbering\", Current, Target}}).\n\n\n%% @doc Add the observers for a module, called after module has been activated\nadd_observers(Module, Pid, State) ->\n {Module, Exports} = lists:keyfind(Module, 1, State#state.module_exports),\n lists:foreach(fun({Message, Handler}) ->\n z_notifier:observe(Message, Handler, State#state.context)\n end,\n observes(Module, Exports,Pid)).\n\n%% @doc Remove the observers for a module, called before module is deactivated\nremove_observers(Module, Pid, State) ->\n {Module, Exports} = lists:keyfind(Module, 1, State#state.module_exports),\n lists:foreach(fun({Message, Handler}) ->\n z_notifier:detach(Message, Handler, State#state.context)\n end,\n lists:reverse(observes(Module, Exports, Pid))).\n\n\n%% @doc Get the list of events the module observes.\n%% The event functions should be called: observe_(event)\n%% observe_xxx\/2 functions observer map\/notify and observe_xxx\/3 functions observe folds.\n-spec observes(atom(), list({atom(), integer()}), pid()) -> [{atom(), {atom(),atom()}|{atom(), atom(), [pid()]}}].\nobserves(Module, Exports, Pid) ->\n observes_1(Module, Pid, Exports, []).\n\nobserves_1(_Module, _Pid, [], Acc) ->\n Acc;\nobserves_1(Module, Pid, [{F,Arity}|Rest], Acc) ->\n case atom_to_list(F) of\n \"observe_\" ++ Message when Arity == 2; Arity == 3 ->\n observes_1(Module, Pid, Rest, [{list_to_atom(Message), {Module,F}}|Acc]);\n \"pid_observe_\" ++ Message when Arity == 3; Arity == 4 ->\n observes_1(Module, Pid, Rest, [{list_to_atom(Message), {Module,F,[Pid]}}|Acc]);\n _ -> \n observes_1(Module, Pid, Rest, Acc)\n end;\nobserves_1(Module, Pid, [_|Rest], Acc) -> \n observes_1(Module, Pid, Rest, Acc).\n\n\n\n%% @doc Reinstall the given module's schema, calling\n%% Module:manage_schema(install, Context); if that function exists.\nreinstall(Module, Context) ->\n case proplists:get_value(manage_schema, erlang:get_module_info(Module, exports)) of\n undefined ->\n %% nothing to do, no manage_schema\n nop;\n 2 ->\n %% has manage_schema\/2\n case Module:manage_schema(install, Context) of\n D=#datamodel{} ->\n ok = z_datamodel:manage(Module, D, Context);\n ok -> ok\n end,\n ok = z_db:flush(Context)\n end.\n","avg_line_length":38.3166666667,"max_line_length":148,"alphanum_fraction":0.5893866899} +{"size":551,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(ppool).\n\n-behaviour(application).\n\n-export([start\/2, stop\/1]).\n\n-export([async_queue\/2, run\/2, start_pool\/3,\n\t stop_pool\/1, sync_queue\/2]).\n\nstart(normal, _Args) -> ppool_supersup:start_link().\n\nstop(_State) -> ok.\n\nstart_pool(Name, Limit, {M, F, A}) ->\n ppool_supersup:start_pool(Name, Limit, {M, F, A}).\n\nstop_pool(Name) -> ppool_supersup:stop_pool(Name).\n\nrun(Name, Args) -> ppool_serv:run(Name, Args).\n\nasync_queue(Name, Args) ->\n ppool_serv:async_queue(Name, Args).\n\nsync_queue(Name, Args) ->\n ppool_serv:sync_queue(Name, Args).\n","avg_line_length":21.1923076923,"max_line_length":54,"alphanum_fraction":0.6860254083} +{"size":1100,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%%-------------------------------------------------------------------\r\n%%% @author z.hua\r\n%%% @copyright (C) 2021, \r\n%%% @doc\r\n%%% \u6bd4\u8f83\u8282\u70b9\r\n%%% @end\r\n%%%-------------------------------------------------------------------\r\n-module(ebt_compare).\r\n-author(\"z.hua\").\r\n\r\n-behavior(ebt_behavior).\r\n\r\n-include(\"ebt.hrl\").\r\n\r\n%%-----------------------------------------------------------------------------\r\n%% API Functions\r\n%%-----------------------------------------------------------------------------\r\n-export([on_enter\/3, on_aback\/3]).\r\n\r\non_enter(Tree, Rt, Node) ->\r\n Key = maps:get(key, Node#ebt_node.props),\r\n Op = maps:get(op, Node#ebt_node.props),\r\n Val = maps:get(val, Node#ebt_node.props),\r\n Result = ?__if(ebt_runtime:test_variant(Rt, Key, Op, Val), ?SUCCESS, ?FAILURE),\r\n ebt_behavior:leave(Tree, Rt#ebt_rt{result = Result}).\r\n\r\non_aback(_Tree, _Rt, _Node) ->\r\n erlang:error(not_implemented).\r\n\r\n%%-----------------------------------------------------------------------------\r\n%% Internal Functions\r\n%%-----------------------------------------------------------------------------\r\n","avg_line_length":33.3333333333,"max_line_length":82,"alphanum_fraction":0.3672727273} +{"size":58908,"ext":"erl","lang":"Erlang","max_stars_count":13.0,"content":"%% -*- erlang-indent-level: 2 -*-\n%%\n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2004-2016. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% File : hipe_rtl_lcm.erl\n%% Author : Henrik Nyman and Erik Cedheim\n%% Description : Performs Lazy Code Motion on RTL\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% @doc\n%%\n%% This module implements Lazy Code Motion on RTL.\n%%\n%% @end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n-module(hipe_rtl_lcm).\n\n-export([rtl_lcm\/2]).\n\n-define(SETS, ordsets). %% Which set implementation module to use\n %% We have tried gb_sets, sets and ordsets and\n %% ordsets seems to be a lot faster according to \n %% our test runs.\n\n-include(\"..\/main\/hipe.hrl\").\n-include(\"hipe_rtl.hrl\").\n-include(\"..\/flow\/cfg.hrl\").\n\n%%-define(LCM_DEBUG, true). %% When defined and true, produces debug printouts\n\n%%=============================================================================\n\n%%\n%% @doc Performs Lazy Code Motion on RTL.\n%%\n\n-spec rtl_lcm(cfg(), comp_options()) -> cfg().\n\nrtl_lcm(CFG, Options) ->\n %% Perform pre-calculation of the data sets.\n ?opt_start_timer(\"RTL LCM precalc\"),\n {NodeInfo, EdgeInfo, AllExpr, ExprMap, IdMap, Labels} = lcm_precalc(CFG, Options),\n ?opt_stop_timer(\"RTL LCM precalc\"),\n %% {NodeInfo, EdgeInfo, AllExpr, ExprMap, Labels} = \n %% ?option_time(lcm_precalc(CFG, Options), \"RTL LCM precalc\", Options),\n \n pp_debug(\"-------------------------------------------------~n\",[]),\n %% pp_debug( \"~w~n\", [MFA]),\n\n %% A check if we should pretty print the result.\n case proplists:get_bool(pp_rtl_lcm, Options) of\n true ->\n pp_debug(\"-------------------------------------------------~n\",[]),\n %% pp_debug(\"AllExpr: ~w~n\", [AllExpr]),\n pp_debug(\"AllExpr:~n\", []),\n pp_exprs(ExprMap, IdMap, ?SETS:to_list(AllExpr)),\n %% pp_sets(ExprMap, NodeInfo, EdgeInfo, AllExpr, CFG2<-ERROR!, Labels); \n pp_sets(ExprMap, IdMap, NodeInfo, EdgeInfo, AllExpr, CFG, Labels);\n _ ->\n ok\n end,\n\n pp_debug(\"-------------------------------------------------~n\",[]),\n {CFG1, MoveSet} = ?option_time(perform_lcm(CFG, NodeInfo, EdgeInfo, ExprMap,\n\t\t\t\t\t IdMap, AllExpr, mk_edge_bb_map(),\n\t\t\t\t\t ?SETS:new(), Labels),\n\t\t\t\t \"RTL LCM perform_lcm\", Options),\n\n %% Scan through list of moved expressions and replace their \n %% assignments with the new temporary created for that expression\n MoveList = ?SETS:to_list(MoveSet),\n CFG2 = ?option_time(moved_expr_replace_assignments(CFG1, ExprMap, IdMap,\n\t\t\t\t\t\t MoveList),\n\t\t \"RTL LCM moved_expr_replace_assignments\", Options),\n pp_debug(\"-------------------------------------------------~n~n\",[]),\n\n CFG2.\n\n%%=============================================================================\n%% Performs lazy code motion given the pre-calculated data sets.\nperform_lcm(CFG, _, _, _, _, _, _, MoveSet, []) ->\n {CFG, MoveSet};\nperform_lcm(CFG0, NodeInfo, EdgeInfo, ExprMap, IdMap, AllExp, BetweenMap, \n\t MoveSet0, [Label|Labels]) ->\n Code0 = hipe_bb:code(hipe_rtl_cfg:bb(CFG0, Label)),\n DeleteSet = delete(NodeInfo, Label),\n \n %% Check if something should be deleted from this block.\n {CFG1, MoveSet1} = \n case ?SETS:size(DeleteSet) > 0 of\n true ->\n pp_debug(\"Label ~w: Expressions Deleted: ~n\", [Label]),\n Code1 = delete_exprs(Code0, ExprMap, IdMap, ?SETS:to_list(DeleteSet)),\n BB = hipe_bb:mk_bb(Code1),\n {hipe_rtl_cfg:bb_add(CFG0, Label, BB), \n ?SETS:union(MoveSet0, DeleteSet)};\n false ->\n {CFG0, MoveSet0}\n end,\n \n Succs = hipe_rtl_cfg:succ(CFG1, Label), \n \n %% Go through the list of successors and insert expression where needed.\n %% Also collect a list of expressions that are inserted somewhere\n {CFG2, NewBetweenMap, MoveSet2} = \n lists:foldl(fun(Succ, {CFG, BtwMap, MoveSet}) ->\n\t\t InsertSet = calc_insert_edge(NodeInfo, EdgeInfo, \n\t\t\t\t\t\t Label, Succ),\n\t\t %% Check if something should be inserted on this edge.\n\t\t case ?SETS:size(InsertSet) > 0 of\n\t\t true ->\n\t\t\tpp_debug(\"Label ~w: Expressions Inserted for Successor: ~w~n\", [Label, Succ]),\n\t\t\tInsertList = ?SETS:to_list(InsertSet),\n\t\t\t{NewCFG, NewBtwMap} =\n\t\t\t insert_exprs(CFG, Label, Succ, ExprMap, IdMap, \n\t\t\t\t BtwMap, InsertList),\n\t\t\t{NewCFG, NewBtwMap, ?SETS:union(MoveSet, InsertSet)};\n\t\t false ->\n\t\t\t{CFG, BtwMap, MoveSet}\n\t\t end\n\t\tend, \n\t\t{CFG1, BetweenMap, MoveSet1}, Succs),\n \n perform_lcm(CFG2, NodeInfo, EdgeInfo, ExprMap, IdMap, AllExp, NewBetweenMap, \n\t MoveSet2, Labels).\n\n%%=============================================================================\n%% Scan through list of moved expressions and replace their \n%% assignments with the new temporary created for that expression.\nmoved_expr_replace_assignments(CFG, _, _, []) ->\n CFG;\nmoved_expr_replace_assignments(CFG0, ExprMap, IdMap, [ExprId|Exprs]) ->\n Expr = expr_id_map_get_expr(IdMap, ExprId),\n case expr_map_lookup(ExprMap, Expr) of\n {value, {_, ReplaceList, NewReg}} -> \n CFG1 = lists:foldl(fun({Label, Reg}, CFG) ->\n %% Find and replace expression in block\n\t\t pp_debug(\"Label ~w: Expressions Replaced:~n\", [Label]),\n\t\t Code0 = hipe_bb:code(hipe_rtl_cfg:bb(CFG, Label)),\n Code1 = \n moved_expr_do_replacement(expr_set_dst(Expr, Reg), \n Reg, NewReg, Code0),\n hipe_rtl_cfg:bb_add(CFG, Label, hipe_bb:mk_bb(Code1))\n end, CFG0, ReplaceList),\n moved_expr_replace_assignments(CFG1, ExprMap, IdMap, Exprs);\n none ->\n moved_expr_replace_assignments(CFG0, ExprMap, IdMap, Exprs)\n end.\n\nmoved_expr_do_replacement(_, _, _, []) ->\n [];\nmoved_expr_do_replacement(Expr, Reg, NewReg, [Expr|Instrs]) ->\n NewExpr = expr_set_dst(Expr, NewReg),\n Move = mk_expr_move_instr(Reg, NewReg),\n pp_debug(\" Replacing:~n\", []),\n pp_debug_instr(Expr),\n pp_debug(\" With:~n\", []),\n pp_debug_instr(NewExpr),\n pp_debug_instr(Move),\n [NewExpr, Move | moved_expr_do_replacement(Expr, Reg, NewReg, Instrs)];\nmoved_expr_do_replacement(Expr, Reg, NewReg, [Instr|Instrs]) ->\n [Instr | moved_expr_do_replacement(Expr, Reg, NewReg, Instrs)].\n\n%%=============================================================================\n%% Goes through the given list of expressions and deletes them from the code.\n%% NOTE We do not actually delete an expression, but instead we replace it \n%% with an assignment from the new temporary containing the result of the \n%% expressions which is guaranteed to have been calculated earlier in \n%% the code.\ndelete_exprs(Code, _, _, []) ->\n Code;\ndelete_exprs(Code, ExprMap, IdMap, [ExprId|Exprs]) ->\n Expr = expr_id_map_get_expr(IdMap, ExprId),\n %% Perform a foldl that goes through the code and deletes all\n %% occurences of the expression.\n NewCode =\n lists:reverse\n (lists:foldl(fun(CodeExpr, Acc) ->\n case is_expr(CodeExpr) of\n true ->\n case expr_clear_dst(CodeExpr) =:= Expr of\n true ->\n pp_debug(\" Deleting: \", []),\n pp_debug_instr(CodeExpr),\n %% Lookup expression entry.\n Defines = \n case expr_map_lookup(ExprMap, Expr) of\n {value, {_, _, Defs}} -> \n\t\t\t\t Defs;\n none -> \n exit({?MODULE, expr_map_lookup,\n \"expression missing\"})\n end,\n MoveCode = \n mk_expr_move_instr(hipe_rtl:defines(CodeExpr),\n\t\t\t\t\t\t Defines),\n pp_debug(\" Replacing with: \", []),\n pp_debug_instr(MoveCode),\n [MoveCode|Acc];\n false ->\n [CodeExpr|Acc]\n end;\n\t\t false ->\n [CodeExpr|Acc]\n end\n end, \n\t\t [], Code)),\n delete_exprs(NewCode, ExprMap, IdMap, Exprs).\n\n%%=============================================================================\n%% Goes through the given list of expressions and inserts them at \n%% appropriate places in the code.\ninsert_exprs(CFG, _, _, _, _, BetweenMap, []) ->\n {CFG, BetweenMap};\ninsert_exprs(CFG, Pred, Succ, ExprMap, IdMap, BetweenMap, [ExprId|Exprs]) ->\n Expr = expr_id_map_get_expr(IdMap, ExprId),\n Instr = expr_map_get_instr(ExprMap, Expr),\n case hipe_rtl_cfg:succ(CFG, Pred) of\n [_] ->\n pp_debug(\" Inserted last: \", []),\n pp_debug_instr(Instr),\n NewCFG = insert_expr_last(CFG, Pred, Instr),\n insert_exprs(NewCFG, Pred, Succ, ExprMap, IdMap, BetweenMap, Exprs);\n _ ->\n case hipe_rtl_cfg:pred(CFG, Succ) of\n [_] ->\n\t pp_debug(\" Inserted first: \", []),\n\t pp_debug_instr(Instr),\n NewCFG = insert_expr_first(CFG, Succ, Instr),\n insert_exprs(NewCFG, Pred, Succ, ExprMap, IdMap, BetweenMap, Exprs);\n _ ->\n\t pp_debug(\" Inserted between: \", []),\n\t pp_debug_instr(Instr),\n {NewCFG, NewBetweenMap} = \n\t insert_expr_between(CFG, BetweenMap, Pred, Succ, Instr),\n insert_exprs(NewCFG, Pred, Succ, ExprMap, IdMap, NewBetweenMap, Exprs)\n end \n end.\n\n%%=============================================================================\n%% Recursively goes through the code in a block and returns a new block\n%% with the new code inserted second to last (assuming the last expression\n%% is a branch operation).\ninsert_expr_last(CFG0, Label, Instr) ->\n Code0 = hipe_bb:code(hipe_rtl_cfg:bb(CFG0, Label)),\n %% FIXME: Use hipe_bb:butlast() instead?\n Code1 = insert_expr_last_work(Label, Instr, Code0),\n hipe_rtl_cfg:bb_add(CFG0, Label, hipe_bb:mk_bb(Code1)).\n\n%%=============================================================================\n%% Recursively goes through the code in a block and returns a new block\n%% with the new code inserted second to last (assuming the last expression\n%% is a branch operation).\ninsert_expr_last_work(_, Instr, []) ->\n %% This case should not happen since this means that block was completely \n %% empty when the function was called. For compatibility we insert it last.\n [Instr];\ninsert_expr_last_work(_, Instr, [Code1]) ->\n %% We insert the code next to last.\n [Instr, Code1];\ninsert_expr_last_work(Label, Instr, [Code|Codes]) ->\n [Code|insert_expr_last_work(Label, Instr, Codes)].\n\n%%=============================================================================\n%% Inserts expression first in the block for the given label.\ninsert_expr_first(CFG0, Label, Instr) ->\n %% The first instruction is always a label\n [Lbl|Code0] = hipe_bb:code(hipe_rtl_cfg:bb(CFG0, Label)),\n Code1 = [Lbl, Instr | Code0],\n hipe_rtl_cfg:bb_add(CFG0, Label, hipe_bb:mk_bb(Code1)).\n\n%%=============================================================================\n%% Inserts an expression on and edge between two existing blocks.\n%% It creates a new basic block to hold the expression. \n%% Created bbs are inserted into BetweenMap to be able to reuse them for \n%% multiple inserts on the same edge.\n%% NOTE Currently creates multiple blocks for identical expression with the\n%% same successor. Since the new bb usually contains very few instructions\n%% this should not be a problem.\ninsert_expr_between(CFG0, BetweenMap, Pred, Succ, Instr) ->\n PredSucc = {Pred, Succ},\n case edge_bb_map_lookup(BetweenMap, PredSucc) of\n none ->\n NewLabel = hipe_rtl:mk_new_label(),\n NewLabelName = hipe_rtl:label_name(NewLabel),\n pp_debug(\" Creating new bb ~w~n\", [NewLabel]),\n Code = [Instr, hipe_rtl:mk_goto(Succ)],\n CFG1 = hipe_rtl_cfg:bb_add(CFG0, NewLabelName, hipe_bb:mk_bb(Code)),\n CFG2 = hipe_rtl_cfg:redirect(CFG1, Pred, Succ, NewLabelName),\n NewBetweenMap = edge_bb_map_insert(BetweenMap, PredSucc, NewLabelName),\n pp_debug(\" Mapping edge (~w,~w) to label ~w~n\", \n\t [Pred, Succ, NewLabelName]),\n {CFG2, NewBetweenMap};\n {value, Label} ->\n pp_debug(\" Using existing new bb for edge (~w,~w) with label ~w~n\", \n\t [Pred, Succ, Label]),\n {insert_expr_last(CFG0, Label, Instr), BetweenMap}\n end.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%% GENERAL UTILITY FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Returns true if the list of registers only contains virtual registers and\n%% no machine registers. \nno_machine_regs([]) ->\n true;\nno_machine_regs([Reg|Regs]) ->\n case hipe_rtl:is_reg(Reg) of\n true ->\n N = hipe_rtl:reg_index(Reg),\n (N >= hipe_rtl_arch:first_virtual_reg()) andalso no_machine_regs(Regs);\n _ ->\n case hipe_rtl:is_fpreg(Reg) of\n\ttrue ->\n\t N = hipe_rtl:fpreg_index(Reg),\n\t (N >= hipe_rtl_arch:first_virtual_reg()) andalso no_machine_regs(Regs);\n\t_ ->\n\t no_machine_regs(Regs)\n end\n end.\n\n%%=============================================================================\n%% Returns true if an RTL instruction is an expression.\n%%\nis_expr(I) ->\n Defines = hipe_rtl:defines(I),\n Uses = hipe_rtl:uses(I),\n \n %% We don't cosider something that doesn't define anything as an expression.\n %% Also we don't consider machine registers to be expressions.\n case length(Defines) > 0 andalso no_machine_regs(Defines)\n andalso no_machine_regs(Uses) of \n true ->\n case I of\n #alu{} -> true;\n%% \t#alu{} ->\n%% \t Dst = hipe_rtl:alu_dst(I),\n%% \t Src1 = hipe_rtl:alu_src1(I),\n%% \t Src2 = hipe_rtl:alu_src2(I),\n\n \t %% Check if dst updates src\n%% \t case Dst =:= Src1 orelse Dst =:= Src2 of\n%% \t true ->\n%% \t false;\n%% \t false ->\n%% \t true\n%% \t end;\n\n\t %% Check if alu expression is untagging of boxed (rX <- vX sub 2)\n%% \t case hipe_rtl:is_reg(Dst) andalso hipe_rtl:is_var(Src1) andalso \n%% \t (hipe_rtl:alu_op(I) =:= sub) andalso hipe_rtl:is_imm(Src2) of\n%% \t true ->\n%% \t case hipe_rtl:imm_value(Src2) of\n%% \t\t2 -> false; %% Tag for boxed. TODO: Should not be hardcoded...\n%% \t\t_ -> true\n%% \t end;\n%% \t false ->\n%% \t true\n%% \t end;\n\t \n #alub{} -> false; %% TODO: Split instruction to consider alu expression?\n #branch{} -> false;\n #call{} -> false; %% We cannot prove that a call has no side-effects\n #comment{} -> false;\n #enter{} -> false;\n %% #fail_to{} -> false; %% Deprecated?\n #fconv{} -> true;\n #fixnumop{} -> true;\n #fload{} -> true;\n #fmove{} -> false;\n #fp{} -> true;\n #fp_unop{} -> true;\n #fstore{} -> false;\n #goto{} -> false;\n #goto_index{} -> false;\n #gctest{} -> false;\n #label{} -> false;\n #load{} -> true;\n #load_address{} ->\n\t case hipe_rtl:load_address_type(I) of\n\t c_const -> false;\n\t closure -> false;\t%% not sure whether safe to move; \n\t %% also probably not worth it\n\t constant -> true\n\t end;\n #load_atom{} -> true;\n #load_word_index{} -> true;\n #move{} -> false;\n #multimove{} -> false;\n #phi{} -> false;\n #return{} -> false;\n #store{} -> false;\n #switch{} -> false\n end;\n false ->\n false\n end.\n\n%%=============================================================================\n%% Replaces destination of RTL expression with empty list.\n%% \nexpr_set_dst(I, [Dst|_Dsts] = DstList) ->\n case I of\n #alu{} -> hipe_rtl:alu_dst_update(I, Dst);\n #call{} -> hipe_rtl:call_dstlist_update(I, DstList);\n #fconv{} -> hipe_rtl:fconv_dst_update(I, Dst);\n #fixnumop{} -> hipe_rtl:fixnumop_dst_update(I, Dst);\n #fload{} -> hipe_rtl:fload_dst_update(I, Dst);\n %% #fmove{} -> hipe_rtl:fmove_dst_update(I, Dst);\n #fp{} -> hipe_rtl:fp_dst_update(I, Dst);\n #fp_unop{} -> hipe_rtl:fp_unop_dst_update(I, Dst);\n #load{} -> hipe_rtl:load_dst_update(I, Dst);\n #load_address{} -> hipe_rtl:load_address_dst_update(I, Dst);\n #load_atom{} -> hipe_rtl:load_atom_dst_update(I, Dst);\n #load_word_index{} -> hipe_rtl:load_word_index_dst_update(I, Dst);\n %% #move{} -> hipe_rtl:move_dst_update(I, Dst);\n _ -> exit({?MODULE, expr_set_dst, \"bad expression\"})\n end.\n\n%%=============================================================================\n%% Replaces destination of RTL expression with empty list.\n%% \nexpr_clear_dst(I) ->\n case I of\n #alu{} -> hipe_rtl:alu_dst_update(I, nil);\n #call{} -> hipe_rtl:call_dstlist_update(I, nil);\n #fconv{} -> hipe_rtl:fconv_dst_update(I, nil);\n #fixnumop{} -> hipe_rtl:fixnumop_dst_update(I, nil);\n #fload{} -> hipe_rtl:fload_dst_update(I, nil);\n %% #fmove{} -> hipe_rtl:fmove_dst_update(I, nil);\n #fp{} -> hipe_rtl:fp_dst_update(I, nil);\n #fp_unop{} -> hipe_rtl:fp_unop_dst_update(I, nil);\n #load{} -> hipe_rtl:load_dst_update(I, nil);\n #load_address{} -> hipe_rtl:load_address_dst_update(I, nil);\n #load_atom{} -> hipe_rtl:load_atom_dst_update(I, nil);\n #load_word_index{} -> hipe_rtl:load_word_index_dst_update(I, nil);\n %% #move{} -> hipe_rtl:move_dst_update(I, nil);\n _ -> exit({?MODULE, expr_clear_dst, \"bad expression\"})\n end.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%% PRECALC FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Pre-calculates the flow analysis and puts the calculated sets in maps for \n%% easy access later.\nlcm_precalc(CFG, Options) ->\n %% Calculate use map and expression map.\n {ExprMap, IdMap} = ?option_time(mk_expr_map(CFG),\n\t\t\t\t \"RTL LCM mk_expr_map\", Options),\n UseMap = ?option_time(mk_use_map(CFG, ExprMap),\n\t\t\t\"RTL LCM mk_use_map\", Options),\n %% Labels = hipe_rtl_cfg:reverse_postorder(CFG),\n Labels = hipe_rtl_cfg:labels(CFG),\n %% StartLabel = hipe_rtl_cfg:start_label(CFG),\n %% AllExpr = all_exprs(CFG, Labels),\n AllExpr = ?SETS:from_list(gb_trees:keys(IdMap)),\n\n %% Calculate the data sets.\n NodeInfo0 = ?option_time(mk_node_info(Labels),\n\t\t\t \"RTL LCM mk_node_info\", Options),\n %% ?option_time(EdgeInfo0 = mk_edge_info(), \"RTL LCM mk_edge_info\", \n %% \t Options),\n EdgeInfo0 = mk_edge_info(),\n NodeInfo1 = ?option_time(calc_up_exp(CFG, ExprMap, NodeInfo0, Labels),\n\t\t\t \"RTL LCM calc_up_exp\", Options),\n NodeInfo2 = ?option_time(calc_down_exp(CFG, ExprMap, NodeInfo1, Labels),\n\t\t\t \"RTL LCM calc_down_exp\", Options),\n NodeInfo3 = ?option_time(calc_killed_expr(CFG, NodeInfo2, UseMap, AllExpr,\n\t\t\t\t\t IdMap, Labels), \n\t\t\t \"RTL LCM calc_killed_exp\", Options),\n NodeInfo4 = ?option_time(calc_avail(CFG, NodeInfo3),\n\t\t\t \"RTL LCM calc_avail\", Options),\n NodeInfo5 = ?option_time(calc_antic(CFG, NodeInfo4, AllExpr),\n\t\t\t \"RTL LCM calc_antic\", Options),\n EdgeInfo1 = ?option_time(calc_earliest(CFG, NodeInfo5, EdgeInfo0, Labels),\n\t\t\t \"RTL LCM calc_earliest\", Options),\n {NodeInfo6, EdgeInfo2} = ?option_time(calc_later(CFG, NodeInfo5, EdgeInfo1),\n\t\t\t\t\t\"RTL LCM calc_later\", Options),\n NodeInfo7 = ?option_time(calc_delete(CFG, NodeInfo6, Labels),\n\t\t\t \"RTL LCM calc_delete\", Options),\n {NodeInfo7, EdgeInfo2, AllExpr, ExprMap, IdMap, Labels}.\n\n%%%%%%%%%%%%%%%%%%% AVAILABLE IN\/OUT FLOW ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Fixpoint calculation of anticipated in\/out sets.\n%% Uses a worklist algorithm.\n%% Performs the avail in\/out flow analysis.\n\n%%=============================================================================\n%% Calculates the available in\/out sets, and returns an updated NodeInfo.\n\ncalc_avail(CFG, NodeInfo) ->\n StartLabel = hipe_rtl_cfg:start_label(CFG),\n Work = init_work([StartLabel]),\n %% Initialize start node\n NewNodeInfo = set_avail_in(NodeInfo, StartLabel, ?SETS:new()),\n calc_avail_fixpoint(Work, CFG, NewNodeInfo).\n\ncalc_avail_fixpoint(Work, CFG, NodeInfo) ->\n case get_work(Work) of\n fixpoint ->\n NodeInfo;\n {Label, NewWork} ->\n {NewNodeInfo, NewLabels} = calc_avail_node(Label, CFG, NodeInfo),\n NewWork2 = add_work(NewWork, NewLabels),\n calc_avail_fixpoint(NewWork2, CFG, NewNodeInfo)\n end.\n\ncalc_avail_node(Label, CFG, NodeInfo) ->\n %% Get avail in\n AvailIn = avail_in(NodeInfo, Label),\n\n %% Calculate avail out\n AvailOut = ?SETS:union(down_exp(NodeInfo, Label),\n\t\t\t ?SETS:subtract(AvailIn,\n\t\t\t\t\tkilled_expr(NodeInfo, Label))),\n \n {Changed, NodeInfo2} = \n case avail_out(NodeInfo, Label) of\n none ->\n\t%% If there weren't any old avail out we use this one.\n\t{true, set_avail_out(NodeInfo, Label, AvailOut)};\n OldAvailOut ->\n\t%% Check if the avail outs are equal.\n\tcase AvailOut =:= OldAvailOut of\n\t true ->\n\t {false, NodeInfo};\n\t false ->\n\t {true, set_avail_out(NodeInfo, Label, AvailOut)}\n\tend\n end,\n\n case Changed of\n true ->\n %% Update AvailIn-sets of successors and add them to worklist\n Succs = hipe_rtl_cfg:succ(CFG, Label),\n NodeInfo3 =\n\tlists:foldl\n\t (fun(Succ, NewNodeInfo) ->\n\t case avail_in(NewNodeInfo, Succ) of\n\t\t none ->\n\t\t %% Initialize avail in to all expressions\n\t\t set_avail_in(NewNodeInfo, Succ, AvailOut);\n\t\t OldAvailIn ->\n\t\t set_avail_in(NewNodeInfo, Succ, \n\t\t\t\t?SETS:intersection(OldAvailIn, AvailOut))\n\t end\n\t end,\n\t NodeInfo2, Succs),\n {NodeInfo3, Succs};\n false ->\n {NodeInfo2, []}\n end.\n\n%%%%%%%%%%%%%%%%%% ANTICIPATED IN\/OUT FLOW ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Fixpoint calculation of anticipated in\/out sets.\n%% Uses a worklist algorithm.\n\n%%=============================================================================\n%% Calculates the anicipated in\/out sets, and returns an updated NodeInfo.\ncalc_antic(CFG, NodeInfo, AllExpr) ->\n %% Initialize worklist with all nodes in postorder\n Labels = hipe_rtl_cfg:postorder(CFG),\n Work = init_work(Labels),\n calc_antic_fixpoint(Work, CFG, NodeInfo, AllExpr).\n\ncalc_antic_fixpoint(Work, CFG, NodeInfo, AllExpr) ->\n case get_work(Work) of\n fixpoint ->\n NodeInfo;\n {Label, NewWork} ->\n {NewNodeInfo, NewLabels} = calc_antic_node(Label, CFG, NodeInfo, AllExpr),\n NewWork2 = add_work(NewWork, NewLabels),\n calc_antic_fixpoint(NewWork2, CFG, NewNodeInfo, AllExpr)\n end.\n\ncalc_antic_node(Label, CFG, NodeInfo, AllExpr) ->\n %% Get antic out\n AnticOut = \n case antic_out(NodeInfo, Label) of\n none -> \n\tcase is_exit_label(CFG, Label) of \n\t true ->\n\t ?SETS:new();\n\t false ->\n\t AllExpr\n\tend;\n \n AnticOutTemp -> AnticOutTemp\n end,\n\n %% Calculate antic in\n AnticIn = ?SETS:union(up_exp(NodeInfo, Label),\n\t\t\t?SETS:subtract(AnticOut,\n\t\t\t\t killed_expr(NodeInfo, Label))),\n {Changed, NodeInfo2} = \n case antic_in(NodeInfo, Label) of\n %% If there weren't any old antic in we use this one.\n none ->\n\t{true, set_antic_in(NodeInfo, Label, AnticIn)};\n\n OldAnticIn ->\n\t%% Check if the antic in:s are equal.\n\tcase AnticIn =:= OldAnticIn of\n\t true ->\n\t {false, NodeInfo};\n\t false ->\n\t {true, \n\t set_antic_in(NodeInfo, Label, AnticIn)}\n\tend\n end,\n\n case Changed of\n true ->\n %% Update AnticOut-sets of predecessors and add them to worklist\n Preds = hipe_rtl_cfg:pred(CFG, Label),\n NodeInfo3 =\n\tlists:foldl\n\t (fun(Pred, NewNodeInfo) ->\n\t case antic_out(NewNodeInfo, Pred) of\n\t\t none ->\n\t\t %% Initialize antic out to all expressions\n\t\t set_antic_out(NewNodeInfo, Pred, AnticIn);\n\t\t OldAnticOut ->\n\t\t set_antic_out(NewNodeInfo, Pred, \n\t\t\t\t ?SETS:intersection(OldAnticOut, AnticIn))\n\t end\n\t end,\n\t NodeInfo2, Preds),\n {NodeInfo3, Preds};\n false ->\n {NodeInfo2, []}\n end.\n\n%%%%%%%%%%%%%%%%%%%%% LATER \/ LATER IN FLOW ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Fixpoint calculations of Later and LaterIn sets. \n%% Uses a worklist algorithm.\n%% Note that the Later set is calculated on edges.\n\n%%=============================================================================\n%% Calculates the Later and LaterIn sets, and returns updates of both \n%% NodeInfo (with LaterIn sets) and EdgeInfo (with Later sets).\n\ncalc_later(CFG, NodeInfo, EdgeInfo) ->\n StartLabel = hipe_rtl_cfg:start_label(CFG),\n Work = init_work([{node, StartLabel}]),\n %% Initialize start node\n NewNodeInfo = set_later_in(NodeInfo, StartLabel, ?SETS:new()),\n calc_later_fixpoint(Work, CFG, NewNodeInfo, EdgeInfo).\n\ncalc_later_fixpoint(Work, CFG, NodeInfo, EdgeInfo) ->\n case get_work(Work) of\n {{edge, From, To}, Work2} ->\n {NewNodeInfo, NewEdgeInfo, AddWork} = \n\tcalc_later_edge(From, To, CFG, NodeInfo, EdgeInfo),\n Work3 = add_work(Work2, AddWork),\n calc_later_fixpoint(Work3, CFG, NewNodeInfo, NewEdgeInfo);\n {{node, Label}, Work2} ->\n AddWork = calc_later_node(Label, CFG),\n Work3 = add_work(Work2, AddWork),\n calc_later_fixpoint(Work3, CFG, NodeInfo, EdgeInfo);\n fixpoint ->\n {NodeInfo, EdgeInfo}\n end.\n\ncalc_later_node(Label, CFG) ->\n Succs = hipe_rtl_cfg:succ(CFG, Label),\n [{edge, Label, Succ} || Succ <- Succs].\n\ncalc_later_edge(From, To, _CFG, NodeInfo, EdgeInfo) ->\n FromTo = {From, To},\n Earliest = earliest(EdgeInfo, FromTo),\n LaterIn = later_in(NodeInfo, From),\n UpExp = up_exp(NodeInfo, From),\n Later = ?SETS:union(Earliest, ?SETS:subtract(LaterIn, UpExp)),\n {Changed, EdgeInfo2} =\n case lookup_later(EdgeInfo, FromTo) of\n none -> {true, set_later(EdgeInfo, FromTo, Later)};\n Later -> {false, EdgeInfo};\n _Old -> {true, set_later(EdgeInfo, FromTo, Later)}\n end,\n case Changed of \n true ->\n %% Update later in set of To-node\n case lookup_later_in(NodeInfo, To) of\n\t%% If the data isn't set initialize to all expressions\n\tnone ->\n \t {set_later_in(NodeInfo, To, Later), EdgeInfo2, [{node, To}]};\n\tOldLaterIn ->\n\t NewLaterIn = ?SETS:intersection(OldLaterIn, Later),\n\t %% Check if something changed\n\t %% FIXME: Implement faster equality test?\n\t case NewLaterIn =:= OldLaterIn of \n\t true ->\n\t {NodeInfo, EdgeInfo2, []};\n\t false ->\n\t {set_later_in(NodeInfo, To, NewLaterIn),\n\t EdgeInfo2, [{node, To}]}\n\t end\n end;\n false ->\n {NodeInfo, EdgeInfo2, []}\n end.\n\n%%%%%%%%%%%%%%%%%% UPWARDS\/DOWNWARDS EXPOSED EXPRESSIONS %%%%%%%%%%%%%%%%%%%%%%\n%% Calculates upwards and downwards exposed expressions.\n\n%%=============================================================================\n%% Calculates the downwards exposed expression sets for the given labels in\n%% the CFG.\ncalc_down_exp(_, _, NodeInfo, []) ->\n NodeInfo;\ncalc_down_exp(CFG, ExprMap, NodeInfo, [Label|Labels]) ->\n Code = hipe_bb:code(hipe_rtl_cfg:bb(CFG, Label)),\n %% Data = ?SETS:from_list(lists:map(fun expr_clear_dst\/1, exp_work(Code))),\n Data = ?SETS:from_list(get_expr_ids(ExprMap, exp_work(Code))),\n NewNodeInfo = set_down_exp(NodeInfo, Label, Data),\n calc_down_exp(CFG, ExprMap, NewNodeInfo, Labels).\n \n%%=============================================================================\n%% Calculates the upwards exposed expressions sets for the given labels in \n%% the CFG.\ncalc_up_exp(_, _, NodeInfo, []) ->\n NodeInfo;\ncalc_up_exp(CFG, ExprMap, NodeInfo, [Label|Labels]) ->\n BB = hipe_rtl_cfg:bb(CFG, Label),\n RevCode = lists:reverse(hipe_bb:code(BB)),\n Data = ?SETS:from_list(get_expr_ids(ExprMap, exp_work(RevCode))),\n NewNodeInfo = set_up_exp(NodeInfo, Label, Data),\n calc_up_exp(CFG, ExprMap, NewNodeInfo, Labels).\n\n%%=============================================================================\n%% Given a list of expression instructions, gets a list of expression ids\n%% from an expression map.\nget_expr_ids(ExprMap, Instrs) ->\n [expr_map_get_id(ExprMap, expr_clear_dst(I)) || I <- Instrs].\n\n%%=============================================================================\n%% Does the work of the calc_*_exp functions.\nexp_work(Code) ->\n exp_work([], Code).\n\nexp_work([], [Instr|Instrs]) ->\n case is_expr(Instr) of\n true ->\n exp_work([Instr], Instrs);\n false ->\n exp_work([], Instrs)\n end;\nexp_work(Exprs, []) ->\n Exprs;\nexp_work(Exprs, [Instr|Instrs]) ->\n NewExprs = case is_expr(Instr) of\n\t true ->\n\t\t exp_kill_expr(Instr, [Instr|Exprs]);\n\t false ->\n\t\t exp_kill_expr(Instr, Exprs)\n\t end,\n exp_work(NewExprs, Instrs).\n\n%%=============================================================================\n%% Checks if the given instruction redefines any operands of \n%% instructions in the instruction list. \n%% It returns the list of expressions with those instructions that has\n%% operands redefined removed.\nexp_kill_expr(_Instr, []) ->\n [];\nexp_kill_expr(Instr, [CheckedExpr|Exprs]) ->\n %% Calls, gctests and stores potentially clobber everything\n case Instr of\n #call{} -> [];\n #gctest{} -> [];\n #store{} -> []; %% FIXME: Only regs and vars clobbered, not fregs...\n #fstore{} -> \n %% fstore potentially clobber float expressions\n [ExprDefine|_] = hipe_rtl:defines(CheckedExpr),\n case hipe_rtl:is_fpreg(ExprDefine) of\n\ttrue ->\n\t exp_kill_expr(Instr, Exprs);\n\tfalse ->\n\t [CheckedExpr | exp_kill_expr(Instr, Exprs)]\n end;\n _ ->\n InstrDefines = hipe_rtl:defines(Instr),\n ExprUses = hipe_rtl:uses(CheckedExpr),\n Diff = ExprUses -- InstrDefines,\n case length(Diff) < length(ExprUses) of \n\ttrue ->\n\t exp_kill_expr(Instr, Exprs);\n\tfalse ->\n\t [CheckedExpr | exp_kill_expr(Instr, Exprs)]\n end\n end.\n \n%%%%%%%%%%%%%%%%%%%%%%%% KILLED EXPRESSIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Calculates the killed expression sets for all given labels.\ncalc_killed_expr(_, NodeInfo, _, _, _, []) ->\n NodeInfo;\ncalc_killed_expr(CFG, NodeInfo, UseMap, AllExpr, IdMap, [Label|Labels]) ->\n Code = hipe_bb:code(hipe_rtl_cfg:bb(CFG, Label)),\n KilledExprs = calc_killed_expr_bb(Code, UseMap, AllExpr, IdMap, ?SETS:new()),\n NewNodeInfo = set_killed_expr(NodeInfo, Label, KilledExprs),\n calc_killed_expr(CFG, NewNodeInfo, UseMap, AllExpr, IdMap, Labels).\n\n%%=============================================================================\n%% Calculates the killed expressions set for one basic block.\ncalc_killed_expr_bb([], _UseMap, _AllExpr, _IdMap, KilledExprs) ->\n KilledExprs;\ncalc_killed_expr_bb([Instr|Instrs], UseMap, AllExpr, IdMap, KilledExprs) ->\n %% Calls, gctests and stores potentially clobber everything\n case Instr of\n #call{} -> AllExpr;\n #gctest{} -> AllExpr;\n #store{} -> AllExpr; %% FIXME: Only regs and vars clobbered, not fregs...\n #fstore{} -> \n %% Kill all float expressions\n %% FIXME: Make separate function is_fp_expr\n ?SETS:from_list\n\t(lists:foldl(fun(ExprId, Fexprs) ->\n\t\t\t Expr = expr_id_map_get_expr(IdMap, ExprId),\n\t\t\t [Define|_] = hipe_rtl:defines(Expr),\n\t\t\t case hipe_rtl:is_fpreg(Define) of\n\t\t\t true ->\n\t\t\t [Expr|Fexprs];\n\t\t\t false ->\n\t\t\t Fexprs\n\t\t\t end\n\t\t end, [], ?SETS:to_list(AllExpr)));\n _ ->\n case hipe_rtl:defines(Instr) of\n\t[] ->\n\t calc_killed_expr_bb(Instrs, UseMap, AllExpr, IdMap, KilledExprs);\n\t[Define|_] ->\n\t NewKilledExprs = use_map_get_expr_uses(UseMap, Define),\n\t calc_killed_expr_bb(Instrs, UseMap, AllExpr, IdMap,\n\t\t\t ?SETS:union(NewKilledExprs, KilledExprs))\n end\n end.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% EARLIEST %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Calculates the earliest set for all edges in the CFG.\n\ncalc_earliest(_, _, EdgeInfo, []) ->\n EdgeInfo;\ncalc_earliest(CFG, NodeInfo, EdgeInfo, [To|Labels]) ->\n EmptySet = ?SETS:new(),\n Preds = hipe_rtl_cfg:pred(CFG, To),\n NewEdgeInfo =\n case EmptySet =:= antic_in(NodeInfo, To) of\n true ->\n\t%% Earliest is empty for all edges into this block.\n\tlists:foldl(fun(From, EdgeInfoAcc) ->\n\t\t\tset_earliest(EdgeInfoAcc, {From, To}, EmptySet)\n\t\t end, EdgeInfo, Preds);\n false ->\n\tlists:foldl(fun(From, EdgeInfoAcc) ->\n\t\t\tIsStartLabel = (From =:= hipe_rtl_cfg:start_label(CFG)),\n\t\t\tEarliest = \n\t\t\t calc_earliest_edge(NodeInfo, IsStartLabel, From, To),\n\t\t\tset_earliest(EdgeInfoAcc, {From, To}, Earliest)\n\t\t end, EdgeInfo, Preds)\n end,\n calc_earliest(CFG, NodeInfo, NewEdgeInfo, Labels).\n \n%%=============================================================================\n%% Calculates the earliest set for one edge.\n\ncalc_earliest_edge(NodeInfo, IsStartLabel, From, To) ->\n AnticIn = antic_in(NodeInfo, To),\n AvailOut = avail_out(NodeInfo, From),\n \n case IsStartLabel of\n true ->\n ?SETS:subtract(AnticIn, AvailOut);\n false ->\n AnticOut = antic_out(NodeInfo, From),\n ExprKill = killed_expr(NodeInfo, From),\n ?SETS:subtract(?SETS:subtract(AnticIn, AvailOut),\n\t\t ?SETS:subtract(AnticOut, ExprKill))\n end.\n%% The above used to be:\n%%\n%% ?SETS:intersection(?SETS:subtract(AnticIn, AvailOut),\n%% ?SETS:union(ExprKill, ?SETS:subtract(AllExpr, AnticOut)))\n%%\n%% But it is costly to use the AllExpr, so let's do some tricky set algebra.\n%%\n%% Let A = AnticIn, B = AvailOut, C = ExprKill, D = AnticOut, U = AllExpr\n%% Let n = intersection, u = union, ' = inverse\n%%\n%% Then\n%% (A - B) n (C u (U - D)) = \n%% = (A - B) n ((C u U) - (D - C)) = \n%% = (A - B) n (U - (D - C)) = \n%% = (A - B) n (D - C)' = \n%% = (A - B) - (D - C) \n%%\n%% or in other words\n%% ?SETS:subtract(?SETS:subtract(AnticIn, AvailOut),\n%% ?SETS:subtract(AnticOut, ExprKill))\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%% INSERT \/ DELETE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Calculates the insert set for one edge and returns the resulting set.\n%% NOTE This does not modify the EdgeInfo set, since the resulting set is \n%% returned and used immediately, instead of being pre-calculated as are \n%% the other sets.\ncalc_insert_edge(NodeInfo, EdgeInfo, From, To) ->\n Later = later(EdgeInfo, {From, To}),\n LaterIn = later_in(NodeInfo, To),\t \n ?SETS:subtract(Later, LaterIn).\n\n%%=============================================================================\n%% Calculates the delete set for all given labels in a CFG.\ncalc_delete(_, NodeInfo, []) ->\n NodeInfo;\ncalc_delete(CFG, NodeInfo, [Label|Labels]) ->\n NewNodeInfo =\n case Label =:= hipe_rtl_cfg:start_label(CFG) of\n true ->\n\tset_delete(NodeInfo, Label, ?SETS:new());\n false ->\n\tUpExp = up_exp(NodeInfo, Label),\n\tLaterIn = later_in(NodeInfo, Label),\n\tDelete = ?SETS:subtract(UpExp, LaterIn),\n\tset_delete(NodeInfo, Label, Delete)\n end,\n calc_delete(CFG, NewNodeInfo, Labels).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%% FIXPOINT FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Worklist used by the fixpoint calculations.\n%% \n%% We use gb_sets here, which is optimized for continuous inserts and\n%% membership tests.\n\ninit_work(Labels) ->\n {Labels, [], gb_sets:from_list(Labels)}.\n\nget_work({[Label|Left], List, Set}) ->\n NewWork = {Left, List, gb_sets:delete(Label, Set)},\n {Label, NewWork};\nget_work({[], [], _Set}) ->\n fixpoint;\nget_work({[], List, Set}) ->\n get_work({lists:reverse(List), [], Set}).\n\nadd_work(Work = {List1, List2, Set}, [Label|Labels]) ->\n case gb_sets:is_member(Label, Set) of\n true ->\n add_work(Work, Labels);\n false ->\n %%io:format(\"Adding work: ~w\\n\", [Label]),\n add_work({List1, [Label|List2], gb_sets:insert(Label, Set)}, Labels)\n end;\nadd_work(Work, []) ->\n Work.\n\n%%=============================================================================\n%% Calculates the labels that are the exit labels.\n%% FIXME We do not detect dead-end loops spanning more than one block.\n%% This could potentially cause a bug in the future...\n%% exit_labels(CFG) ->\n%% Labels = hipe_rtl_cfg:labels(CFG),\n%% lists:foldl(fun(Label, ExitLabels) ->\n%% Succs = hipe_rtl_cfg:succ(CFG, Label),\n%% case Succs of\n%% \t\t [] ->\n%% [Label|ExitLabels];\n%% \t\t [Label] -> %% Count single bb dead-end loops as exit labels\n%% [Label|ExitLabels];\t\t \n%% _ ->\n%% ExitLabels\n%% end\n%% end, [], Labels ).\n\n%%=============================================================================\n%% Return true if label is an exit label,\n%% i.e. its bb has no successors or itself as only successor.\nis_exit_label(CFG, Label) ->\n case hipe_rtl_cfg:succ(CFG, Label) of\n [] -> true;\n [Label] -> true;\n _ -> false\n end.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%% DATASET FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% The dataset is a collection of data about the CFG. \n%% It is divided into two parts, NodeInfo and EdgeInfo.\n%% The pre-calculation step stores the calculated sets here.\n\n-record(node_data, {up_exp = none,\n\t\t down_exp = none,\n\t\t killed_expr = none,\n\t\t avail_in = none,\n\t\t avail_out = none,\n\t\t antic_in = none,\n\t\t antic_out = none,\n\t\t later_in = none,\n\t\t delete = none}).\n\n-record(edge_data, {earliest = none,\n\t\t later = none,\n\t\t insert = none}).\n\n%%=============================================================================\n%% Creates a node info from a CFG (one entry for each Label).\nmk_node_info(Labels) ->\n lists:foldl(fun(Label, DataTree) ->\n\t\t gb_trees:insert(Label, #node_data{}, DataTree)\n\t\t %%gb_trees:enter(Label, #node_data{}, DataTree)\n\t end, \n\t gb_trees:empty(), Labels).\n\n%%mk_edge_info(Labels) ->\n%% FIXME Should we traverse cfg and initialize edges?\nmk_edge_info() ->\n gb_trees:empty().\n\n%%=============================================================================\n%% Get methods\nup_exp(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.up_exp.\n\ndown_exp(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.down_exp.\n\nkilled_expr(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.killed_expr.\n\navail_in(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.avail_in.\n\navail_out(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.avail_out.\n\nantic_in(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.antic_in.\n\nantic_out(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.antic_out.\n\nlater_in(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.later_in.\n\nlookup_later_in(NodeInfo, Label) ->\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n none;\n {value, #node_data{later_in = Data}} ->\n Data\n end.\n\ndelete(NodeInfo, Label) ->\n Data = gb_trees:get(Label, NodeInfo),\n Data#node_data.delete.\n\nearliest(EdgeInfo, Edge) ->\n Data = gb_trees:get(Edge, EdgeInfo),\n Data#edge_data.earliest.\n\n-ifdef(LOOKUP_EARLIEST_NEEDED).\nlookup_earliest(EdgeInfo, Edge) ->\n case gb_trees:lookup(Edge, EdgeInfo) of\n none -> \n none;\n {value, #edge_data{earliest = Data}} ->\n Data\n end.\n-endif.\n\nlater(EdgeInfo, Edge) ->\n Data = gb_trees:get(Edge, EdgeInfo),\n Data#edge_data.later.\n\nlookup_later(EdgeInfo, Edge) ->\n case gb_trees:lookup(Edge, EdgeInfo) of\n none -> \n none;\n {value, #edge_data{later = Data}} ->\n Data\n end.\n\n%% insert(EdgeInfo, Edge) ->\n%% case gb_trees:lookup(Edge, EdgeInfo) of\n%% none -> \n%% exit({?MODULE, insert, \"edge info not found\"}),\n%% none;\n%% {value, #edge_data{insert = Data}} ->\n%% Data\n%% end.\n\n%%=============================================================================\n%% Set methods\nset_up_exp(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{up_exp = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{up_exp = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_down_exp(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{down_exp = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{down_exp = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_killed_expr(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{killed_expr = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{killed_expr = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_avail_in(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{avail_in = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{avail_in = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_avail_out(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{avail_out = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{avail_out = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_antic_in(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{antic_in = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{antic_in = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_antic_out(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{antic_out = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{antic_out = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_later_in(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{later_in = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{later_in = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_delete(NodeInfo, Label, Data) ->\n NodeData =\n case gb_trees:lookup(Label, NodeInfo) of\n none -> \n\t#node_data{delete = Data};\n {value, OldNodeData} ->\n\tOldNodeData#node_data{delete = Data}\n end,\n gb_trees:enter(Label, NodeData, NodeInfo).\n\nset_earliest(EdgeInfo, Edge, Data) ->\n EdgeData =\n case gb_trees:lookup(Edge, EdgeInfo) of\n none -> \n\t#edge_data{earliest = Data};\n {value, OldEdgeData} ->\n\tOldEdgeData#edge_data{earliest = Data}\n end,\n gb_trees:enter(Edge, EdgeData, EdgeInfo).\n\nset_later(EdgeInfo, Edge, Data) ->\n EdgeData =\n case gb_trees:lookup(Edge, EdgeInfo) of\n none -> \n\t#edge_data{later = Data};\n {value, OldEdgeData} ->\n\tOldEdgeData#edge_data{later = Data}\n end,\n gb_trees:enter(Edge, EdgeData, EdgeInfo).\n\n%% set_insert(EdgeInfo, Edge, Data) ->\n%% EdgeData =\n%% case gb_trees:lookup(Edge, EdgeInfo) of\n%% none -> \n%% \t#edge_data{insert = Data};\n%% {value, OldEdgeData} ->\n%% \tOldEdgeData#edge_data{insert = Data}\n%% end,\n%% gb_trees:enter(Edge, EdgeData, EdgeInfo).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% USE MAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% The use map is a mapping from \"use\" (which is an rtl register\/variable) \n%% to a set of expressions (IDs) where that register\/variable is used.\n%% It is used by calc_killed_expr to know what expressions are affected by\n%% a definition.\n\n%%=============================================================================\n%% Creates and calculates the use map for a CFG.\n%% It uses ExprMap to lookup the expression IDs.\nmk_use_map(CFG, ExprMap) ->\n Labels = hipe_rtl_cfg:reverse_postorder(CFG),\n NewMap = mk_use_map(gb_trees:empty(), CFG, ExprMap, Labels),\n gb_trees:balance(NewMap).\n\nmk_use_map(Map, _, _, []) ->\n Map;\nmk_use_map(Map, CFG, ExprMap, [Label|Labels]) ->\n Code = hipe_bb:code(hipe_rtl_cfg:bb(CFG, Label)),\n NewMap = mk_use_map_bb(Map, ExprMap, Code),\n mk_use_map(NewMap, CFG, ExprMap, Labels).\n\nmk_use_map_bb(UseMap, _, []) ->\n UseMap;\nmk_use_map_bb(UseMap, ExprMap, [Instr|Instrs]) ->\n case is_expr(Instr) of\n true ->\n Uses = hipe_rtl:uses(Instr),\n ExprId = expr_map_get_id(ExprMap, expr_clear_dst(Instr)),\n NewUseMap = mk_use_map_insert_uses(UseMap, ExprId, Uses),\n mk_use_map_bb(NewUseMap, ExprMap, Instrs);\n false ->\n mk_use_map_bb(UseMap, ExprMap, Instrs)\n end.\n\n%%=============================================================================\n%% Worker function for mk_use_map that inserts the expression id for every \n%% rtl register the expression uses in a use map.\nmk_use_map_insert_uses(Map, _, []) ->\n Map;\nmk_use_map_insert_uses(Map, Expr, [Use|Uses]) ->\n case gb_trees:lookup(Use, Map) of\n {value, UseSet} ->\n NewUseSet = ?SETS:add_element(Expr, UseSet),\n mk_use_map_insert_uses(gb_trees:update(Use, NewUseSet, Map), Expr, Uses);\n none ->\n UseSet = ?SETS:new(),\n NewUseSet = ?SETS:add_element(Expr, UseSet),\n mk_use_map_insert_uses(gb_trees:insert(Use, NewUseSet, Map), Expr, Uses)\n end.\n\n%%=============================================================================\n%% Gets a set of expressions where the given rtl register is used.\nuse_map_get_expr_uses(Map, Reg) ->\n case gb_trees:lookup(Reg, Map) of\n {value, UseSet} ->\n UseSet;\n none ->\n ?SETS:new()\n end. \n\n%%%%%%%%%%%%%%%%%%%%%% EXPRESSION MAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% The expression map is a mapping from expression to \n%% (1) Expression Id (Integer used to speed up set operations)\n%% (2) List of definitions (labels where the expression is defined and the \n%% list of registers or variables defined by an instruction in that label,\n%% represented as a tuple {Label, Defines})\n%% (3) The list of replacement registers created for the expression\n\n%%=============================================================================\n%% Creates and calculates the expression map for a CFG.\nmk_expr_map(CFG) ->\n init_expr_id(),\n Labels = hipe_rtl_cfg:reverse_postorder(CFG),\n {ExprMap, IdMap} = mk_expr_map(gb_trees:empty(), gb_trees:empty(), \n\t\t\t\t CFG, Labels),\n {gb_trees:balance(ExprMap), gb_trees:balance(IdMap)}.\n\nmk_expr_map(ExprMap, IdMap, _, []) ->\n {ExprMap, IdMap};\nmk_expr_map(ExprMap, IdMap, CFG, [Label|Labels]) ->\n Code = hipe_bb:code(hipe_rtl_cfg:bb(CFG, Label)),\n {NewExprMap, NewIdMap} = mk_expr_map_bb(ExprMap, IdMap, Label, Code),\n mk_expr_map(NewExprMap, NewIdMap, CFG, Labels).\n\nmk_expr_map_bb(ExprMap, IdMap, _, []) ->\n {ExprMap, IdMap};\nmk_expr_map_bb(ExprMap, IdMap, Label, [Instr|Instrs]) ->\n case is_expr(Instr) of\n true ->\n Expr = expr_clear_dst(Instr),\n Defines = hipe_rtl:defines(Instr),\n case gb_trees:lookup(Expr, ExprMap) of\n {value, {ExprId, DefinesList, ReplRegs}} ->\n NewExprMap = gb_trees:update(Expr, {ExprId, \n\t\t\t\t\t [{Label, Defines}|DefinesList], \n\t\t\t\t\t ReplRegs}, ExprMap),\n\t mk_expr_map_bb(NewExprMap, IdMap, Label, Instrs);\n none ->\n\t NewExprId = new_expr_id(),\n NewReplRegs = mk_replacement_regs(Defines),\n NewExprMap = gb_trees:insert(Expr, {NewExprId, \n\t\t\t\t\t [{Label, Defines}], \n\t\t\t\t\t NewReplRegs}, ExprMap),\n NewIdMap = gb_trees:insert(NewExprId, Expr, IdMap),\n\t mk_expr_map_bb(NewExprMap, NewIdMap, Label, Instrs)\n end;\n false ->\n mk_expr_map_bb(ExprMap, IdMap, Label, Instrs)\n end.\n\n%%=============================================================================\n%% Creates new temporaries to replace defines in moved expressions.\nmk_replacement_regs([]) ->\n [];\nmk_replacement_regs(Defines) ->\n mk_replacement_regs(Defines, []).\n\nmk_replacement_regs([], NewRegs) ->\n lists:reverse(NewRegs);\nmk_replacement_regs([Define|Defines], NewRegs) ->\n case hipe_rtl:is_reg(Define) of\n true ->\n NewReg =\n\tcase hipe_rtl:reg_is_gcsafe(Define) of\n\t true -> hipe_rtl:mk_new_reg_gcsafe();\n\t false -> hipe_rtl:mk_new_reg()\n\tend,\n mk_replacement_regs(Defines, [NewReg|NewRegs]);\n false ->\n case hipe_rtl:is_var(Define) of\n\ttrue ->\n\t mk_replacement_regs(Defines, [hipe_rtl:mk_new_var()|NewRegs]);\n\tfalse ->\n\t true = hipe_rtl:is_fpreg(Define),\n\t mk_replacement_regs(Defines, [hipe_rtl:mk_new_fpreg()|NewRegs])\n end\n end.\n \n%%=============================================================================\n%% Performs a lookup, which returns a tuple\n%% {expression ID, list of definitions, list of replacement registers}\nexpr_map_lookup(Map, Expr) ->\n gb_trees:lookup(Expr, Map).\n\n%%=============================================================================\n%% Gets the actual RTL instruction to be generated for insertions of an \n%% expression.\nexpr_map_get_instr(Map, Expr) ->\n case gb_trees:lookup(Expr, Map) of\n {value, {_, _, Regs}} ->\n expr_set_dst(Expr, Regs);\n none ->\n exit({?MODULE, expr_map_get_instr, \"expression missing\"})\n end.\n\n%%=============================================================================\n%% Gets expression id.\nexpr_map_get_id(Map, Expr) ->\n case gb_trees:lookup(Expr, Map) of\n {value, {ExprId, _, _}} ->\n ExprId;\n none ->\n exit({?MODULE, expr_map_get_instr, \"expression missing\"})\n end.\n\n%%=============================================================================\n%% Creates an rtl instruction that moves a value\nmk_expr_move_instr([Reg], [Define]) ->\n case hipe_rtl:is_fpreg(Reg) of\n true ->\n hipe_rtl:mk_fmove(Reg, Define);\n false ->\n %% FIXME Check is_var() orelse is_reg() ?\n hipe_rtl:mk_move(Reg, Define)\n end;\nmk_expr_move_instr([_Reg|_Regs] = RegList, Defines) ->\n %% FIXME Does this really work? What about floats...\n %% (Multiple defines does not seem to be used by any of the \n %% instructions considered by rtl_lcm at the moment so this is pretty much\n %% untested\/unused.)\n hipe_rtl:mk_multimove(RegList, Defines);\nmk_expr_move_instr(_, []) ->\n exit({?MODULE, mk_expr_move_instr, \"bad match\"}).\n\n%%=============================================================================\n%% Returns a set of all expressions in the code.\n%% all_exprs(_CFG, []) ->\n%% ?SETS:new();\n%% all_exprs(CFG, [Label|Labels]) ->\n%% BB = hipe_rtl_cfg:bb(CFG, Label),\n%% Code = hipe_bb:code(BB),\n%% ?SETS:union(all_exprs_bb(Code),\n%% \t all_exprs(CFG, Labels)).\n\n%%=============================================================================\n%% Returns a set of expressions in a basic block.\n%% all_exprs_bb([]) ->\n%% ?SETS:new();\n%% all_exprs_bb([Instr|Instrs]) ->\n%% case is_expr(Instr) of\n%% true ->\n%% Expr = expr_clear_dst(Instr),\n%% ExprSet = all_exprs_bb(Instrs),\n%% ?SETS:add_element(Expr, ExprSet);\n%% false ->\n%% all_exprs_bb(Instrs)\n%% end.\n\n%%%%%%%%%%%%%%%%%% EXPRESSION ID -> EXPRESSION MAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Map from expression IDs to expressions.\n%%=============================================================================\n%% mk_expr_id_map() ->\n%% gb_trees:empty().\n\n%% expr_id_map_insert(Map, ExprId, Expr) ->\n%% gb_trees:insert(ExprId, Expr, Map).\n\n%% expr_id_map_lookup(Map, ExprId) ->\n%% gb_trees:lookup(ExprId, Map).\n\n%%=============================================================================\n%% Given expression id, gets expression.\nexpr_id_map_get_expr(Map, ExprId) ->\n case gb_trees:lookup(ExprId, Map) of\n {value, Expr} ->\n Expr;\n none ->\n exit({?MODULE, expr_id_map_get_expr, \"expression id missing\"})\n end.\n\n%%=============================================================================\n%% Expression ID counter\ninit_expr_id() ->\n put({rtl_lcm,expr_id_count}, 0),\n ok.\n\n-spec new_expr_id() -> non_neg_integer().\nnew_expr_id() ->\n Obj = {rtl_lcm, expr_id_count},\n V = get(Obj),\n put(Obj, V+1),\n V.\n\n%%%%%%%%%%%%%%%%%% EDGE BB (INSERT BETWEEN) MAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Map from edges to labels.\n%% This is used by insert_expr_between to remember what new bbs it has created\n%% for insertions on edges, and thus for multiple insertions on the same edge\n%% to end up in the same bb.\n%%=============================================================================\nmk_edge_bb_map() ->\n gb_trees:empty().\n\nedge_bb_map_insert(Map, Edge, Label) ->\n gb_trees:enter(Edge, Label, Map).\n\nedge_bb_map_lookup(Map, Edge) ->\n gb_trees:lookup(Edge, Map).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PRETTY-PRINTING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%=============================================================================\n%% Prints debug messages.\n-ifdef(LCM_DEBUG).\n\npp_debug(Str, Args) ->\n case ?LCM_DEBUG of\n true ->\n io:format(standard_io, Str, Args);\n false ->\n ok\n end.\n\npp_debug_instr(Instr) ->\n case ?LCM_DEBUG of\n true ->\n hipe_rtl:pp_instr(standard_io, Instr);\n false ->\n ok\n end.\n\n-else.\n\npp_debug(_, _) -> \n ok.\n\npp_debug_instr(_) -> \n ok.\n\n-endif.\t%% DEBUG\n\n%%=============================================================================\n%% Pretty-prints the calculated sets for the lazy code motion.\npp_sets(_, _, _, _, _, _, []) ->\n ok; \npp_sets(ExprMap, IdMap, NodeInfo, EdgeInfo, AllExpr, CFG, [Label|Labels]) ->\n Preds = hipe_rtl_cfg:pred(CFG, Label),\n Succs = hipe_rtl_cfg:succ(CFG, Label),\n\n io:format(standard_io, \"Label ~w~n\", [Label]),\n io:format(standard_io, \" Preds: ~w~n\", [Preds]),\n io:format(standard_io, \" Succs: ~w~n\", [Succs]),\n\n case up_exp(NodeInfo, Label) of\n none -> ok;\n UpExp -> \n case ?SETS:size(UpExp) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" UEExpr: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(UpExp));\n\ttrue -> ok\n end\n end,\n case down_exp(NodeInfo, Label) of\n none -> ok;\n DownExp -> \n case ?SETS:size(DownExp) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" DEExpr: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(DownExp));\n\ttrue -> ok\n end\n end,\n case killed_expr(NodeInfo, Label) of\n none -> ok;\n KilledExpr -> \n case ?SETS:size(KilledExpr) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" ExprKill: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(KilledExpr));\n\ttrue -> ok\n end\n end,\n case avail_in(NodeInfo, Label) of\n none -> ok;\n AvailIn ->\n case ?SETS:size(AvailIn) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" AvailIn: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(AvailIn));\n\ttrue -> ok\n end\n end,\n case avail_out(NodeInfo, Label) of\n none -> ok;\n AvailOut ->\n case ?SETS:size(AvailOut) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" AvailOut: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(AvailOut));\n\ttrue -> ok\n end\n end,\n case antic_in(NodeInfo, Label) of\n none -> ok;\n AnticIn ->\n case ?SETS:size(AnticIn) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" AnticIn: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(AnticIn));\n\ttrue -> ok\n end\n end,\n case antic_out(NodeInfo, Label) of\n none -> ok;\n AnticOut ->\n case ?SETS:size(AnticOut) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" AnticOut: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(AnticOut));\n\ttrue -> ok\n end\n end,\n case later_in(NodeInfo, Label) of\n none -> ok;\n LaterIn ->\n case ?SETS:size(LaterIn) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" LaterIn: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(LaterIn));\n\ttrue -> ok\n end\n end, \n\n pp_earliest(ExprMap, IdMap, EdgeInfo, Label, Succs),\n pp_later(ExprMap, IdMap, EdgeInfo, Label, Succs),\n\n case delete(NodeInfo, Label) of\n none -> ok;\n Delete ->\n case ?SETS:size(Delete) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" Delete: ~n\", []),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(Delete));\n\ttrue -> ok\n end\n end,\n pp_sets(ExprMap, IdMap, NodeInfo, EdgeInfo, AllExpr, CFG, Labels).\n\n%%=============================================================================\n%% Pretty-prints the later set.\npp_later(_, _, _, _, []) ->\n ok;\npp_later(ExprMap, IdMap, EdgeInfo, Pred, [Succ|Succs]) ->\n case later(EdgeInfo, {Pred, Succ}) of\n none -> ok;\n Later ->\n case ?SETS:size(Later) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" Later(~w->~w): ~n\", [Pred,Succ]),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(Later));\n\ttrue -> ok\n end\n end,\n pp_later(ExprMap, IdMap, EdgeInfo, Pred, Succs).\n\n%%=============================================================================\n%% Pretty-prints the earliest set.\npp_earliest(_, _, _, _, []) ->\n ok;\npp_earliest(ExprMap, IdMap, EdgeInfo, Pred, [Succ|Succs]) ->\n case earliest(EdgeInfo, {Pred, Succ}) of\n none -> ok;\n Earliest ->\n case ?SETS:size(Earliest) =:= 0 of\n\tfalse ->\n\t io:format(standard_io, \" Earliest(~w->~w): ~n\", [Pred,Succ]),\n\t pp_exprs(ExprMap, IdMap, ?SETS:to_list(Earliest));\n\ttrue -> ok\n end\n end,\n pp_earliest(ExprMap, IdMap, EdgeInfo, Pred, Succs).\n\n%%=============================================================================\n%% Pretty-prints an expression\npp_expr(ExprMap, IdMap, ExprId) ->\n Expr = expr_id_map_get_expr(IdMap, ExprId),\n hipe_rtl:pp_instr(standard_io, expr_map_get_instr(ExprMap, Expr)).\n\npp_exprs(_, _, []) ->\n ok;\npp_exprs(ExprMap, IdMap, [E|Es]) ->\n pp_expr(ExprMap, IdMap, E),\n pp_exprs(ExprMap, IdMap, Es).\n","avg_line_length":34.6517647059,"max_line_length":84,"alphanum_fraction":0.5742853263} +{"size":6672,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Copyright (c) 2020 Anatoly Rodionov. All Rights Reserved.\r\n%%\r\n%% This file is provided to you under the Apache License,\r\n%% Version 2.0 (the \"License\"); you may not use this file\r\n%% except in compliance with the License. You may obtain\r\n%% a copy of the License at\r\n%%\r\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n%%\r\n%% Unless required by applicable law or agreed to in writing,\r\n%% software distributed under the License is distributed on an\r\n%% \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n%% KIND, either express or implied. See the License for the\r\n%% specific language governing permissions and limitations\r\n%% under the License.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%%% \r\n%%% @author Anatoly Rodionov \r\n%%% @copyright 2020 Anatoly Rodionov\r\n%%%\r\n%%% @doc Pruning algorithm in Erlang\r\n%%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%-------------------------------------------------------------------------------------------------\r\n\r\n-module(lstree).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n\r\n-export([from_list\/1, from_list\/2, to_list\/1]).\r\n-export([min\/1, max\/1]).\r\n-export([min_max\/1, max_min\/1]).\r\n-export([min_max_p\/1, max_min_p\/1]).\r\n-export([map\/2, map\/3, map\/4]).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n\r\n-define(ALPHA_MAX, 16#7FFFFFFFFFFFFFF). % Erlang max integer (60 bit)\r\n-define(BETA_MIN, -?ALPHA_MAX).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n\r\n-record(lsnode,{\r\n\tlevel = 0 :: non_neg_integer(),\r\n\tscore = false :: integer() | false,\r\n\tchildren = [] :: [lsnode()] \r\n\t}).\r\n-type lsnode() :: #lsnode{}. \r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec from_list([number()] | number()) -> lsnode().\r\n\r\nfrom_list(Arg) -> ?MODULE:from_list(Arg, 0).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec from_list([number()] | number(), non_neg_integer()) -> lsnode().\r\n\r\nfrom_list(S, L) when is_list(S) -> \r\n\t#lsnode{children = [?MODULE:from_list(A, L + 1) || A <- S], level = L};\r\nfrom_list(S, L) when is_number(S) -> #lsnode{score = S, level = L}.\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec to_list(lsnode()) -> [term()].\r\n\r\nto_list(Anode) when Anode#lsnode.children == [] -> Anode#lsnode.score;\r\nto_list(Anode) -> [?MODULE:to_list(A) || A <- Anode#lsnode.children].\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec max(lsnode() | [number()]) -> integer().\r\n\r\nmax(A) when is_list(A) -> ?MODULE:max(?MODULE:from_list(A));\r\nmax(A) -> ?MODULE:map(A, fun lists:max\/1).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec min(lsnode() | [number()]) -> integer().\r\n\r\nmin(A) when is_list(A) -> ?MODULE:min(?MODULE:from_list(A));\r\nmin(A) -> ?MODULE:map(A, fun lists:min\/1).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec max_min(lsnode() | [number()]) -> integer().\r\n\r\nmax_min(A) when is_list(A) -> ?MODULE:max_min(?MODULE:from_list(A));\r\nmax_min(A) -> ?MODULE:map(A, fun lists:max\/1, fun lists:min\/1).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec min_max(lsnode() | [number()]) -> integer().\r\n\r\nmin_max(A) when is_list(A) -> ?MODULE:min_max(?MODULE:from_list(A));\r\nmin_max(A) -> ?MODULE:map(A, fun lists:min\/1, fun lists:max\/1).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec max_min_p(lsnode() | [number()]) -> integer().\r\n\r\nmax_min_p(A) when is_list(A) -> max_min_p(?MODULE:from_list(A));\r\nmax_min_p(A) -> ?MODULE:map(A, fun pmax\/3, fun pmin\/3, {?BETA_MIN, ?ALPHA_MAX}).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec min_max_p(lsnode() | [number()]) -> integer().\r\n\r\nmin_max_p(A) when is_list(A) -> min_max_p(?MODULE:from_list(A));\r\nmin_max_p(A) -> ?MODULE:map(A, fun pmin\/3, fun pmax\/3, {?BETA_MIN, ?ALPHA_MAX}).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec map(lsnode(), fun()) -> integer() | [integer()].\r\n\r\nmap(Anode, _Fn) when Anode#lsnode.children == [] -> Anode#lsnode.score;\r\nmap(Anode, Fn) -> Fn([?MODULE:map(A, Fn) || A <- Anode#lsnode.children]).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec map(lsnode(), fun(), fun()) -> integer() | [integer()].\r\n\r\nmap(Anode, _Fa, _Fb) when Anode#lsnode.children == [] -> Anode#lsnode.score;\r\nmap(Anode, Fa, Fb) -> Fa([?MODULE:map(A, Fb, Fa) || A <- Anode#lsnode.children]).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec map(lsnode(), fun(), fun(), {number(), number()}) -> integer() | [integer()].\r\n\r\nmap(Anode, _Fa, _Fb, _) when Anode#lsnode.children == [] -> Anode#lsnode.score;\r\nmap(Anode, Fa, Fb, {Alpha, Beta}) -> \r\n\tFa( fun(N, {A, B}) -> ?MODULE:map(N, Fb, Fa, {A, B}) end,\r\n\t\t{Alpha, Beta},\r\n\t\tAnode#lsnode.children).\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec pmax(fun(), {number(), number()}, [lsnode()]) -> number().\r\npmax(F, {AL, BE}, Lst) -> pmax(F, {AL, BE}, Lst, ?BETA_MIN). \r\n\r\n-spec pmax(fun(), {number(), number()}, [lsnode()], number()) -> number().\r\npmax(_F, _, [], X) -> X;\r\npmax(F, {Al, Be}, [N | Tail], X) -> \r\n\tA = erlang:max(F(N, {Al, Be}), X),\r\n\tcase A < Be of\r\n\t\ttrue -> pmax(F, {A, Be}, Tail, A);\r\n\t\tfalse -> A % pruning\r\n\tend.\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n-spec pmin(fun(), {number(), number()}, [lsnode()]) -> number().\r\npmin(F, {AL, BE}, Lst) -> pmin(F, {AL, BE}, Lst, ?ALPHA_MAX). \r\n\r\n-spec pmin(fun(), {number(), number()}, [lsnode()], number()) -> number().\r\npmin(_F, _, [], X) -> X;\r\npmin(F, {Al, Be}, [N | Tail], X) -> \r\n\tB = erlang:min(F(N, {Al, Be}), X),\r\n\tcase Al < B of\r\n\t\ttrue -> pmin(F, {Al, B}, Tail, B);\r\n\t\tfalse -> B % pruning\r\n\tend.\r\n\r\n%-------------------------------------------------------------------------------------------------\r\n","avg_line_length":43.8947368421,"max_line_length":178,"alphanum_fraction":0.4054256595} +{"size":1600,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% @author Kevin Smith \n%% @copyright 2009-2010 Basho Technologies\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n%% @ doc This module is the entry point to start erlang_js as an OTP application.\n-module(erlang_perl).\n\n-behaviour(application).\n\n%% Application callbacks\n-export([start\/0, start\/2, stop\/1]).\n\n\n%% @spec start() -> ok | {error, any()}\n%% @doc Starts the erlang_perl OTP application and all\n%% dependencies. Intended for use with the Erlang VM's\n%% -s option\nstart() ->\n start_deps([sasl]),\n application:start(erlang_perl).\n\n%% @private\nstart(_StartType, _StartArgs) ->\n erlang_perl_sup:start_link().\n\n%% @private\nstop(_State) ->\n ok.\n\n%% Internal functions\nstart_deps([]) ->\n ok;\nstart_deps([App|T]) ->\n case is_running(App, application:which_applications()) of\n false ->\n ok = application:start(App);\n true ->\n ok\n end,\n start_deps(T).\n\nis_running(_App, []) ->\n false;\nis_running(App, [{App, _, _}|_]) ->\n true;\nis_running(App, [_|T]) ->\n is_running(App, T).\n","avg_line_length":27.1186440678,"max_line_length":81,"alphanum_fraction":0.664375} +{"size":398,"ext":"erl","lang":"Erlang","max_stars_count":3.0,"content":"-module(arithmetic_tests).\n-include_lib(\"eunit\/include\/eunit.hrl\").\n\nexpn_test() ->\n P = fun arithmetic:expn\/1,\n Inp = \"2+(4-1)*3\",\n ?assertMatch(\n [ {{add,{num,2},{mul,{sub,{num,4},{num,1}},{num,3}}}, \"\"},\n {{add,{num,2},{sub,{num,4},{num,1}}}, \"*3\"},\n {{num,2}, \"+(4-1)*3\"}\n ],\n P(Inp)),\n ok.\n\n","avg_line_length":26.5333333333,"max_line_length":72,"alphanum_fraction":0.391959799} +{"size":21446,"ext":"erl","lang":"Erlang","max_stars_count":8238.0,"content":"%%\n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2003-2016. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%%\n\n%% Description : Helper module to xmerl_xpath: XPATH predicates.\n\n-module(xmerl_xpath_pred).\n\n%% API\n-export([eval\/2]).\n\n\n%% internal functions (called via apply\/3)\n-export([boolean\/1, boolean\/2,\n\t ceiling\/2,\n\t concat\/2,\n\t contains\/2,\n\t count\/2,\n\t floor\/2,\n\t fn_false\/2,\n\t fn_not\/2,\n\t fn_true\/2,\n\t id\/2,\n\t lang\/2,\n\t last\/2,\n\t 'local-name'\/2,\n\t 'namespace-uri'\/2,\n\t name\/2,\n\t string\/2,\n\t nodeset\/1,\n\t 'normalize-space'\/2,\n\t number\/1, number\/2,\n\t position\/2,\n\t round\/2,\n\t 'starts-with'\/2,\n\t string\/1,\n\t 'string-length'\/2,\n\t substring\/2,\n\t 'substring-after'\/2,\n\t 'substring-before'\/2,\n\t sum\/2,\n\t translate\/2]).\n-export([core_function\/1]).\t \n\n-include(\"xmerl.hrl\").\n-include(\"xmerl_internal.hrl\").\n-include(\"xmerl_xpath.hrl\").\n\n%% -record(obj, {type,\n%% \t value}).\n\n\n-define(string(X), #xmlObj{type = string,\n\t\t\t value = X}).\n-define(nodeset(X), #xmlObj{type = nodeset,\n\t\t\t value = X}).\n-define(number(X), #xmlObj{type = number,\n\t\t\t value = X}).\n-define(boolean(X), #xmlObj{type = boolean,\n\t\t\t value = X}).\n\n\n\n\neval(Expr, C = #xmlContext{context_node = #xmlNode{pos = Pos}}) ->\n Obj = expr(Expr, C),\n Res = case Obj#xmlObj.type of\n\t number when Obj#xmlObj.value == Pos ->\n\t\t true;\n\t number ->\n\t\t false;\n\t boolean ->\n\t\t Obj#xmlObj.value;\n\t _ ->\n\t\t mk_boolean(C, Obj)\n\t end,\n% ?dbg(\"eval(~p, ~p) -> ~p~n\", [Expr, Pos, Res]),\n Res.\n\n\nstring(X) ->\n ?string(X).\n\nnodeset(X) -> \n ?nodeset(X).\n\nnumber(X) ->\n ?number(X).\n\nboolean(X) ->\n ?boolean(X).\n\n\nexpr({arith, Op, E1, E2}, C) ->\n arith_expr(Op, E1, E2, C);\nexpr({comp, Op, E1, E2}, C) ->\n comp_expr(Op, E1, E2, C);\nexpr({bool, Op, E1, E2}, C) ->\n bool_expr(Op, E1, E2, C);\nexpr({'negative', E}, C) ->\n N = mk_number(C, E),\n - N;\nexpr({number, N}, _C) ->\n ?number(N);\nexpr({literal, S}, _C) ->\n ?string(S);\nexpr({function_call, F, Args}, C) ->\n case core_function(F) of\n\t{true, F1} ->\n\t ?MODULE:F1(C, Args);\n\ttrue ->\n\t ?MODULE:F(C, Args);\n\tfalse ->\n\t %% here, we should look up the function in the context provided \n\t %% by the caller, but we haven't figured this out yet.\n\t exit({not_a_core_function, F})\n end;\nexpr({path, Type, PathExpr}, C) ->\n #state{context=#xmlContext{nodeset = NS}} =\n\txmerl_xpath:eval_path(Type, PathExpr, C),\n ?nodeset(NS);\nexpr(Expr, _C) ->\n exit({unknown_expr, Expr}).\n\n\narith_expr('+', E1, E2, C) ->\n ?number(mk_number(C, E1) + mk_number(C, E2));\narith_expr('-', E1, E2, C) ->\n ?number(mk_number(C, E1) - mk_number(C, E2));\narith_expr('*', E1, E2, C) ->\n ?number(mk_number(C, E1) * mk_number(C, E2));\narith_expr('div', E1, E2, C) ->\n ?number(mk_number(C, E1) \/ mk_number(C, E2));\narith_expr('mod', E1, E2, C) ->\n ?number(mk_number(C, E1) rem mk_number(C, E2)).\n\ncomp_expr('>', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_ineq_format(N1,N2,C) > compare_ineq_format(N2,N1,C));\ncomp_expr('<', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_ineq_format(N1,N2,C) > compare_ineq_format(N2,N1,C));\ncomp_expr('>=', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_ineq_format(N1,N2,C) > compare_ineq_format(N2,N1,C));\ncomp_expr('<=', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_ineq_format(N1,N2,C) > compare_ineq_format(N2,N1,C));\ncomp_expr('=', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_eq_format(N1,N2,C) == compare_eq_format(N2,N1,C));\ncomp_expr('!=', E1, E2, C) ->\n N1 = expr(E1,C),\n N2 = expr(E2,C),\n ?boolean(compare_eq_format(N1,N2,C) \/= compare_eq_format(N2,N1,C)).\n\nbool_expr('or', E1, E2, C) ->\n ?boolean(mk_boolean(C, E1) or mk_boolean(C, E2));\nbool_expr('and', E1, E2, C) ->\n ?boolean(mk_boolean(C, E1) and mk_boolean(C, E2)).\n\n%% According to chapter 3.4 in XML Path Language ver 1.0 the format of\n%% the compared objects are depending on the type of the other\n%% object. \n%% 1. Comparisons involving node-sets is treated equally despite\n%% of which comparancy operand is used. In this case:\n%% - node-set comp node-set: string values are used\n%% - node-set comp number : ((node-set string value) -> number) \n%% - node-set comp boolean : (node-set string value) -> boolean\n%% 2. Comparisons when neither object is a node-set and the operand\n%% is = or != the following transformation is done before comparison:\n%% - if one object is a boolean the other is converted to a boolean.\n%% - if one object is a number the other is converted to a number.\n%% - otherwise convert both to the string value.\n%% 3. Comparisons when neither object is a node-set and the operand is\n%% <=, <, >= or > both objects are converted to a number.\ncompare_eq_format(N1=#xmlObj{type=T1},N2=#xmlObj{type=T2},C) when T1==nodeset;\n\t\t\t\t\t\t\t T2==nodeset ->\n compare_nseq_format(N1,N2,C);\ncompare_eq_format(N1=#xmlObj{type=T1},#xmlObj{type=T2},C) when T1==boolean;\n\t\t\t\t\t\t\t T2==boolean ->\n mk_boolean(C,N1);\ncompare_eq_format(N1=#xmlObj{type=T1},#xmlObj{type=T2},C) when T1==number;\n\t\t\t\t\t\t\t T2==number ->\n mk_number(C,N1);\ncompare_eq_format(N1,_,C) ->\n mk_string(C,string_value(N1)).\n\ncompare_ineq_format(N1=#xmlObj{type=T1},\n\t\t N2=#xmlObj{type=T2},C) when T1==nodeset;\n\t\t\t\t\t\tT2==nodeset ->\n compare_nseq_format(N1,N2,C);\ncompare_ineq_format(N1,_N2,C) ->\n mk_number(C,N1).\n\ncompare_nseq_format(N1=#xmlObj{type = number},_N2,C) ->\n mk_number(C,N1);\ncompare_nseq_format(N1=#xmlObj{type = boolean},_N2,C) ->\n mk_boolean(C,N1);\ncompare_nseq_format(N1=#xmlObj{type = string},_N2,C) ->\n mk_string(C,N1);\ncompare_nseq_format(N1=#xmlObj{type = nodeset},_N2=#xmlObj{type=number},C) ->\n %% transform nodeset value to its string-value\n mk_number(C,string_value(N1));\ncompare_nseq_format(N1=#xmlObj{type = nodeset},_N2=#xmlObj{type=boolean},C) ->\n mk_boolean(C,N1);\ncompare_nseq_format(N1=#xmlObj{type = nodeset},_N2,C) ->\n mk_string(C,string_value(N1)).\n\n\ncore_function('last') ->\t\ttrue;\ncore_function('position') ->\t\ttrue;\ncore_function('count') ->\t\ttrue;\ncore_function('id') ->\t\t\ttrue;\ncore_function('local-name') ->\t\ttrue;\ncore_function('namespace-uri') ->\ttrue;\ncore_function('name') ->\t\ttrue;\ncore_function('string') ->\t\ttrue;\ncore_function('concat') ->\t\ttrue;\ncore_function('starts-with') ->\t\ttrue;\ncore_function('contains') ->\t\ttrue;\ncore_function('substring-before') ->\ttrue;\ncore_function('substring-after') ->\ttrue;\ncore_function('string-length') ->\ttrue;\ncore_function('normalize-space') ->\ttrue;\ncore_function('translate') ->\t\ttrue;\ncore_function('boolean') ->\t\ttrue;\ncore_function('not') ->\t\t\t{true, fn_not};\ncore_function('true') ->\t\t{true, fn_true};\ncore_function('false') ->\t\t{true, fn_false};\ncore_function('lang') ->\t\ttrue;\ncore_function('number') ->\t\ttrue;\ncore_function('sum') ->\t\t\ttrue;\ncore_function('floor') ->\t\ttrue;\ncore_function('ceiling') ->\t\ttrue;\ncore_function('round') ->\t\ttrue;\ncore_function(_) ->\n false.\n\n\n%%% node set functions\n\n%% number: last()\nlast(#xmlContext{nodeset = Set}, []) ->\n ?number(length(Set)).\n\n%% number: position()\nposition(#xmlContext{context_node = #xmlNode{pos = Pos}}, []) ->\n ?number(Pos).\n\n%% number: count(node-set)\ncount(C, [Arg]) ->\n ?number(length(mk_nodeset(C, Arg))).\n\n%% node-set: id(object)\nid(C, [Arg]) ->\n WD = C#xmlContext.whole_document,\n NS0 = [WD],\n Obj = mk_object(C,Arg),\n case Obj#xmlObj.type of\n\tnodeset ->\n\t NodeSet = Obj#xmlObj.value,\n\t IdTokens = \n\t\tlists:foldl(\n\t\t fun(N, AccX) ->\n\t\t\t StrVal = string_value(N),\n\t\t\t TokensX = id_tokens(StrVal),\n\t\t\t TokensX ++ AccX\n\t\t end, [], NodeSet),\n\t NewNodeSet = \n\t\txmerl_xpath:axis(descendant_or_self, \n\t\t\t\t fun(Node) ->\n\t\t\t\t\t attribute_test(Node, id, IdTokens)\n\t\t\t\t end, C#xmlContext{nodeset = NS0}),\n\t ?nodeset(NewNodeSet);\n\t_ ->\n\t StrVal = string_value(Obj#xmlObj.value),\n\t IdTokens = id_tokens(StrVal),\n\t NodeSet = [(WD#xmlNode.node)#xmlDocument.content],\n\t NewNodeSet = lists:foldl(\n\t\t\t fun(Tok, AccX) ->\n\t\t\t\t select_on_attribute(NodeSet, id, Tok, AccX)\n\t\t\t end, [], IdTokens),\n\t ?nodeset(NewNodeSet)\n\t \n end.\n\nid_tokens(Str=#xmlObj{type=string}) ->\n string:tokens(Str#xmlObj.value, \" \\t\\n\\r\").\n%%id_tokens(Str) when list(Str) ->\n%% string:tokens(Str, \" \\t\\n\\r\").\t\t\t \n\nattribute_test(#xmlNode{node = #xmlElement{attributes = Attrs}}, \n\t Key, Vals) ->\n case lists:keysearch(Key, #xmlAttribute.name, Attrs) of\n\t{value, #xmlAttribute{value = V}} ->\n\t lists:member(V, Vals);\n\t_ ->\n\t false\n end;\nattribute_test(_Node, _Key, _Vals) ->\n false.\n\n%%% CONTINUE HERE!!!!\n\n%% string: local-name(node-set?)\n'local-name'(C, []) ->\n local_name1(default_nodeset(C));\n\n'local-name'(C, [Arg]) ->\n local_name1(mk_nodeset(C, Arg)).\n\nlocal_name1([]) ->\n ?string([]);\nlocal_name1([#xmlNode{type=element,node=El}|_]) ->\n #xmlElement{name=Name,nsinfo=NSI} = El,\n local_name2(Name,NSI);\nlocal_name1([#xmlNode{type=attribute,node=Att}|_]) ->\n #xmlAttribute{name=Name,nsinfo=NSI} = Att,\n local_name2(Name,NSI);\nlocal_name1([#xmlNode{type=namespace,node=N}|_]) ->\n #xmlNsNode{prefix=Prefix} = N,\n ?string(Prefix);\nlocal_name1([#xmlElement{name = Name, nsinfo = NSI}|_]) ->\n local_name2(Name,NSI).\nlocal_name2(Name, NSI) ->\n case NSI of\n\t{_Prefix, Local} ->\n\t ?string(Local);\n\t[] ->\n\t ?string(atom_to_list(Name))\n end.\n\n%% string: namespace-uri(node-set?)\n'namespace-uri'(C, []) ->\n ns_uri(default_nodeset(C));\n\n'namespace-uri'(C, [Arg]) ->\n ns_uri(mk_nodeset(C, Arg)).\n\n\nns_uri([]) ->\n ?string([]);\nns_uri([#xmlElement{nsinfo = NSI, namespace = NS}|_]) ->\n ns_uri2(NSI,NS);\nns_uri([#xmlNode{type=element,node=El}|_]) ->\n #xmlElement{nsinfo=NSI, namespace = NS} = El,\n ns_uri2(NSI,NS);\nns_uri([#xmlNode{type=attribute,node=Att}|_]) ->\n #xmlAttribute{nsinfo=NSI, namespace = NS} = Att,\n ns_uri2(NSI,NS);\nns_uri(_) ->\n ?string([]).\n\nns_uri2(NSI,NS) ->\n case NSI of\n\t{Prefix, _} ->\n\t case lists:keysearch(Prefix, 1, NS#xmlNamespace.nodes) of\n\t\tfalse ->\n\t\t ?string([]);\n\t\t{value, {_K, V}} ->\n\t\t string_value(V)\n\t end;\n\t[] ->\n\t ?string([])\n end.\n\n%% name(node-set) -> xmlObj{type=string}\n%% The name function returns a string containing the QName of the node\n%% first in document order. The representation of the QName is not\n%% standardized and applications have their own format. At\n%% http:\/\/xml.coverpages.org\/clarkNS-980804.html (the author of XPath)\n%% adopts the format \"namespace URI\"+\"local-name\" but according to\n%% other sources it is more common to use the format:\n%% '{'\"namespace URI\"'}'\"local-name\". This function also uses this\n%% latter form.\nname(C,[]) ->\n name1(default_nodeset(C));\nname(C, [Arg]) ->\n name1(mk_nodeset(C, Arg)).\nname1([]) ->\n ?string([]);\nname1(NodeSet) ->\n NSVal =\n\tcase ns_uri(NodeSet) of\n\t #xmlObj{value=NSStr} when NSStr =\/= [] ->\n\t\t\"{\"++NSStr++\"}\";\n\t _ ->\n\t\t\"\"\n\tend,\n #xmlObj{value=LocalName} = local_name1(NodeSet),\n ?string(NSVal++LocalName).\n\t\n\t \n\n%%% String functions\n\n%% string: string(object?)\nstring(C, []) ->\n ns_string(default_nodeset(C));\nstring(C, [Arg]) ->\n string_value(mk_object(C, Arg)).\n\nns_string([Obj|_]) ->\n string_value(Obj).\n\nstring_value(#xmlObj{type=nodeset,value=[]}) ->\n ?string(\"\");\nstring_value(N=#xmlObj{type=nodeset}) ->\n string_value(hd(N#xmlObj.value));\nstring_value(N=#xmlObj{}) ->\n string_value(N#xmlObj.value);\n%% Needed also string_value for root_nodes, elements (concatenation of\n%% al decsendant text nodes) and attribute nodes (normalized value).\nstring_value(A=#xmlNode{type=attribute}) ->\n #xmlAttribute{value=AttVal}=A#xmlNode.node,\n ?string(AttVal);\nstring_value(N=#xmlNode{type=namespace}) ->\n #xmlNsNode{uri=URI}=N#xmlNode.node,\n ?string(atom_to_list(URI));\nstring_value(El=#xmlNode{type=element}) ->\n #xmlElement{content=C} = El#xmlNode.node,\n TextValue = fun(#xmlText{value=T},_Fun) -> T;\n\t\t\t(#xmlElement{content=Cont},Fun) -> Fun(Cont,Fun);\n\t\t\t(_,_) -> []\n\t\t end,\n TextDecendants=fun(X) -> TextValue(X,TextValue) end,\n ?string(lists:flatten(lists:map(TextDecendants,C)));\nstring_value(T=#xmlNode{type=text}) ->\n #xmlText{value=Txt} = T#xmlNode.node,\n ?string(Txt);\nstring_value(T=#xmlNode{type=comment}) ->\n #xmlComment{value=Txt} = T#xmlNode.node,\n ?string(Txt);\nstring_value(infinity) -> ?string(\"Infinity\");\nstring_value(neg_infinity) -> ?string(\"-Infinity\");\nstring_value(A) when is_atom(A) ->\n ?string(atom_to_list(A));\nstring_value(N) when is_integer(N) ->\n ?string(integer_to_list(N));\nstring_value(N) when is_float(N) ->\n N1 = round(N * 10000000000000000),\n ?string(strip_zeroes(integer_to_list(N1)));\nstring_value(Str) when is_list(Str) ->\n ?string(Str).\n\nstrip_zeroes(Str) ->\n strip_zs(lists:reverse(Str), 15).\n\nstrip_zs([H|T], 0) ->\n lists:reverse(T) ++ [$., H];\nstrip_zs(\"0\" ++ T, N) ->\n strip_zs(T, N-1);\nstrip_zs([H|T], N) ->\n strip_zs(T, N-1, [H]).\n\nstrip_zs([H|T], 0, Acc) ->\n lists:reverse(T) ++ [$.,H|Acc];\nstrip_zs([H|T], N, Acc) ->\n strip_zs(T, N-1, [H|Acc]).\n\n\n%% string: concat(string, string, string*)\nconcat(C, Args = [_, _|_]) ->\n Strings = [mk_string(C, A) || A <- Args],\n ?string(lists:concat(Strings)).\n\n%% boolean: starts-with(string, string)\n'starts-with'(C, [A1, A2]) ->\n ?boolean(lists:prefix(mk_string(C, A2), mk_string(C, A1))).\n\n%% boolean: contains(string, string)\ncontains(C, [A1, A2]) ->\n Pos = string:str(mk_string(C, A1), mk_string(C, A2)),\n ?boolean(Pos > 0).\n\n%% string: substring-before(string, string)\n'substring-before'(C, [A1, A2]) ->\n S1 = mk_string(C, A1),\n S2 = mk_string(C, A2),\n Pos = string:str(S1, S2),\n ?string(string:substr(S1, 1, Pos)).\n\n%% string: substring-after(string, string)\n'substring-after'(C, [A1, A2]) ->\n S1 = mk_string(C, A1),\n S2 = mk_string(C, A2),\n case string:str(S1, S2) of\n\t0 ->\n\t ?string([]);\n\tPos ->\n\t ?string(string:substr(S1, Pos))\n end.\n\n%% string: substring(string, number, number?)\nsubstring(C, [A1, A2]) ->\n S = mk_string(C, A1),\n Pos = mk_integer(C, A2),\n ?string(string:substr(S, Pos));\nsubstring(C, [A1, A2, A3]) ->\n S = mk_string(C, A1),\n Pos = mk_integer(C, A2),\n Length = mk_integer(C, A3),\n ?string(string:substr(S, Pos, Length)).\n\n\n%% number: string-length(string?)\n'string-length'(C = #xmlContext{context_node = N}, []) ->\n length(mk_string(C, string_value(N)));\n\n'string-length'(C, [A]) ->\n length(mk_string(C, A)).\n\n\n%% string: normalize-space(string?)\n'normalize-space'(C = #xmlContext{context_node = N}, []) ->\n normalize(mk_string(C, string_value(N)));\n\n'normalize-space'(C, [A]) ->\n normalize(mk_string(C, A)).\n\n\n%% string: translate(string, string, string)\ntranslate(C, [A1, A2, A3]) ->\n S1 = mk_string(C, A1),\n S2 = mk_string(C, A2),\n S3 = mk_string(C, A3),\n ?string(translate1(S1, translations(S2, S3))).\n\ntranslate1([H|T], Xls) ->\n case lists:keysearch(H, 1, Xls) of\n\t{value, {_, remove}} ->\n\t translate1(T, Xls);\n\t{value, {_, replace, H1}} ->\n\t [H1|translate1(T, Xls)];\n\tfalse ->\n\t [H|translate1(T, Xls)]\n end;\ntranslate1([], _) ->\n [].\n\ntranslations([H|T], [H1|T1]) ->\n [{H, replace, H1}|translations(T, T1)];\ntranslations(Rest, []) ->\n [{X, remove} || X <- Rest];\ntranslations([], _Rest) ->\n [].\n\n\n\n%% boolean: boolean(object)\nboolean(C, [Arg]) ->\n ?boolean(mk_boolean(C, Arg)).\n\n%% boolean: not(boolean) ->\nfn_not(C, [Arg]) ->\n ?boolean(not(mk_boolean(C, Arg))).\n\n%% boolean: true() ->\nfn_true(_C, []) ->\n ?boolean(true).\n\n%% boolean: false() ->\nfn_false(_C, []) ->\n ?boolean(false).\n\n%% boolean: lang(string) ->\nlang(C = #xmlContext{context_node = N}, [Arg]) ->\n S = mk_string(C, Arg),\n Lang = \n\tcase N of\n\t #xmlElement{language = L} -> L;\n\t #xmlAttribute{language = L} -> L;\n\t #xmlText{language = L} -> L;\n\t #xmlComment{language = L} -> L;\n\t _ -> []\n\tend,\n case Lang of\n\t[] ->\n\t ?boolean(false);\n\t_ ->\n\t ?boolean(match_lang(upcase(S), upcase(Lang)))\n end.\n\n\nupcase([H|T]) when H >= $a, H =< $z ->\n [H+($A-$a)|upcase(T)];\nupcase([H|T]) ->\n [H|upcase(T)];\nupcase([]) ->\n [].\n\nmatch_lang([H|T], [H|T1]) ->\n match_lang(T, T1);\nmatch_lang([], \"-\" ++ _) ->\n true;\nmatch_lang([], []) ->\n true;\nmatch_lang(_, _) ->\n false.\n\t\n\n\n%% number: number(object)\nnumber(C = #xmlContext{context_node = N}, []) ->\n ?number(mk_number(C, string(C, N)));\nnumber(C, [Arg]) ->\n ?number(mk_number(C, Arg)).\n\n\nsum(C, [Arg]) ->\n NS = mk_nodeset(C, Arg),\n lists:foldl(\n fun(N, Sum) ->\n\t Sum + mk_number(C, string(C, N))\n end, 0, NS).\n\nfloor(C, [Arg]) ->\n Num = mk_number(C, Arg),\n case trunc(Num) of\n\tNum1 when Num1 > Num ->\n\t ?number(Num1-1);\n\tNum1 ->\n\t ?number(Num1)\n end.\n\nceiling(C, [Arg]) ->\n Num = mk_number(C, Arg),\n case trunc(Num) of\n\tNum1 when Num1 < Num ->\n\t ?number(Num1+1);\n\tNum1 ->\n\t ?number(Num1)\n end.\n\n\nround(C, [Arg]) ->\n case mk_number(C, Arg) of\n\tA when is_atom(A) ->\n\t A;\n\tN when is_integer(N) ->\n\t N;\n\tF when is_float(F) ->\n\t round(F)\n end.\n\n\nselect_on_attribute([E = #xmlElement{attributes = Attrs}|T], K, V, Acc) ->\n case lists:keysearch(K, #xmlAttribute.name, Attrs) of\n\t{value, #xmlAttribute{value = V}} ->\n\t Acc2 = select_on_attribute(E#xmlElement.content,K,V,[E|Acc]),\n\t select_on_attribute(T, K, V, Acc2);\n\t_ ->\n\t Acc2 = select_on_attribute(E#xmlElement.content,K,V,Acc),\n\t select_on_attribute(T, K, V, Acc2)\n end;\nselect_on_attribute([H|T], K, V, Acc) when is_record(H,xmlText) ->\n select_on_attribute(T, K, V, Acc);\nselect_on_attribute([], _K, _V, Acc) ->\n Acc.\n\n\n%%%%\n\nmk_nodeset(_C0, #xmlContext{nodeset = NS}) ->\n NS;\nmk_nodeset(_C0, #xmlObj{type = nodeset, value = NS}) ->\n NS;\nmk_nodeset(C0, Expr) ->\n case expr(Expr, C0) of\n\t#xmlObj{type = nodeset, value = NS} ->\n\t NS;\n\tOther ->\n\t exit({expected_nodeset, Other})\n end.\n\n\ndefault_nodeset(#xmlContext{context_node = N}) ->\n [N].\n\n\nmk_object(_C0, Obj = #xmlObj{}) ->\n Obj;\nmk_object(C0, Expr) ->\n expr(Expr, C0).\n\n\nmk_string(_C0, #xmlObj{type = string, value = V}) ->\n V;\nmk_string(C0, Obj = #xmlObj{}) ->\n mk_string(C0,string_value(Obj));\nmk_string(C0, Expr) ->\n mk_string(C0, expr(Expr, C0)).\n\n\n\nmk_integer(_C0, #xmlObj{type = number, value = V}) when is_float(V) ->\n round(V);\nmk_integer(_C0, #xmlObj{type = number, value = V}) when is_integer(V) ->\n V;\nmk_integer(C, Expr) ->\n mk_integer(C, expr(Expr, C)).\n\n\nmk_number(_C, #xmlObj{type = string, value = V}) ->\n scan_number(V);\nmk_number(_C, #xmlObj{type = number, value = V}) ->\n V;\nmk_number(C, N=#xmlObj{type = nodeset}) ->\n mk_number(C,string_value(N));\nmk_number(_C, #xmlObj{type = boolean, value = false}) ->\n 0;\nmk_number(_C, #xmlObj{type = boolean, value = true}) ->\n 1;\nmk_number(C, Expr) ->\n mk_number(C, expr(Expr, C)).\n\n\nmk_boolean(_C, #xmlObj{type = boolean, value = V}) -> \n V;\nmk_boolean(_C, #xmlObj{type = number, value = 0}) ->\n false;\nmk_boolean(_C, #xmlObj{type = number, value = V}) when is_float(V) ; is_integer(V) ->\n true;\nmk_boolean(_C, #xmlObj{type = nodeset, value = []}) ->\n false;\nmk_boolean(_C, #xmlObj{type = nodeset, value = _V}) ->\n true;\nmk_boolean(_C, #xmlObj{type = string, value = []}) ->\n false;\nmk_boolean(_C, #xmlObj{type = string, value = _V}) ->\n true;\nmk_boolean(C, Expr) ->\n mk_boolean(C, expr(Expr, C)).\n\n\nnormalize([H|T]) when ?whitespace(H) ->\n normalize(T);\nnormalize(Str) ->\n ContF = fun(_ContF, RetF, _S) ->\n\t\t RetF()\n\t end,\n normalize(Str,\n\t #xmerl_scanner{acc_fun = fun() -> exit(acc_fun) end,\n\t\t\t event_fun = fun() -> exit(event_fun) end,\n\t\t\t hook_fun = fun() -> exit(hook_fun) end,\n\t\t\t continuation_fun = ContF},\n\t []).\n\n\nnormalize(Str = [H|_], S, Acc) when ?whitespace(H) ->\n case xmerl_scan:accumulate_whitespace(Str, S, preserve, Acc) of\n\t{\" \" ++ Acc1, [], _S1} ->\n\t lists:reverse(Acc1);\n\t{Acc1, [], _S1} ->\n\t lists:reverse(Acc1);\n\t{Acc1, T1, S1} ->\n\t normalize(T1, S1, Acc1)\n end;\nnormalize([H|T], S, Acc) ->\n normalize(T, S, [H|Acc]);\nnormalize([], _S, Acc) ->\n lists:reverse(Acc).\n\n\nscan_number([H|T]) when ?whitespace(H) ->\n scan_number(T);\nscan_number(\"-\" ++ T) ->\n case catch xmerl_xpath_scan:scan_number(T) of\n\t{{number, N}, Tail} ->\n\t case is_all_white(Tail) of\n\t\ttrue ->\n\t\t N;\n\t\tfalse ->\n\t\t 'NaN'\n\t end;\n\t_Other ->\n\t 'NaN'\n end;\nscan_number(T) ->\n case catch xmerl_xpath_scan:scan_number(T) of\n\t{{number, N}, Tail} ->\n\t case is_all_white(Tail) of\n\t\ttrue ->\n\t\t N;\n\t\tfalse ->\n\t\t 'NaN'\n\t end;\n\t_Other ->\n\t 'NaN'\n end.\n\nis_all_white([H|T]) when ?whitespace(H) ->\n is_all_white(T);\nis_all_white([_H|_T]) ->\n false;\nis_all_white([]) ->\n true.\n","avg_line_length":26.1536585366,"max_line_length":85,"alphanum_fraction":0.611862352} +{"size":15341,"ext":"erl","lang":"Erlang","max_stars_count":14.0,"content":"%%% Module Description:\n%%% Main entrypoint into compiler\n-module(jarlang).\n-author([\"Chris Bailey\", \"Andrew Johnson\"]).\n\n-define(VERSION, \"2.1.0\").\n\n-vsn(?VERSION).\n\n%%% Export all functions if we compiled with erlc -dTEST or c(?MODULE, {d, 'TEST'}).\n%%% This is so that we can run external eunit tests\n-ifdef(TEST).\n -compile(export_all).\n-else.\n -export([main\/1,\n pipeline\/1,\n pipeline\/2,\n pipeline\/3]).\n-endif.\n\n\n\n\n\n%%% ---------------------------------------------------------------------------------------------%%%\n%%% - TYPE DEFINITIONS --------------------------------------------------------------------------%%%\n%%% ---------------------------------------------------------------------------------------------%%%\n\n-type input_args() :: [atom() | string()].\n\n-type pipeline_stage() :: js\n | js_ast\n | core\n | core_ast\n | all.\n\n-type concurrency_mode() :: single_threaded\n | multi_threaded.\n\n%% Export concurrency_mode type since that'll be used in asttrans\n-export_type([\n concurrency_mode\/0\n]).\n\n\n%%% ---------------------------------------------------------------------------------------------%%%\n%%% - PUBLIC FUNCTIONS --------------------------------------------------------------------------%%%\n%%% ---------------------------------------------------------------------------------------------%%%\n\n%%% Define the arguments that this program can take\n-define(DEFAULT_ARGS, [\n {[\"-o\", \"--output\"], o_output, singleton, \".\", \"Sets the output directory for compiled code. \" ++\n \"If the directory doesn't exist, we will create it.\"},\n\n {[\"-t\", \"--type\"], o_type, singleton, \"js\", \"Sets the output type, defaults to 'js'. \" ++\n \"Valid options are 'js', 'js_ast', 'core_ast', 'core' & 'all'.\"},\n\n {[\"-h\", \"--help\"], o_help, is_set, false, \"Displays this help message and exits.\"},\n\n {[\"-v\", \"--version\"], o_vsn, is_set, false, \"Displays current build version.\"},\n\n {[\"--single-thread\"], o_one_thread, is_set, false, \"Forces transpilation to only use only one thread\/process. \" ++\n \"Single-threaded error output is also much nicer.\"}\n]).\n\n%% Main entrypoint into Jarlang, parses given arguments and decides on what to do.\n-spec main(input_args()) -> ok.\nmain(Args) ->\n % Normalize args to strings if they're atoms, and parse them.\n NArgs = [case is_atom(Arg) of true -> atom_to_list(Arg); false -> Arg end || Arg <- Args],\n ParsedArgs = pkgargs:parse(NArgs, ?DEFAULT_ARGS),\n\n % Read ParsedArgs for arguments\n ShowHelp = pkgargs:get(o_help, ParsedArgs),\n ShowVsn = pkgargs:get(o_vsn, ParsedArgs),\n OutDir = pkgargs:get(o_output, ParsedArgs),\n Type = list_to_atom(pkgargs:get(o_type, ParsedArgs)),\n Files = perform_wildcard_matches(pkgargs:get(default, ParsedArgs)),\n ConcMode = case pkgargs:get(o_one_thread, ParsedArgs) of\n true -> single_threaded;\n false -> multi_threaded\n end,\n\n try branch(ShowHelp, ShowVsn, OutDir, Type, Files, ConcMode) of\n _ -> ok\n catch\n throw:usage ->\n usage(),\n help();\n throw:help ->\n help();\n throw:vsn ->\n version();\n throw:{invalid_type, T} ->\n io:format(\"Type '~p' is an invalid output type. Aborting...~n~n\", [T])\n end,\n\n % Clean up and stop\n init:stop().\n\n\n\n\n\n%%% ---------------------------------------------------------------------------------------------%%%\n%%% - ENTRYPOINT CODE ---------------------------------------------------------------------------%%%\n%%% ---------------------------------------------------------------------------------------------%%%\n\n%% Determines which function to run depending on arguments given.\n-spec branch(boolean(),\n boolean(),\n file:filename_all(),\n pipeline_stage(),\n [file:filename_all(), ...],\n concurrency_mode()) -> ok | no_return().\nbranch(_Help = false, _Vsn = false, Outdir, all, Files, ConcMode) when (length(Files) > 0) ->\n transpile(Files, Outdir, core, ConcMode),\n transpile(Files, Outdir, core_ast, ConcMode),\n transpile(Files, Outdir, js_ast, ConcMode),\n transpile(Files, Outdir, js, ConcMode);\nbranch(_Help = false, _Vsn = false, Outdir, Type, Files, ConcMode) when (length(Files) > 0) ->\n transpile(Files, Outdir, Type, ConcMode);\nbranch(_Help = true, _Vsn = false, _OutDir, _Type, _Files = [], _ConcMode) ->\n throw(help);\nbranch(_Help = false, _Vsn = true, _OutDir, _Type, _Files = [], _ConcMode) ->\n throw(vsn);\nbranch(_Help, _Vsn, _OutDir, _Type, _Files, _ConcMode) ->\n throw(usage).\n\n\n\n\n\n%%% ---------------------------------------------------------------------------------------------%%%\n%%% - COMPILER PIPELINE -------------------------------------------------------------------------%%%\n%%% ---------------------------------------------------------------------------------------------%%%\n\n\n-spec transpile([file:filename_all()],\n file:filename_all(),\n pipeline_stage(),\n concurrency_mode()) -> ok.\n%% Convinience function for synchronously transpiling erl files in js files.\n%% Also sets up compilation environment by extracting files to a tmp directory. Also cleans this\n%% once transpilation is complete.\ntranspile(Files, Outdir, js, single_threaded) ->\n Codegen = pkgutils:pkg_extract_file(\"codegen.js\"),\n pkgutils:pkg_extract_dir(\"node_modules.zip\"),\n ASTs = [pipeline(js_ast, File, single_threaded) || File <- Files],\n [gen_js(Data, Module, Codegen, Outdir) || {Module, Data} <- ASTs],\n pkgutils:pkg_clean_tmp_dir(),\n ok;\n\n%% Convinience function for asynchronously transpiling erl files into js files, and synchronously\n%% returning after all processes finish.\n%% Also sets up compilation environment by extracting files to a tmp directory. Once transpilation\n%% finishes, it then cleans up said directory\ntranspile(Files, Outdir, js, multi_threaded) ->\n Codegen = pkgutils:pkg_extract_file(\"codegen.js\"),\n pkgutils:pkg_extract_dir(\"node_modules.zip\"),\n Pids = [spawn_transpilation_process(File, js_ast, self()) || File <- Files],\n\n %% Pass transpilated results into codegen.js to get JavaScript which we can write to a file\n [\n receive {Pid, {Module, Ast}} ->\n gen_js(Ast, Module, Codegen, Outdir)\n end\n || Pid <- Pids\n ],\n pkgutils:pkg_clean_tmp_dir(),\n ok;\n\n%% Convinience function to synchronously transpile erl files into core_ast files\ntranspile(Files, Outdir, Type, single_threaded) ->\n ok = is_valid_type(Type),\n Processed = [pipeline(Type, File, single_threaded) || File <- Files],\n [write_other(io_lib:format(\"~p\", [Data]), Module, Type, Outdir) || {Module, Data} <- Processed],\n ok;\n\n%% Convinience function for asynchronously transpiling erl files into core_ast files, and synchronously\n%% returning after all processes finish.\ntranspile(Files, Outdir, Type, multi_threaded) ->\n ok = is_valid_type(Type),\n Pids = [spawn_transpilation_process(File, Type, self()) || File <- Files],\n\n % Write results to file\n [\n receive {Pid, {Module, Data}} ->\n write_other(io_lib:format(\"~p\", [Data]), Module, Type, Outdir)\n end\n || Pid <- Pids\n ],\n ok.\n\n%% Spawns a process which performs transpilation for any given file.\n%% Returns output to the spawning process\n-spec spawn_transpilation_process(file:filename_all(),\n pipeline_stage(),\n pid()) -> pid().\nspawn_transpilation_process(File, Type, MainProcess) ->\n spawn_link(fun() ->\n MainProcess ! {self(), pipeline(Type, File, multi_threaded)}\n end).\n\n%% Shorthand for calling pipeline\/3 where the function called is pipeline going as far as\n%% the pipeline is currently implemented, assuming concurrency mode is 'single_threaded'\n-spec pipeline(file:filename_all()) -> {file:filename_all(), any()}.\npipeline(Module) ->\n pipeline(js_ast, Module, single_threaded).\n\n%% Shorthand for calling pipeline\/3 where the function called is pipeline going as far as\n%% the pipeline is currently implemented, with the specified concurrency mode.\n-spec pipeline(file:filename_all(),\n concurrency_mode()) -> {file:filename_all(), any()}.\npipeline(Module, ConcMode) ->\n pipeline(js_ast, Module, ConcMode).\n\n%% Calls different modules, all of which implement different parts of our compiler pipeline,\n%% and returns the result of that stage of the pipeline to the calling function.\n%% The first parameter should be an atom representing what stage of the pipeline you would like\n%% to run and produce, such as 'core' or 'core_ast' to generate core_erlang or\n%% a core_erlang_ast respectively.\n-spec pipeline(pipeline_stage(),\n file:filename_all(),\n concurrency_mode()) -> {file:filename_all(), any()}.\npipeline(core, Module, _ConcMode) ->\n {ok, _ModuleName, BinaryData} = coregen:to_core_erlang(Module, return),\n {Module, BinaryData};\npipeline(core_ast, Module, _ConcMode) ->\n {ok, AST} = coregen:to_core_erlang_ast(Module, return),\n {Module, AST};\npipeline(js_ast, Module, ConcMode) ->\n {_Module, AST} = pipeline(core_ast, Module, ConcMode),\n {Module, estree:to_list(asttrans:erast_to_esast(AST, ConcMode))}.\n\n%% Generate JavaScript by writing our JS AST into a file and then calling escodegen() with a few\n%% generate which ultimately shells out to node and calls codegen.js\n-spec gen_js(estree:es_ast(),\n file:filename_all(),\n file:filename_all(),\n file:filename_all()) -> ok | no_return().\ngen_js(AST, File, Codegen, Outdir) ->\n EncodedAST = jsone:encode(AST),\n\n %% We need to write our json into a temp file so that we can easily pass it into codegen.js\n %% We'll dump the temp file into the same directory as codegen.js\n WorkingDirectory = filename:dirname(Codegen),\n Filename = filename:basename(filename:rootname(File)),\n TempFile = lists:flatten([WorkingDirectory, \"\/\", Filename, \".json\"]),\n filepath:write(EncodedAST, TempFile),\n\n %% Pass json file into escodegen to generate JavaScript\n try escodegen(Codegen, File, TempFile) of\n Result ->\n write_js(Result, Filename, Outdir)\n catch\n E ->\n {err, E}\n end.\n\n%% Does a little processing before shelling out to NodeJS to generate JavaScript from a given JS AST\n-spec escodegen(file:filename_all(),\n file:filename_all(),\n file:filename_all()) -> string().\nescodegen(Codegen, OriginalFile, AstFile) ->\n % {ok, M} = compile:file(OriginalFile),\n \n % % Here we generate some metadata to attach to the generated code\n % ModuleName = M:module_info(module),\n % ModuleAttrs = M:module_info(attributes),\n % ModuleMd5 = M:module_info(md5),\n\n % Metadata = jsone:encode([{module_name, ModuleName},\n % {attributes, ModuleAttrs}]),\n\n % WorkingDirectory = filename:dirname(Codegen),\n % Filename = filename:basename(filename:rootname(OriginalFile)),\n % Metafile = lists:flatten([WorkingDirectory, \"\/\", Filename, \".meta\"]),\n % filepath:write(Metadata, Metafile),\n\n % % Remove compiled beam file\n % file:delete(Filename ++ \".beam\"),\n\n % Finally call escodegen\n os:cmd(\"node \" ++ Codegen ++ \" \" ++ \" \" ++ AstFile).\n\n%% Write results of codegen.js to a file\n-spec write_js(any(),\n file:filename_all(),\n file:filename_all()) -> ok | no_return().\nwrite_js(Result, Filename, Outdir) ->\n write_file(Result, Filename, \"js\", Outdir).\n\n-spec write_other(any(),\n file:filename_all(),\n pipeline_stage(),\n file:filename_all()) -> ok | no_return().\nwrite_other(Data, File, core_ast, Outdir) ->\n Filename = filename:basename(filename:rootname(File)),\n write_file(Data, Filename, \"est\", Outdir);\nwrite_other(Data, File, js_ast, Outdir) ->\n Filename = filename:basename(filename:rootname(File)),\n write_file(Data, Filename, \"jst\", Outdir);\nwrite_other(Data, File, core, Outdir) ->\n Filename = filename:basename(filename:rootname(File)),\n write_file(Data, Filename, \"core\", Outdir).\n\n%% Write results of codegen.js to a file\n-spec write_file(any(),\n file:filename_all(),\n nonempty_string(),\n file:filename_all()) -> ok;\n (any(),\n file:filename_all(),\n nonempty_string(), io) -> no_return().\nwrite_file(Result, Filename, Ext, \"io\") ->\n write_file(Result, Filename, Ext, io); % dirty hack for dialyzer\nwrite_file(Result, Filename, _Ext, io) ->\n io:format(\"==> Result of transpilation for: ~s.erl~n~s~n\", [Filename, Result]);\nwrite_file(Result, Filename, Ext, Outdir) ->\n filelib:ensure_dir(Outdir),\n ok = file:write_file(lists:flatten([Outdir, \"\/\", Filename, \".\", Ext]), Result).\n\n\n\n%%% ---------------------------------------------------------------------------------------------%%%\n%%% - MISC FUNCTIONS ----------------------------------------------------------------------------%%%\n%%% ---------------------------------------------------------------------------------------------%%%\n\n%% Displays usage information\n-spec usage() -> no_return().\nusage() ->\n SelfName = pkgutils:pkg_name(),\n io:format(\"Usage: ~s FILEs... [-o ][-t ]~n\" ++\n \"Compiles the Erlang source files FILEs you specify into JavaScript.~n\" ++\n \"Or if Type is set will output a file from that point in the pipeline.~n\" ++\n \"Example: ~s src\/*.erl -o js\/~n~n\",\n [SelfName,\n SelfName]).\n\n%% Displays help information\n-spec help() -> no_return().\nhelp() ->\n io:format(\"Valid Configuration Parameters:~n\" ++\n \"~s~n\",\n [pkgargs:create_help_string(?DEFAULT_ARGS, 1, 55)]).\n\n%% Displays version information\n-spec version() -> no_return().\nversion() ->\n io:format(\"Current ~s version: v~s~n~n\",\n [pkgutils:pkg_name(),\n ?VERSION]).\n\n%% Looks through a list of file names and expands any wildcards that may exist.\n%% None wildcards will just be added to the accumulator so that we can crash gracefully\n%% later on.\n-spec perform_wildcard_matches([file:filename_all()]) -> [file:filename_all()].\nperform_wildcard_matches([]) ->\n [];\nperform_wildcard_matches(FileList) ->\n lists:foldl(fun(PotentialWildcard, Accumulator) ->\n case filelib:wildcard(PotentialWildcard) of\n [] ->\n Accumulator ++ [PotentialWildcard];\n Matches ->\n Accumulator ++ Matches\n end\n end, [], FileList).\n\n%% Checks whether a given type is a valid one, and if so, returns ok.\n%% Otherwise throws an error.\n-spec is_valid_type(pipeline_stage()) -> ok.\nis_valid_type(js) ->\n ok;\nis_valid_type(js_ast) ->\n ok;\nis_valid_type(core) ->\n ok;\nis_valid_type(core_ast) ->\n ok;\nis_valid_type(all) ->\n ok;\nis_valid_type(Type) ->\n throw({invalid_type, Type}).","avg_line_length":39.8467532468,"max_line_length":118,"alphanum_fraction":0.573430676} +{"size":97024,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2000-2013. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n\n-module(xref_SUITE).\n\n%-define(debug, true).\n\n-ifdef(debug).\n-define(format(S, A), io:format(S, A)).\n-define(line, put(line, ?LINE), ).\n-define(config(X,Y), \".\/log_dir\/\").\n-define(t,test_server).\n-define(datadir, \"xref_SUITE_data\").\n-define(privdir, \"xref_SUITE_priv\").\n-define(copydir, \"xref_SUITE_priv\/datacopy\").\n-else.\n-include_lib(\"test_server\/include\/test_server.hrl\").\n-define(format(S, A), ok).\n-define(datadir, ?config(data_dir, Conf)).\n-define(privdir, ?config(priv_dir, Conf)).\n-define(copydir, ?config(copy_dir, Conf)).\n-endif.\n\n-export([all\/0, suite\/0,groups\/0,init_per_suite\/1, end_per_suite\/1, \n\t init_per_group\/2,end_per_group\/2, init\/1, fini\/1]).\n\n-export([\n\t addrem\/1, convert\/1, intergraph\/1, lines\/1, loops\/1,\n\t no_data\/1, modules\/1]).\n\n-export([\n\t add\/1, default\/1, info\/1, lib\/1, read\/1, read2\/1, remove\/1,\n\t replace\/1, update\/1, deprecated\/1, trycatch\/1,\n fun_mfa\/1, fun_mfa_r14\/1,\n\t fun_mfa_vars\/1, qlc\/1]).\n\n-export([\n\t analyze\/1, basic\/1, md\/1, q\/1, variables\/1, unused_locals\/1]).\n\n-export([\n\t format_error\/1, otp_7423\/1, otp_7831\/1, otp_10192\/1]).\n\n-import(lists, [append\/2, flatten\/1, keysearch\/3, member\/2, sort\/1, usort\/1]).\n\n-import(sofs, [converse\/1, from_term\/1, intersection\/2, is_sofs_set\/1,\n\trange\/1, relation_to_family\/1, set\/1, to_external\/1,\n\tunion\/2]).\n\n-export([init_per_testcase\/2, end_per_testcase\/2]).\n\n%% Checks some info counters of a server and some relations that should hold.\n-export([check_count\/1, check_state\/1]).\n\n-include_lib(\"kernel\/include\/file.hrl\").\n\n-include_lib(\"tools\/src\/xref.hrl\").\n\nsuite() -> [{ct_hooks,[ts_install_cth]}].\n\nall() -> \n [{group, xref}, {group, files}, {group, analyses},\n {group, misc}].\n\ngroups() -> \n [{xref, [],\n [addrem, convert, intergraph, lines, loops, no_data,\n modules]},\n {files, [],\n [add, default, info, lib, read, read2, remove, replace,\n update, deprecated, trycatch, fun_mfa,\n fun_mfa_r14, fun_mfa_vars, qlc]},\n {analyses, [],\n [analyze, basic, md, q, variables, unused_locals]},\n {misc, [], [format_error, otp_7423, otp_7831, otp_10192]}].\n\ninit_per_suite(Config) ->\n init(Config).\n\nend_per_suite(_Config) ->\n ok.\n\ninit_per_group(_GroupName, Config) ->\n Config.\n\nend_per_group(_GroupName, Config) ->\n Config.\n\n\ninit(Conf) when is_list(Conf) ->\n DataDir = ?datadir,\n PrivDir = ?privdir,\n ?line CopyDir = fname(PrivDir, \"datacopy\"),\n ?line TarFile = fname(PrivDir, \"datacopy.tgz\"),\n ?line {ok, Tar} = erl_tar:open(TarFile, [write, compressed]),\n ?line ok = erl_tar:add(Tar, DataDir, CopyDir, [compressed]),\n ?line ok = erl_tar:close(Tar),\n ?line ok = erl_tar:extract(TarFile, [compressed]),\n ?line ok = file:delete(TarFile),\n [{copy_dir, CopyDir} | Conf].\n\nfini(Conf) when is_list(Conf) ->\n %% Nothing.\n Conf.\n\ninit_per_testcase(_Case, Config) ->\n Dog=?t:timetrap(?t:minutes(2)),\n [{watchdog, Dog}|Config].\n\nend_per_testcase(_Case, _Config) ->\n Dog=?config(watchdog, _Config),\n test_server:timetrap_cancel(Dog),\n ok.\n\n\n%% Seems a bit short...\naddrem(suite) -> [];\naddrem(doc) -> [\"Simple test of removing modules\"];\naddrem(Conf) when is_list(Conf) ->\n S0 = new(),\n\n F1 = {m1,f1,1},\n F2 = {m2,f1,2},\n\n E1 = {F1,F2},\n E2 = {F2,F1},\n\n D1 = {F1,12},\n DefAt_m1 = [D1],\n X_m1 = [F1],\n % L_m1 = [],\n XC_m1 = [E1],\n LC_m1 = [],\n LCallAt_m1 = [],\n XCallAt_m1 = [{E1,13}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n D2 = {F2,7},\n DefAt_m2 = [D2],\n X_m2 = [F2],\n % L_m2 = [],\n XC_m2 = [E2],\n LC_m2 = [],\n LCallAt_m2 = [],\n XCallAt_m2 = [{E2,96}],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n ?line S5 = set_up(S2),\n\n ?line {ok, XMod1, S6} = remove_module(S5, m1),\n ?line [a1] = XMod1#xref_mod.app_name,\n ?line {ok, XMod2, S6a} = remove_module(S6, m2),\n ?line [a2] = XMod2#xref_mod.app_name,\n ?line S7 = set_up(S6a),\n\n ?line AppInfo1 = #xref_app{name = a1, rel_name = [r1]},\n ?line S9 = add_application(S7, AppInfo1),\n ?line S10 = set_up(S9),\n ?line AppInfo2 = #xref_app{name = a2, rel_name = [r1]},\n ?line _S11 = add_application(S10, AppInfo2),\n ok.\n\nconvert(suite) -> [];\nconvert(doc) -> [\"Coercion of data\"];\nconvert(Conf) when is_list(Conf) ->\n S0 = new(),\n\n F1 = {m1,f1,1},\n F6 = {m1,f2,6}, % X\n F2 = {m2,f1,2},\n F3 = {m2,f2,3}, % X\n F7 = {m2,f3,7}, % X\n F4 = {m3,f1,4}, % X\n F5 = {m3,f2,5},\n\n UF1 = {m1,f12,17},\n UF2 = {m17,f17,177},\n\n E1 = {F1,F3}, % X\n E2 = {F6,F7}, % X\n E3 = {F2,F6}, % X\n E4 = {F1,F4}, % X\n E5 = {F4,F5},\n E6 = {F7,F4}, % X\n\n UE1 = {F2,UF2}, % X\n UE2 = {F5,UF1}, % X\n\n D1 = {F1,12},\n D6 = {F6,3},\n DefAt_m1 = [D1,D6],\n X_m1 = [F6],\n % L_m1 = [F1],\n XC_m1 = [E1,E2,E4],\n LC_m1 = [],\n LCallAt_m1 = [],\n XCallAt_m1 = [{E1,13},{E2,17},{E4,7}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n D2 = {F2,7},\n D3 = {F3,9},\n D7 = {F7,19},\n DefAt_m2 = [D2,D3,D7],\n X_m2 = [F3,F7],\n % L_m2 = [F2],\n XC_m2 = [E3,E6,UE1],\n LC_m2 = [],\n LCallAt_m2 = [],\n XCallAt_m2 = [{E3,96},{E6,12},{UE1,77}],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n D4 = {F4,6},\n D5 = {F5,97},\n DefAt_m3 = [D4,D5],\n X_m3 = [F4],\n % L_m3 = [F5],\n XC_m3 = [UE2],\n LC_m3 = [E5],\n LCallAt_m3 = [{E5,19}],\n XCallAt_m3 = [{UE2,22}],\n Info3 = #xref_mod{name = m3, app_name = [a3]},\n ?line S3 = add_module(S2, Info3, DefAt_m3, X_m3, LCallAt_m3, XCallAt_m3,\n\t\t\t XC_m3, LC_m3),\n\n Info4 = #xref_mod{name = m4, app_name = [a2]},\n ?line S4 = add_module(S3, Info4, [], [], [], [], [], []),\n\n AppInfo1 = #xref_app{name = a1, rel_name = [r1]},\n ?line S9 = add_application(S4, AppInfo1),\n AppInfo2 = #xref_app{name = a2, rel_name = [r1]},\n ?line S10 = add_application(S9, AppInfo2),\n AppInfo3 = #xref_app{name = a3, rel_name = [r2]},\n ?line S11 = add_application(S10, AppInfo3),\n\n RelInfo1 = #xref_rel{name = r1},\n ?line S12 = add_release(S11, RelInfo1),\n RelInfo2 = #xref_rel{name = r2},\n ?line S13 = add_release(S12, RelInfo2),\n\n ?line S = set_up(S13),\n\n ?line {ok, _} = eval(\"(Lin)(m1->m1:Mod) * m1->m1\", type_error, S),\n ?line {ok, _} = eval(\"(XXL)(Lin)(m1->m1:Mod) * m1->m1\", type_error, S),\n\n ?line AllDefAt = eval(\"(Lin) M\", S),\n ?line AllV = eval(\"(Fun) M\", S),\n ?line AllCallAt = eval(\"(XXL)(Lin) E\", S),\n ?line AllE = eval(\"E\", S),\n\n ?line AM = eval(\"AM\", S),\n ?line A = eval(\"A\", S),\n ?line R = eval(\"R\", S),\n\n\n % vertices\n % general 1 step\n ?line {ok, _} = eval(\"(Fun) (Lin) M\", AllV, S),\n ?line {ok, _} = eval(\"(Fun) (Lin) (Lin) M\", AllV, S),\n ?line {ok, _} = eval(f(\"(Fun) (Lin) ~p\", [[F1, F3]]), [F1,F3], S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [AllV]), [m1,m17,m2,m3], S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [[F1,F3,F6]]), [m1,m2], S),\n ?line {ok, _} = eval(\"(App) M\", A, S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [[m1,m2,m4]]), [a1,a2], S),\n ?line {ok, _} = eval(f(\"(Rel) ~p\", [A]), R, S),\n ?line {ok, _} = eval(f(\"(Rel) ~p\", [[a1,a2,a2]]), [r1], S),\n % general 2 steps\n ?line {ok, _} = eval(\"(Mod) (Lin) M\", [m1,m17,m2,m3], S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [AllV]), [a1,a2,a3], S),\n ?line {ok, _} = eval(\"(Rel) M\", R, S),\n % general 4 steps\n ?line {ok, _} = eval(\"(Rel) (Lin) M\", [r1,r2], S),\n\n % special 1 step\n ?line {ok, _} = eval(f(\"(Lin) ~p\", [AllV]), AllDefAt, S),\n ?line {ok, _} = eval(f(\"(Lin) ~p\", [[F1,F3]]), [{F1,12},{F3,9}], S),\n ?line {ok, _} = eval(\"(Fun) M\", AllV, S),\n ?line {ok, _} = eval(f(\"(Fun) ~p\", [[m1,m2]]), [F1,F2,F3,F6,F7,UF1], S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [A]), AM, S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [[a1,a2]]), [m1,m2,m4], S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [R]), A, S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [[r1]]), [a1,a2], S),\n % special 2 steps\n ?line {ok, _} = eval(\"(Lin) M\", AllDefAt, S),\n ?line AnalyzedV = eval(\"(Fun) AM\", S),\n ?line {ok, _} = eval(f(\"(Fun) ~p\", [A]), AnalyzedV, S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [R]), AM, S),\n % special 4 steps\n ?line AnalyzedAllDefAt = eval(\"(Lin) AM\", S),\n ?line {ok, _} = eval(\"(Lin) R\", AnalyzedAllDefAt, S),\n\n % edges\n Ms = [{m1,m2},{m1,m3},{m2,m1},{m2,m3},{m3,m3}],\n UMs = [{m2,m17},{m3,m1}],\n AllMs = append(Ms, UMs),\n As = [{a1,a2},{a1,a3},{a2,a1},{a2,a3},{a3,a3}],\n Rs = [{r1,r1},{r1,r2},{r2,r2}],\n\n % general 1 step\n ?line {ok, _} = eval(\"(Fun) (Lin) E\", AllE, S),\n ?line {ok, _} = eval(f(\"(Fun)(Lin) ~p\", [[E1, E6]]), [E1, E6], S),\n ?line {ok, _} = eval(\"(Mod) E\", AllMs, S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [[E1, E6]]), [{m1,m2},{m2,m3}], S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [As]), As, S),\n ?line {ok, _} = eval(\"(App) [m1->m2,m2->m3]\", [{a1,a2},{a2,a3}], S),\n ?line {ok, _} = eval(f(\"(Rel) ~p\", [As]), Rs, S),\n ?line {ok, _} = eval(\"(Rel) a1->a2\", [{r1,r1}], S),\n\n % special 1 step\n ?line {ok, _} = eval(\"(XXL) (Lin) (Fun) E\", AllCallAt, S),\n ?line {ok, _} = eval(\"(XXL) (XXL) (Lin) (Fun) E\", AllCallAt, S),\n\n ?line {ok, _} = eval(f(\"(XXL) (Lin) ~p\", [[E1, E6]]),\n\t\t\t [{{D1,D3},[13]}, {{D7,D4},[12]}], S),\n ?line {ok, _} = eval(f(\"(Fun) ~p\", [AllMs]), AllE, S),\n ?line {ok, _} = eval(\"(Fun) [m1->m2,m2->m3]\", [E1,E2,E6], S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [As]), Ms, S),\n ?line {ok, _} = eval(\"(Mod) [a1->a2,a2->a3]\", [{m1,m2},{m2,m3}], S),\n ?line {ok, _} = eval(f(\"(App) ~p\", [Rs]), As, S),\n ?line {ok, _} = eval(\"(App) r1->r1\", [{a1,a2},{a2,a1}], S),\n ok.\n\nintergraph(suite) -> [];\nintergraph(doc) -> [\"Inter Call Graph\"];\nintergraph(Conf) when is_list(Conf) ->\n S0 = new(),\n\n F1 = {m1,f1,1}, % X\n F2 = {m1,f2,2}, % X\n F3 = {m1,f3,3},\n F4 = {m1,f4,4},\n F5 = {m1,f5,5},\n\n F6 = {m2,f1,6}, % X\n F7 = {m2,f1,7},\n F8 = {m2,f1,8},\n F9 = {m2,f1,9},\n F10 = {m2,f1,10},\n F11 = {m2,f1,11},\n\n % Note: E1 =:= E4!\n E1 = {F2,F1},\n E2 = {F2,F3},\n E3 = {F3,F1},\n E4 = {F2,F1}, % X\n E5 = {F4,F2},\n E6 = {F5,F4},\n E7 = {F4,F5},\n\n E8 = {F6,F7},\n E9 = {F7,F8},\n E10 = {F8,F1}, % X\n E11 = {F6,F9},\n E12 = {F6,F10},\n E13 = {F9,F11},\n E14 = {F10,F11},\n E15 = {F11,F1}, % X\n\n D1 = {F1,1},\n D2 = {F2,2},\n D3 = {F3,3},\n D4 = {F4,4},\n D5 = {F5,5},\n DefAt_m1 = [D1,D2,D3,D4,D5],\n X_m1 = [F1,F2],\n % L_m1 = [F3,F4,F5],\n XC_m1 = [E4],\n LC_m1 = [E1,E2,E3,E5,E6,E7],\n % Note: E1 and E4 together!\n LCallAt_m1 = [{E1,1},{E2,2},{E3,3},{E5,5},{E6,6},{E7,7}],\n XCallAt_m1 = [{E1,4}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n D6 = {F6,6},\n D7 = {F7,7},\n D8 = {F8,8},\n D9 = {F9,9},\n D10 = {F10,10},\n D11 = {F11,11},\n DefAt_m2 = [D6,D7,D8,D9,D10,D11],\n X_m2 = [F6],\n % L_m2 = [F7,F8,F9,F10,F11],\n XC_m2 = [E10,E15],\n LC_m2 = [E8,E9,E11,E12,E13,E14],\n LCallAt_m2 = [{E8,8},{E9,9},{E11,11},{E12,12},{E13,13},{E14,14}],\n XCallAt_m2 = [{E10,10},{E15,15}],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n AppInfo1 = #xref_app{name = a1, rel_name = [r1]},\n ?line S5 = add_application(S2, AppInfo1),\n AppInfo2 = #xref_app{name = a2, rel_name = [r1]},\n ?line S6 = add_application(S5, AppInfo2),\n\n RelInfo = #xref_rel{name = r1},\n ?line S7 = add_release(S6, RelInfo),\n\n ?line S = set_up(S7),\n\n ?line {ok, _} = eval(\"EE | m1\", [E1,E5,E6,E7], S),\n ?line {ok, _} = eval(\"EE | m2\", [{F6,F1}], S),\n ?line {ok, _} = eval(\"EE | m2 + EE | m2\", [{F6,F1}], S),\n\n ?line {ok, _} = eval(\"(Fun)(Lin)(E | m1)\",\n\t to_external(union(set(XC_m1), set(LC_m1))), S),\n ?line {ok, _} = eval(\"(XXL)(ELin) (EE | m1)\",\n\t [{{D2,D1},[1,2,4]},{{D4,D2},[5]},{{D5,D4},[6]},{{D4,D5},[7]}],\n\t S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(EE | m2)\", [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(ELin)(EE | m2)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n\n %% Combining graphs (equal or different):\n ?line {ok, _} = eval(\"(XXL)(ELin)(EE | m2 + EE | m2)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(EE | m2 * EE | m2)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(EE | m2 - EE | m1)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(EE | m2 - E | m2)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(Fun)(ELin)(EE | m2)\",\n\t\t\t [{{D6,D1},[8,11,12]}], S),\n ?line {ok, _} = eval(\"EE | m1 + E | m1\", LC_m1, S),\n ?line {ok, _} = eval(f(\"EE | ~p + E | ~p\", [F2, F2]), [E1,E2], S),\n %% [1,4] from 'calls' is a subset of [1,2,4] from Inter Call Graph:\n ?line {ok, _} = eval(f(\"(XXL)(Lin) (E | ~p)\", [F2]),\n\t\t\t [{{D2,D1},[1,4]},{{D2,D3},[2]}], S),\n\n ?line {ok, _} = eval(f(\"(XXL)(ELin) (EE | ~p)\", [F2]),\n\t\t\t [{{D2,D1},[1,2,4]}], S),\n ?line {ok, _} = eval(f(\"(XXL)((ELin)(EE | ~p) + (Lin)(E | ~p))\", [F2, F2]),\n\t\t\t [{{D2,D1},[1,2,4]},{{D2,D3},[2]}], S),\n ?line {ok, _} =\n\teval(f(\"(XXL)((ELin) ~p + (Lin) ~p)\", [{F2, F1}, {F2, F1}]),\n\t [{{D2,D1},[1,2,4]}], S),\n ?line {ok, _} = eval(f(\"(Fun)(Lin) ~p\", [{F2, F1}]), [E1], S),\n %% The external call E4 is included in the reply:\n ?line {ok, _} = eval(\"(XXL)(Lin)(LC | m1)\",\n\t\t\t [{{D2,D1},[1,4]},{{D2,D3},[2]},{{D3,D1},[3]},\n\t\t\t {{D4,D2},[5]},{{D4,D5},[7]},{{D5,D4},[6]}], S),\n %% The local call E1 is included in the reply:\n ?line {ok, _} = eval(\"(XXL)(Lin)(XC | m1)\", [{{D2,D1},[1,4]}], S),\n\n ?line {ok, _} = eval(f(\"(LLin) (E | ~p || ~p) + (XLin) (E | ~p || ~p)\",\n\t\t\t [F2, F1, F2, F1]), [{E4,[1,4]}], S),\n\n ?line {ok, _} = eval(\"# (ELin) E\", 6, S),\n\n ok.\n\nlines(suite) -> [];\nlines(doc) -> [\"More test of Inter Call Graph, and regular expressions\"];\nlines(Conf) when is_list(Conf) ->\n S0 = new(),\n\n F1 = {m1,f1,1}, % X\n F2 = {m1,f2,2},\n F3 = {m1,f3,3},\n F4 = {m2,f4,4}, % X\n F5 = {m1,f5,5}, % X\n F6 = {m1,f6,6},\n\n E1 = {F1,F2},\n E2 = {F2,F1}, % X\n E3 = {F3,F2},\n E4 = {F1,F4}, % X\n E5 = {F2,F4}, % X\n E6 = {F5,F6},\n E7 = {F6,F4}, % X\n\n D1 = {F1,1},\n D2 = {F2,2},\n D3 = {F3,3},\n D4 = {F4,4},\n D5 = {F5,5},\n D6 = {F6,6},\n\n DefAt_m1 = [D1,D2,D3,D5,D6],\n X_m1 = [F1,F5],\n % L_m1 = [F2,F3,F6],\n XC_m1 = [E4,E5,E7],\n LC_m1 = [E1,E2,E3,E6],\n LCallAt_m1 = [{E1,1},{E3,3},{E6,6}],\n XCallAt_m1 = [{E2,2},{E4,4},{E5,5},{E7,7}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n DefAt_m2 = [D4],\n X_m2 = [F4],\n % L_m2 = [],\n XC_m2 = [],\n LC_m2 = [],\n LCallAt_m2 = [],\n XCallAt_m2 = [],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n AppInfo1 = #xref_app{name = a1, rel_name = [r1]},\n ?line S5 = add_application(S2, AppInfo1),\n AppInfo2 = #xref_app{name = a2, rel_name = [r1]},\n ?line S6 = add_application(S5, AppInfo2),\n\n RelInfo = #xref_rel{name = r1},\n ?line S7 = add_release(S6, RelInfo),\n\n ?line S = set_up(S7),\n\n ?line {ok, _} = eval(\"(XXL) (ELin) (EE | m1)\",\n\t\t [{{D1,D1},[1]},{{D1,D4},[1,4]},{{D3,D1},[3]},{{D3,D4},[3]},\n\t\t {{D5,D4},[6]}], S),\n ?line {ok, _} = eval(\"(XXL)(Lin) (E | m1)\",\n\t\t [{{D1,D2},[1]},{{D1,D4},[4]},{{D2,D1},[2]},\n\t\t {{D2,D4},[5]},{{D3,D2},[3]},{{D5,D6},[6]},{{D6,D4},[7]}],\n\t\t S),\n ?line {ok, _} = eval(\"(E | m1) + (EE | m1)\",\n\t\t [E1,E2,E3,E4,E5,E6,E7,{F1,F1},{F3,F1},{F3,F4},{F5,F4}],\n\t\t S),\n ?line {ok, _} = eval(\"(Lin)(E | m1)\",\n\t\t [{E4,[4]},{E1,[1]},{E2,[2]},{E5,[5]},\n\t\t {E3,[3]},{E7,[7]},{E6,[6]}], S),\n ?line {ok, _} = eval(\"(ELin)(EE | m1)\",\n\t\t [{{F1,F1},[1]},{{F1,F4},[1,4]},{{F3,F1},[3]},{{F3,F4},[3]},\n\t\t {{F5,F4},[6]}], S),\n ?line {ok, _} = eval(\"(Lin)(E | m1) + (ELin)(EE | m1)\",\n\t\t [{E4,[1,4]},{E1,[1]},{E2,[2]},{E5,[5]},\n\t\t {E3,[3]},{E7,[7]},{E6,[6]},\n\t\t {{F1,F1},[1]},{{F3,F1},[3]},{{F3,F4},[3]},\n\t\t {{F5,F4},[6]}], S),\n ?line {ok, _} = eval(\"(Lin)(E | m1) - (ELin)(EE | m1)\",\n\t\t [{E1,[1]},{E2,[2]},{E5,[5]},\n\t\t {E3,[3]},{E7,[7]},{E6,[6]}], S),\n ?line {ok, _} = eval(\"(Lin)(E | m1) * (ELin)(EE | m1)\",\n\t\t [{E4,[4]}], S),\n ?line {ok, _} = eval(\"(XXL)(Lin) (E | m1)\",\n\t\t [{{D1,D4},[4]},{{D1,D2},[1]},{{D2,D1},[2]},{{D2,D4},[5]},\n\t\t {{D3,D2},[3]},{{D6,D4},[7]},{{D5,D6},[6]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin) (EE | m1)\",\n\t\t [{{D1,D1},[1]},{{D1,D4},[1,4]},{{D3,D1},[3]},{{D3,D4},[3]},\n\t\t {{D5,D4},[6]}], S),\n ?line {ok, _} = eval(\"(XXL)(Lin)(Fun)(Lin) (E | m1)\",\n\t\t [{{D1,D4},[4]},{{D1,D2},[1]},{{D2,D1},[2]},{{D2,D4},[5]},\n\t\t {{D3,D2},[3]},{{D6,D4},[7]},{{D5,D6},[6]}], S),\n ?line {ok, _} = eval(\"(XXL)(ELin)(Fun)(ELin) (EE | m1)\",\n\t\t [{{D1,D1},[1]},{{D1,D4},[1,4]},{{D3,D1},[3]},{{D3,D4},[3]},\n\t\t {{D5,D4},[6]}], S),\n\n %% A few tests on regexp.\n ?line {ok, _} = eval(\"\\\"(foo\\\":Mod\", parse_error, S),\n ?line {ok, _} = eval(\"_Foo:_\/_\", parse_error, S),\n ?line {ok, _} = eval(\"\\\".*foo\\\"\", parse_error, S),\n ?line {ok, _} = eval(\"_:_\/_:Lin\", parse_error, S),\n ?line {ok, _} = eval(\"_:_\/_:Mod\", parse_error, S),\n ?line {ok, _} = eval(\"_:_\/_:App\", parse_error, S),\n ?line {ok, _} = eval(\"_:_\/_:Rel\", parse_error, S),\n ?line {ok, _} = eval(\"m2:_\/4\", [F4], S),\n ?line {ok, _} = eval(\"m2:_\/4:Fun\", [F4], S),\n ?line {ok, _} = eval(\"\\\"m.?\\\":\\\"f.*\\\"\/\\\"6\\\"\", [F6], S),\n ?line {ok, _} = eval(\"_:_\/6\", [F6], S),\n ?line {ok, _} = eval(\"m1:\\\"f1\\\"\/_\", [F1], S),\n ?line {ok, _} = eval(\"\\\"m1\\\":f1\/_\", [F1], S),\n ?line {ok, _} = eval(\"\\\"m1\\\":Mod\", [m1], S),\n ?line {ok, _} = eval(\"\\\"a1\\\":App\", [a1], S),\n ?line {ok, _} = eval(\"\\\"r1\\\":Rel\", [r1], S),\n ?line {ok, _} = eval(\"_:_\/-1\", [], S),\n\n ok.\n\nloops(suite) -> [];\nloops(doc) -> [\"More Inter Call Graph, loops and \\\"unusual\\\" cases\"];\nloops(Conf) when is_list(Conf) ->\n S0 = new(),\n\n F1 = {m1,f1,1}, % X\n F2 = {m1,f2,2},\n F3 = {m1,f3,3}, % X\n F4 = {m1,f4,4},\n F5 = {m1,f5,5},\n F6 = {m1,f1,6}, % X\n F7 = {m1,f1,7},\n\n E1 = {F1,F1}, % X\n E2 = {F2,F2},\n E3 = {F3,F4},\n E4 = {F4,F5},\n E5 = {F5,F3}, % X\n\n D1 = {F1,1},\n D2 = {F2,2},\n D3 = {F3,3},\n D4 = {F4,4},\n D5 = {F5,5},\n D6 = {F6,6},\n D7 = {F7,7},\n DefAt_m1 = [D1,D2,D3,D4,D5,D6,D7],\n X_m1 = [F1,F3,F6],\n % L_m1 = [F2,F4,F5],\n XC_m1 = [],\n LC_m1 = [E1,E2,E3,E4,E5],\n LCallAt_m1 = [{E2,2},{E3,3},{E4,4}],\n XCallAt_m1 = [{E1,1},{E5,5}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n ?line S = set_up(S1),\n\n % Neither F6 nor F7 is included. Perhaps one should change that?\n ?line {ok, _} = eval(\"EE | m1\", [E1,E2,{F3,F3}], S),\n ?line {ok, _} = eval(f(\"(XXL)(ELin) (EE | ~p)\", [F3]), [{{D3,D3},[3]}], S),\n\n ?line {ok, _} = eval(\"m1->m1 | m1->m1\", type_error, S),\n ?line {ok, _} = eval(f(\"~p | ~p\", [F2, F1]), type_error, S),\n\n ?line {ok, _} = eval(f(\"range (closure EE | ~p)\", [F1]), [F1], S),\n ?line {ok, _} = eval(f(\"domain (closure EE || ~p)\", [F3]), [F3], S),\n\n ?line {ok, _} = eval(f(\"domain (closure E || ~p)\", [F3]), [F3,F4,F5], S),\n\n ?line {ok, _} = eval(\"components E\", [[F1],[F2],[F3,F4,F5]], S),\n ?line {ok, _} = eval(\"components EE\", [[F1],[F2],[F3]], S),\n\n ok.\n\nno_data(suite) -> [];\nno_data(doc) -> [\"Simple tests when there is no data\"];\nno_data(Conf) when is_list(Conf) ->\n S0 = new(),\n ?line S1 = set_up(S0),\n ?line {ok, _} = eval(\"M\", [], S1),\n ?line {ok, _} = eval(\"A\", [], S1),\n ?line {ok, _} = eval(\"R\", [], S1),\n\n ModInfo = #xref_mod{name = m, app_name = []},\n ?line S2 = add_module(S1, ModInfo, [], [], [], [], [], []),\n AppInfo = #xref_app{name = a, rel_name = []},\n ?line S3 = add_application(S2, AppInfo),\n RelInfo = #xref_rel{name = r, dir = \"\"},\n ?line S4 = add_release(S3, RelInfo),\n ?line S5 = set_up(S4),\n ?line {ok, _} = eval(\"M\", [m], S5),\n ?line {ok, _} = eval(\"A\", [a], S5),\n ?line {ok, _} = eval(\"R\", [r], S5),\n ok.\n\nmodules(suite) -> [];\nmodules(doc) -> [\"Modules mode\"];\nmodules(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir, \"rel2\"),\n X = fname(Dir, \"x.erl\"),\n Y = fname(Dir, \"y.erl\"),\n A1_1 = fname([Dir,\"lib\",\"app1-1.1\"]),\n A2 = fname([Dir,\"lib\",\"app2-1.1\"]),\n EB1_1 = fname(A1_1, \"ebin\"),\n EB2 = fname(A2, \"ebin\"),\n Xbeam = fname(EB2, \"x.beam\"),\n Ybeam = fname(EB1_1, \"y.beam\"),\n\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB2}]),\n ?line {ok, y} = compile:file(Y, [debug_info, {outdir,EB1_1}]),\n\n ?line {ok, S0} = xref_base:new([{xref_mode, modules}]),\n ?line {ok, release2, S1} =\n\txref_base:add_release(S0, Dir, [{name,release2}]),\n ?line S = set_up(S1),\n ?line {{error, _, {unavailable_analysis, undefined_function_calls}}, _} =\n\txref_base:analyze(S, undefined_function_calls),\n ?line {{error, _, {unavailable_analysis, locals_not_used}}, _} =\n\txref_base:analyze(S, locals_not_used),\n ?line {{error, _, {unavailable_analysis, {call, foo}}}, _} =\n\txref_base:analyze(S, {call, foo}),\n ?line {{error, _, {unavailable_analysis, {use, foo}}}, _} =\n\txref_base:analyze(S, {use, foo}),\n ?line analyze(undefined_functions, [{x,undef,0}], S),\n ?line 5 = length(xref_base:info(S)),\n\n %% More: all info, conversions.\n\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n ?line ok = xref_base:delete(S),\n ok.\n\n\nadd(suite) -> [];\nadd(doc) -> [\"Add modules, applications, releases, directories\"];\nadd(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir, \"rel2\"),\n UDir = fname([CopyDir,\"dir\",\"unreadable\"]),\n DDir = fname(CopyDir,\"dir\"),\n UFile = fname([DDir, \"dir\",\"unreadable.beam\"]),\n X = fname(Dir, \"x.erl\"),\n Y = fname(Dir, \"y.erl\"),\n A1_1 = fname([Dir,\"lib\",\"app1-1.1\"]),\n A2 = fname([Dir,\"lib\",\"app2-1.1\"]),\n EB1_1 = fname(A1_1, \"ebin\"),\n EB2 = fname(A2, \"ebin\"),\n Xbeam = fname(EB2, \"x.beam\"),\n Ybeam = fname(EB1_1, \"y.beam\"),\n\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB2}]),\n ?line {ok, y} = compile:file(Y, [debug_info, {outdir,EB1_1}]),\n\n ?line case os:type() of\n\t {unix, _} ->\n\t\t ?line make_udir(UDir),\n\t\t ?line make_ufile(UFile);\n\t _ ->\n\t\t true\n\t end,\n\n ?line {error, _, {invalid_options,[not_an_option] }} =\n\txref_base:new([not_an_option]),\n ?line {error, _, {invalid_options,[{verbose,not_a_value}] }} =\n\txref_base:new([{verbose,not_a_value}]),\n ?line S = new(),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref_base:set_up(S, [not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,true},not_an_option]}} =\n\txref_base:add_directory(S, foo, [{builtins,true},not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref_base:add_directory(S, foo, [{builtins,not_a_value}]),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref_base:add_directory(S, {foo,bar}, []),\n ?line {error, _, {invalid_options,[{builtins,true},not_an_option]}} =\n\txref_base:add_module(S, foo, [{builtins,true},not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref_base:add_module(S, foo, [{builtins,not_a_value}]),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref_base:add_module(S, {foo,bar}, []),\n ?line {error, _, {invalid_options,[{builtins,true},not_an_option]}} =\n\txref_base:add_application(S, foo, [{builtins,true},not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref_base:add_application(S, foo, [{builtins,not_a_value}]),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref_base:add_application(S, {foo,bar}, []),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref_base:add_release(S, foo, [not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref_base:add_release(S, foo, [{builtins,not_a_value}]),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref_base:add_release(S, {foo,bar}, []),\n ?line {ok, S1} =\n\txref_base:set_default(S, [{verbose,false}, {warnings, false}]),\n ?line case os:type() of\n\t {unix, _} ->\n\t\t ?line {error, _, {file_error, _, _}} =\n\t\t xref_base:add_release(S, UDir);\n\t _ ->\n\t\t true\n\t end,\n ?line {error, _, {file_error, _, _}} =\n\txref_base:add_release(S, fname([\"\/a\/b\/c\/d\/e\/f\",\"__foo\"])),\n ?line {ok, release2, S2} =\n\txref_base:add_release(S1, Dir, [{name,release2}]),\n ?line {error, _, {module_clash, {x, _, _}}} =\n\txref_base:add_module(S2, Xbeam),\n ?line {ok, S3} = xref_base:remove_release(S2, release2),\n ?line {ok, rel2, S4} = xref_base:add_release(S3, Dir),\n ?line {error, _, {release_clash, {rel2, _, _}}} =\n\txref_base:add_release(S4, Dir),\n ?line {ok, S5} = xref_base:remove_release(S4, rel2),\n %% One unreadable file and one JAM file found (no verification here):\n ?line {ok, [], S6} = xref_base:add_directory(S5, fname(CopyDir,\"dir\"),\n\t\t\t\t\t [{recurse,true}, {warnings,true}]),\n ?line case os:type() of\n\t {unix, _} ->\n\t\t ?line {error, _, {file_error, _, _}} =\n\t\t xref_base:add_directory(S6, UDir);\n\t _ ->\n\t\t true\n\t end,\n ?line {ok, app1, S7} = xref_base:add_application(S6, A1_1),\n ?line {error, _, {application_clash, {app1, _, _}}} =\n\txref_base:add_application(S7, A1_1),\n ?line {ok, S8} = xref_base:remove_application(S7, app1),\n ?line ok = xref_base:delete(S8),\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n ?line case os:type() of\n\t {unix, _} ->\n\t\t ?line ok = file:del_dir(UDir),\n\t\t ?line ok = file:delete(UFile);\n\t _ ->\n\t\t true\n\t end,\n ok.\n\ndefault(suite) -> [];\ndefault(doc) -> [\"Default values of options\"];\ndefault(Conf) when is_list(Conf) ->\n S = new(),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref_base:set_default(S, not_an_option, true),\n ?line {error, _, {invalid_options,[{builtins, not_a_value}]}} =\n\txref_base:set_default(S, builtins, not_a_value),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref_base:get_default(S, not_an_option),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref_base:set_default(S, [not_an_option]),\n\n ?line D = xref_base:get_default(S),\n ?line [{builtins,false},{recurse,false},{verbose,false},{warnings,true}] =\n\tD,\n\n ?line ok = xref_base:delete(S),\n ok.\n\ninfo(suite) -> [];\ninfo(doc) -> [\"The info functions\"];\ninfo(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"rel2\"),\n LDir = fname(CopyDir,\"lib_test\"),\n X = fname(Dir, \"x.erl\"),\n Y = fname(Dir, \"y.erl\"),\n A1_1 = fname([Dir,\"lib\",\"app1-1.1\"]),\n A2 = fname([Dir,\"lib\",\"app2-1.1\"]),\n EB1_1 = fname(A1_1, \"ebin\"),\n EB2 = fname(A2, \"ebin\"),\n Xbeam = fname(EB2, \"x.beam\"),\n Ybeam = fname(EB1_1, \"y.beam\"),\n\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB2}]),\n ?line {ok, y} = compile:file(Y, [debug_info, {outdir,EB1_1}]),\n\n ?line {ok, _} = start(s),\n ?line {error, _, {no_such_info, release}} = xref:info(s, release),\n ?line {error, _, {no_such_info, release}} = xref:info(s, release, rel),\n ?line {error, _, {no_such_module, mod}} = xref:info(s, modules, mod),\n ?line {error, _, {no_such_application, app}} =\n\txref:info(s, applications, app),\n ?line {error, _, {no_such_release, rel}} = xref:info(s, releases, rel),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n ?line {ok, rel2} = xref:add_release(s, Dir),\n ?line 9 = length(xref:info(s)),\n ?line [{x,_}, {y, _}] = xref:info(s, modules),\n ?line [{app1,_}, {app2, _}] = xref:info(s, applications),\n ?line [{rel2,_}] = xref:info(s, releases),\n ?line [] = xref:info(s, libraries),\n ?line [{x,_}] = xref:info(s, modules, x),\n ?line [{rel2,_}] = xref:info(s, releases, rel2),\n ?line {error, _, {no_such_library, foo}} = xref:info(s, libraries, [foo]),\n\n ?line {ok, lib1} =\n\tcompile:file(fname(LDir,lib1),[debug_info,{outdir,LDir}]),\n ?line {ok, lib2} =\n\tcompile:file(fname(LDir,lib2),[debug_info,{outdir,LDir}]),\n ?line ok = xref:set_library_path(s, [LDir], [{verbose,false}]),\n ?line [{lib1,_}, {lib2, _}] = xref:info(s, libraries),\n ?line [{lib1,_}, {lib2, _}] = xref:info(s, libraries, [lib1,lib2]),\n ?line ok = file:delete(fname(LDir, \"lib1.beam\")),\n ?line ok = file:delete(fname(LDir, \"lib2.beam\")),\n\n ?line check_state(s),\n\n ?line xref:stop(s),\n\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n\n ok.\n\nlib(suite) -> [];\nlib(doc) -> [\"Library modules\"];\nlib(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"lib_test\"),\n UDir = fname([CopyDir,\"dir\",\"non_existent\"]),\n\n ?line {ok, lib1} = compile:file(fname(Dir,lib1),[debug_info,{outdir,Dir}]),\n ?line {ok, lib2} = compile:file(fname(Dir,lib2),[debug_info,{outdir,Dir}]),\n ?line {ok, lib3} = compile:file(fname(Dir,lib3),[debug_info,{outdir,Dir}]),\n ?line {ok, t} = compile:file(fname(Dir,t),[debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = start(s),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n ?line {ok, t} = xref:add_module(s, fname(Dir,\"t.beam\")),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref:set_library_path(s, [\"foo\"], [not_an_option]),\n ?line {error, _, {invalid_path,otp}} = xref:set_library_path(s,otp),\n ?line {error, _, {invalid_path,[\"\"]}} = xref:set_library_path(s,[\"\"]),\n ?line {error, _, {invalid_path,[[$a | $b]]}} =\n\txref:set_library_path(s,[[$a | $b]]),\n ?line {error, _, {invalid_path,[otp]}} = xref:set_library_path(s,[otp]),\n ?line {ok, []} = xref:get_library_path(s),\n ?line ok = xref:set_library_path(s, [Dir], [{verbose,false}]),\n ?line {ok, UnknownFunctions} = xref:q(s, \"U\"),\n ?line [{lib1,unknown,0}, {lib2,local,0},\n\t {lib2,unknown,0}, {unknown,unknown,0}]\n = UnknownFunctions,\n ?line {ok, [{lib2,f,0},{lib3,f,0}]} = xref:q(s, \"DF\"),\n ?line {ok, []} = xref:q(s, \"DF_1\"),\n ?line {ok, [{lib2,f,0}]} = xref:q(s, \"DF_2\"),\n ?line {ok, [{lib2,f,0}]} = xref:q(s, \"DF_3\"),\n\n ?line {ok, [unknown]} = xref:q(s, \"UM\"),\n ?line {ok, UnknownDefAt} = xref:q(s, \"(Lin)U\"),\n ?line [{{lib1,unknown,0},0},{{lib2,local,0},0}, {{lib2,unknown,0},0},\n\t {{unknown,unknown,0},0}] = UnknownDefAt,\n ?line {ok, LibFuns} = xref:q(s, \"X * LM\"),\n ?line [{lib2,f,0},{lib3,f,0}] = LibFuns,\n ?line {ok, LibMods} = xref:q(s, \"LM\"),\n ?line [lib1,lib2,lib3] = LibMods,\n ?line {ok, [{{lib2,f,0},0},{{lib3,f,0},0}]} = xref:q(s, \"(Lin) (LM * X)\"),\n ?line {ok, [{{lib1,unknown,0},0}, {{lib2,f,0},0}, {{lib2,local,0},0},\n\t\t{{lib2,unknown,0},0}, {{lib3,f,0},0}]} = xref:q(s,\"(Lin)LM\"),\n ?line {ok,[lib1,lib2,lib3,t,unknown]} = xref:q(s,\"M\"),\n ?line {ok,[{lib2,f,0},{lib3,f,0},{t,t,0}]} = xref:q(s,\"X * M\"),\n ?line check_state(s),\n\n ?line copy_file(fname(Dir, \"lib1.erl\"), fname(Dir,\"lib1.beam\")),\n ?line ok = xref:set_library_path(s, [Dir]),\n ?line {error, _, _} = xref:q(s, \"U\"),\n\n %% OTP-3921. AM and LM not always disjoint.\n ?line {ok, lib1} = compile:file(fname(Dir,lib1),[debug_info,{outdir,Dir}]),\n ?line {ok, lib1} = xref:add_module(s, fname(Dir,\"lib1.beam\")),\n ?line check_state(s),\n\n ?line {error, _, {file_error, _, _}} = xref:set_library_path(s, [UDir]),\n\n ?line xref:stop(s),\n ?line ok = file:delete(fname(Dir, \"lib1.beam\")),\n ?line ok = file:delete(fname(Dir, \"lib2.beam\")),\n ?line ok = file:delete(fname(Dir, \"lib3.beam\")),\n ?line ok = file:delete(fname(Dir, \"t.beam\")),\n\n ?line {ok, cp} = compile:file(fname(Dir,cp),[debug_info,{outdir,Dir}]),\n ?line {ok, _} = start(s),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n ?line {ok, cp} = xref:add_module(s, fname(Dir,\"cp.beam\")),\n ?line {ok, [{lists, sort, 1}]} = xref:q(s, \"U\"),\n ?line ok = xref:set_library_path(s, code_path),\n ?line {ok, []} = xref:q(s, \"U\"),\n ?line check_state(s),\n ?line xref:stop(s),\n ?line ok = file:delete(fname(Dir, \"cp.beam\")),\n ok.\n\nread(suite) -> [];\nread(doc) -> [\"Data read from the Abstract Code\"];\nread(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"read\"),\n File = fname(Dir, \"read\"),\n Beam = fname(Dir, \"read.beam\"),\n ?line {ok, read} = compile:file(File, [debug_info,{outdir,Dir}]),\n ?line do_read(File, abstract_v2),\n ?line copy_file(fname(Dir, \"read.beam.v1\"), Beam),\n ?line do_read(File, abstract_v1),\n ?line ok = file:delete(Beam),\n ok.\n\ndo_read(File, Version) ->\n ?line {ok, _} = start(s),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n ?line {ok, read} = xref:add_module(s, File),\n\n ?line {U, OK, OKB} = read_expected(Version),\n\n %% {ok, UC} = xref:q(s, \"(Lin) UC\"),\n %% RR = to_external(converse(family_to_relation(family(UC)))),\n %% lists:foreach(fun(X) -> io:format(\"~w~n\", [X]) end, RR),\n Unres = to_external(relation_to_family(converse(from_term(U)))),\n ?line {ok, Unres} =\txref:q(s, \"(Lin) UC\"),\n\n %% {ok, EE} = xref:q(s, \"(Lin) (E - UC)\"),\n %% AA = to_external(converse(family_to_relation(family(EE)))),\n %% lists:foreach(fun(X) -> io:format(\"~w~n\", [X]) end, AA),\n Calls = to_external(relation_to_family(converse(from_term(OK)))),\n ?line {ok, Calls} = xref:q(s, \"(Lin) (E - UC) \"),\n\n ?line ok = check_state(s),\n ?line {ok, UM} = xref:q(s, \"UM\"),\n ?line true = member('$M_EXPR', UM),\n\n ?line {ok, X} = xref:q(s, \"X\"),\n ?line true = member({read, module_info, 0}, X),\n ?line false = member({foo, module_info, 0}, X),\n ?line false = member({erlang, module_info, 0}, X),\n ?line {ok, Unknowns} = xref:q(s, \"U\"),\n ?line false = member({read, module_info, 0}, Unknowns),\n ?line true = member({foo, module_info, 0}, Unknowns),\n ?line true = member({erlang, module_info, 0}, Unknowns),\n ?line {ok, LC} = xref:q(s, \"LC\"),\n ?line true = member({{read,bi,0},{read,bi,0}}, LC),\n\n ?line ok = xref:set_library_path(s, add_erts_code_path(fname(code:lib_dir(kernel),ebin))),\n ?line io:format(\"~p~n\",[(catch xref:get_library_path(s))]),\n ?line {ok, X2} = xref:q(s, \"X\"),\n ?line ok = check_state(s),\n ?line true = member({read, module_info, 0}, X2),\n ?line false = member({foo, module_info, 0}, X2),\n ?line true = member({erlang, module_info, 0}, X2),\n ?line {ok, Unknowns2} = xref:q(s, \"U\"),\n ?line false = member({read, module_info, 0}, Unknowns2),\n ?line true = member({foo, module_info, 0}, Unknowns2),\n ?line false = member({erlang, module_info, 0}, Unknowns2),\n\n ?line ok = xref:remove_module(s, read),\n ?line {ok, read} = xref:add_module(s, File, [{builtins,true}]),\n\n UnresB = to_external(relation_to_family(converse(from_term(U)))),\n ?line {ok, UnresB} = xref:q(s, \"(Lin) UC\"),\n CallsB = to_external(relation_to_family(converse(from_term(OKB)))),\n ?line {ok, CallsB} = xref:q(s, \"(Lin) (E - UC) \"),\n ?line ok = check_state(s),\n ?line {ok, XU} = xref:q(s, \"XU\"),\n ?line Erl = set([{erlang,length,1},{erlang,integer,1},\n\t\t {erlang,binary_to_term,1}]),\n ?line [{erlang,binary_to_term,1},{erlang,length,1}] =\n\tto_external(intersection(set(XU), Erl)),\n ?line xref:stop(s).\n\n%% What is expected when xref_SUITE_data\/read\/read.erl is added:\nread_expected(Version) ->\n %% Line positions in xref_SUITE_data\/read\/read.erl:\n POS1 = 28, POS2 = POS1+10, POS3 = POS2+6, POS4 = POS3+6, POS5 = POS4+10,\n POS6 = POS5+5, POS7 = POS6+6, POS8 = POS7+6, POS9 = POS8+8,\n POS10 = POS9+10, POS11 = POS10+7, POS12 = POS11+8, POS13 = POS12+10,\n POS14 = POS13+18, POS15 = POS14+23,\n\n FF = {read,funfuns,0},\n U = [{POS1+5,{FF,{dist,'$F_EXPR',0}}},\n\t {POS1+8,{FF,{dist,'$F_EXPR',0}}},\n\t {POS2+8,{{read,funfuns,0},{expr,'$F_EXPR',1}}},\n\t {POS3+4,{FF,{expr,'$F_EXPR',2}}},\n\t {POS4+2,{FF,{modul,'$F_EXPR',1}}},\n\t {POS4+4,{FF,{spm,'$F_EXPR',1}}},\n\t {POS4+6,{FF,{spm,'$F_EXPR',1}}},\n\t {POS4+8,{FF,{spm,'$F_EXPR',1}}},\n\t {POS5+1,{FF,{'$M_EXPR','$F_EXPR',0}}},\n\t {POS5+2,{FF,{'$M_EXPR','$F_EXPR',0}}},\n\t {POS5+3,{FF,{'$M_EXPR','$F_EXPR',0}}},\n\t {POS6+1,{FF,{'$M_EXPR','$F_EXPR',0}}},\n\t {POS6+2,{FF,{'$M_EXPR','$F_EXPR',0}}},\n\t {POS6+4,{FF,{n,'$F_EXPR',-1}}},\n\t {POS7+1,{FF,{'$M_EXPR',f,1}}},\n\t {POS7+2,{FF,{'$M_EXPR',f,1}}},\n\t {POS8+2,{FF,{hej,'$F_EXPR',1}}},\n\t {POS8+3,{FF,{t,'$F_EXPR',1}}},\n\t {POS8+5,{FF,{a,'$F_EXPR',1}}},\n\t {POS8+7,{FF,{m,'$F_EXPR',1}}},\n\t {POS9+1,{FF,{'$M_EXPR',f,1}}},\n\t {POS9+3,{FF,{a,'$F_EXPR',1}}},\n\t {POS10+1,{FF,{'$M_EXPR',foo,1}}},\n\t {POS10+2,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS10+3,{FF,{'$M_EXPR','$F_EXPR',2}}},\n\t {POS10+4,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS10+5,{FF,{'$M_EXPR',san,1}}},\n\t {POS10+6,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS11+1,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS11+2,{FF,{'$M_EXPR','$F_EXPR',-1}}},\n\t {POS11+3,{FF,{m,f,-1}}},\n\t {POS11+4,{FF,{m,f,-1}}},\n\t {POS11+5,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS11+6,{FF,{'$M_EXPR','$F_EXPR',1}}},\n\t {POS12+1,{FF,{'$M_EXPR','$F_EXPR',-1}}},\n\t {POS12+4,{FF,{'$M_EXPR','$F_EXPR',2}}},\n\t {POS12+7,{FF,{'$M_EXPR','$F_EXPR',-1}}},\n\t {POS12+8,{FF,{m4,f4,-1}}},\n\t {POS13+2,{FF,{debug,'$F_EXPR',0}}},\n\t {POS13+3,{FF,{'$M_EXPR','$F_EXPR',-1}}},\n\t {POS14+8,{{read,bi,0},{'$M_EXPR','$F_EXPR',1}}}],\n\n O1 = [{20,{{read,lc,0},{ets,new,0}}},\n\t {21,{{read,lc,0},{ets,tab2list,1}}},\n\t {POS1+1,{FF,{erlang,spawn,1}}},\n\t {POS1+1,{FF,{mod17,fun17,0}}},\n\t {POS1+2,{FF,{erlang,spawn,1}}},\n\t {POS1+2,{FF,{read,local,0}}},\n\t {POS1+3,{FF,{erlang,spawn,1}}},\n\t {POS1+4,{FF,{dist,func,0}}},\n\t {POS1+4,{FF,{erlang,spawn,1}}},\n\t {POS1+5,{FF,{erlang,spawn,1}}},\n\t {POS1+6,{FF,{erlang,spawn_link,1}}},\n\t {POS1+6,{FF,{mod17,fun17,0}}},\n\t {POS1+7,{FF,{dist,func,0}}},\n\t {POS1+7,{FF,{erlang,spawn_link,1}}},\n\t {POS1+8,{FF,{erlang,spawn_link,1}}},\n\t {POS2+1,{FF,{d,f,0}}},\n\t {POS2+1,{FF,{dist,func,2}}},\n\t {POS2+1,{FF,{erlang,spawn,2}}},\n\t {POS2+2,{FF,{dist,func,2}}},\n\t {POS2+2,{FF,{erlang,spawn,2}}},\n\t {POS2+2,{FF,{mod42,func,0}}},\n\t {POS2+3,{FF,{d,f,0}}},\n\t {POS2+3,{FF,{dist,func,2}}},\n\t {POS2+3,{FF,{erlang,spawn_link,2}}},\n\t {POS2+4,{FF,{dist,func,2}}},\n\t {POS2+4,{FF,{erlang,spawn_link,2}}},\n\t {POS2+4,{FF,{mod42,func,0}}},\n\t {POS3+1,{FF,{dist,func,2}}},\n\t {POS3+3,{FF,{dist,func,2}}},\n\t {POS4+1,{FF,{erlang,spawn,4}}},\n\t {POS4+1,{FF,{modul,function,0}}},\n\t {POS4+2,{FF,{erlang,spawn,4}}},\n\t {POS4+3,{FF,{dist,func,2}}},\n\t {POS4+3,{FF,{erlang,spawn,4}}},\n\t {POS4+3,{FF,{spm,spf,2}}},\n\t {POS4+4,{FF,{dist,func,2}}},\n\t {POS4+4,{FF,{erlang,spawn,4}}},\n\t {POS4+5,{FF,{dist,func,2}}},\n\t {POS4+5,{FF,{erlang,spawn_link,4}}},\n\t {POS4+5,{FF,{spm,spf,2}}},\n\t {POS4+6,{FF,{dist,func,2}}},\n\t {POS4+6,{FF,{erlang,spawn_link,4}}},\n\t {POS4+7,{FF,{erlang,spawn_opt,4}}},\n\t {POS4+7,{FF,{read,bi,0}}},\n\t {POS4+7,{FF,{spm,spf,2}}},\n\t {POS4+8,{FF,{erlang,spawn_opt,4}}},\n\t {POS4+8,{FF,{read,bi,0}}},\n\t {POS5+1,{FF,{erlang,spawn,1}}},\n\t {POS5+2,{FF,{erlang,spawn,1}}},\n\t {POS5+3,{FF,{erlang,spawn_link,1}}},\n\t {POS6+1,{FF,{erlang,spawn,2}}},\n\t {POS6+2,{FF,{erlang,spawn_link,2}}},\n\t {POS7+1,{FF,{erlang,spawn,4}}},\n\t {POS7+2,{FF,{erlang,spawn_opt,4}}},\n\t {POS8+1,{FF,{hej,san,1}}},\n\t {POS8+4,{FF,{a,b,1}}},\n\t {POS8+4,{FF,{erlang,apply,2}}},\n\t {POS8+5,{FF,{erlang,apply,2}}},\n\t {POS8+6,{FF,{m,f,1}}},\n\t {POS9+1,{FF,{read,bi,0}}},\n\t {POS9+2,{FF,{a,b,1}}},\n\t {POS9+2,{FF,{erlang,apply,2}}},\n\t {POS9+3,{FF,{erlang,apply,2}}},\n\t {POS9+4,{FF,{erlang,apply,2}}},\n\t {POS9+4,{FF,{erlang,not_a_function,1}}},\n\t {POS9+5,{FF,{mod,func,2}}},\n\t {POS9+6,{FF,{erlang,apply,1}}},\n\t {POS9+7,{FF,{erlang,apply,2}}},\n\t {POS9+7,{FF,{math,add3,1}}},\n\t {POS9+8,{FF,{q,f,1}}},\n\t {POS10+4,{FF,{erlang,apply,2}}},\n\t {POS10+5,{FF,{mod1,fun1,1}}},\n\t {POS11+6,{FF,{erlang,apply,2}}},\n\t {POS12+1,{FF,{erlang,apply,2}}},\n\t {POS12+4,{FF,{erlang,apply,2}}},\n\t {POS12+5,{FF,{m3,f3,2}}},\n\t {POS12+7,{FF,{erlang,apply,2}}},\n\t {POS13+1,{FF,{dm,df,1}}},\n\t {POS13+6,{{read,bi,0},{foo,module_info,0}}},\n\t {POS13+7,{{read,bi,0},{read,module_info,0}}},\n\t {POS13+9,{{read,bi,0},{t,foo,1}}},\n\t {POS14+11,{{read,bi,0},{erlang,module_info,0}}},\n\t {POS14+17,{{read,bi,0},{read,bi,0}}}],\n\n OK = case Version of\n\t abstract_v1 ->\n [{0,{FF,{read,'$F_EXPR',178}}},\n {0,{FF,{modul,'$F_EXPR',179}}}]\n ++ O1;\n\t _ ->\n [{16,{FF,{read,'$F_EXPR',178}}},\n {17,{FF,{modul,'$F_EXPR',179}}}]\n ++\n O1\n\t end,\n\n %% When builtins =:= true:\n OKB1 = [{POS13+1,{FF,{erts_debug,apply,4}}},\n {POS13+2,{FF,{erts_debug,apply,4}}},\n {POS13+3,{FF,{erts_debug,apply,4}}},\n\t {POS1+3, {FF,{erlang,binary_to_term,1}}},\n {POS3+1, {FF,{erlang,spawn,3}}},\n {POS3+2, {FF,{erlang,spawn,3}}},\n {POS3+3, {FF,{erlang,spawn_link,3}}},\n {POS3+4, {FF,{erlang,spawn_link,3}}},\n {POS6+4, {FF,{erlang,spawn,3}}},\n\t {POS8+6,{FF,{erlang,apply,3}}},\n\t {POS8+7,{FF,{erlang,apply,3}}},\n\t {POS9+1,{FF,{erlang,apply,3}}},\n\t {POS9+5,{FF,{erlang,apply,3}}},\n\t {POS11+1,{FF,{erlang,apply,3}}},\n\t {POS11+2,{FF,{erlang,apply,3}}},\n\t {POS11+3,{FF,{erlang,apply,3}}},\n\t {POS11+4,{FF,{erlang,apply,3}}},\n\t {POS12+5,{FF,{erlang,apply,3}}},\n\t {POS12+8,{FF,{erlang,apply,3}}},\n {POS13+5, {{read,bi,0},{erlang,length,1}}},\n {POS14+3, {{read,bi,0},{erlang,length,1}}}],\n\n %% Operators (OTP-8647):\n OKB = case Version of\n abstract_v1 ->\n\t\t [{POS8+3, {FF,{erlang,apply,3}}},\n\t\t {POS10+1, {FF,{erlang,apply,3}}},\n\t\t {POS10+6, {FF,{erlang,apply,3}}}];\n _ ->\n [{POS13+16, {{read,bi,0},{erlang,'!',2}}},\n {POS13+16, {{read,bi,0},{erlang,'-',1}}},\n {POS13+16, {{read,bi,0},{erlang,self,0}}},\n {POS15+1, {{read,bi,0},{erlang,'>',2}}},\n {POS15+2, {{read,bi,0},{erlang,'-',2}}},\n {POS15+2, {{read,bi,0},{erlang,'*',2}}},\n {POS15+8, {{read,bi,0},{erlang,'\/',2}}}]\n end\n ++ [{POS14+19, {{read,bi,0},{erlang,'+',2}}},\n {POS14+21, {{read,bi,0},{erlang,'+',2}}},\n {POS13+16, {{read,bi,0},{erlang,'==',2}}},\n {POS14+15, {{read,bi,0},{erlang,'==',2}}},\n {POS13+5, {{read,bi,0},{erlang,'>',2}}},\n {POS14+3, {{read,bi,0},{erlang,'>',2}}}]\n\t++ OKB1 ++ OK,\n\n {U, OK, OKB}.\n\nread2(suite) -> [];\nread2(doc) -> [\"Data read from the Abstract Code (cont)\"];\nread2(Conf) when is_list(Conf) ->\n %% Handles the spawn_opt versions added in R9 (OTP-4180).\n %% Expected augmentations: try\/catch, cond.\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"read\"),\n File = fname(Dir, \"read2.erl\"),\n MFile = fname(Dir, \"read2\"),\n Beam = fname(Dir, \"read2.beam\"),\n Test = <<\"-module(read2).\n\t -compile(export_all).\n\n\t f() ->\n\t\t spawn_opt({read2,f}, % POS2\n\t\t\t [f()]),\n\t\t spawn_opt(fun() -> foo end, [link]),\n\t\t spawn_opt(f(),\n\t\t\t {read2,f}, [{min_heap_size,1000}]),\n\t\t spawn_opt(f(),\n\t\t\t fun() -> f() end, [flopp]),\n\t\t spawn_opt(f(),\n\t\t\t read2, f, [], []);\n\t f() ->\n\t\t %% Duplicated unresolved calls are ignored:\n\t\t (f())(foo,bar),(f())(foo,bar). % POS1\n \">>,\n ?line ok = file:write_file(File, Test),\n ?line {ok, read2} = compile:file(File, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, read2} = xref:add_module(s, MFile),\n ?line {U0, OK0} = read2_expected(),\n\n U = to_external(relation_to_family(converse(from_term(U0)))),\n OK = to_external(relation_to_family(converse(from_term(OK0)))),\n ?line {ok, U2} = xref:q(s, \"(Lin) UC\"),\n ?line {ok, OK2} = xref:q(s, \"(Lin) (E - UC)\"),\n ?line true = U =:= U2,\n ?line true = OK =:= OK2,\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File),\n ?line ok = file:delete(Beam),\n ok.\n\n\nread2_expected() ->\n POS1 = 16,\n POS2 = 5,\n FF = {read2,f,0},\n U = [{POS1,{FF,{'$M_EXPR','$F_EXPR',2}}}],\n OK = [{POS2,{FF,{erlang,spawn_opt,2}}},\n\t {POS2,{FF,FF}},\n\t {POS2+1,{FF,FF}},\n\t {POS2+2,{FF,{erlang,spawn_opt,2}}},\n\t {POS2+3,{FF,{erlang,spawn_opt,3}}},\n\t {POS2+3,{FF,FF}},\n\t {POS2+3,{FF,FF}},\n\t {POS2+5,{FF,{erlang,spawn_opt,3}}},\n\t {POS2+5,{FF,FF}},\n\t {POS2+6,{FF,FF}},\n\t {POS2+7,{FF,{erlang,spawn_opt,5}}},\n\t {POS2+7,{FF,FF}},\n\t {POS2+7,{FF,FF}},\n\t {POS1,{FF,FF}}],\n {U, OK}.\n\nremove(suite) -> [];\nremove(doc) -> [\"Remove modules, applications, releases\"];\nremove(Conf) when is_list(Conf) ->\n S = new(),\n ?line {error, _, {no_such_module, mod}} =\n\txref_base:remove_module(S, mod),\n ?line {error, _, {no_such_application, app}} =\n\txref_base:remove_application(S, app),\n ?line {error, _, {no_such_release, rel}} =\n\txref_base:remove_release(S, rel),\n ?line ok = xref_base:delete(S),\n ok.\n\nreplace(suite) -> [];\nreplace(doc) -> [\"Replace modules, applications, releases\"];\nreplace(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"rel2\"),\n X = fname(Dir, \"x.erl\"),\n Y = fname(Dir, \"y.erl\"),\n A1_0 = fname(Dir, fname(\"lib\",\"app1-1.0\")),\n A1_1 = fname(Dir, fname(\"lib\",\"app1-1.1\")),\n A2 = fname(Dir, fname(\"lib\",\"app2-1.1\")),\n EB1_0 = fname(A1_0, \"ebin\"),\n EB1_1 = fname(A1_1, \"ebin\"),\n Xbeam = fname(EB1_1, \"x.beam\"),\n Ybeam = fname(EB1_1, \"y.beam\"),\n\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB1_0}]),\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB1_1}]),\n ?line {ok, y} = compile:file(Y, [debug_info, {outdir,EB1_1}]),\n\n ?line {ok, _} = start(s),\n ?line {ok, false} = xref:set_default(s, verbose, false),\n ?line {ok, true} = xref:set_default(s, warnings, false),\n ?line {ok, rel2} = xref:add_release(s, Dir, []),\n ?line {error, _, _} = xref:replace_application(s, app1, \"no_data\"),\n ?line {error, _, {no_such_application, app12}} =\n\txref:replace_application(s, app12, A1_0, []),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref:replace_application(s, app1, {foo,bar}, []),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref:replace_application(s, foo, bar, [not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref:replace_application(s, foo, bar, [{builtins,not_a_value}]),\n ?line {ok, app1} =\n\txref:replace_application(s, app1, A1_0),\n ?line [{_, AppInfo}] = xref:info(s, applications, app1),\n ?line {value, {release, [rel2]}} = keysearch(release, 1, AppInfo),\n\n ?line {error, _, {no_such_module, xx}} =\n\txref:replace_module(s, xx, Xbeam, []),\n ?line {error, _, {invalid_options,[{builtins,true},not_an_option]}} =\n\txref:replace_module(s, foo, bar,[{builtins,true},not_an_option]),\n ?line {error, _, {invalid_options,[{builtins,not_a_value}]}} =\n\txref:replace_module(s, foo, bar, [{builtins,not_a_value}]),\n ?line {error, _, {invalid_filename,{foo,bar}}} =\n\txref:replace_module(s, x, {foo,bar}),\n ?line {ok, x} = xref:replace_module(s, x, Xbeam),\n ?line [{x, ModInfo}] = xref:info(s, modules, x),\n ?line {value, {application, [app1]}} =\n\tkeysearch(application, 1, ModInfo),\n\n ?line {ok, x} = compile:file(X, [no_debug_info, {outdir,EB1_1}]),\n ?line {error, _, {no_debug_info, _}} = xref:replace_module(s, x, Xbeam),\n ?line {error, _, {module_mismatch, x,y}} =\n\txref:replace_module(s, x, Ybeam),\n ?line case os:type() of\n\t {unix, _} ->\n\t\t ?line hide_file(Ybeam),\n\t\t ?line {error, _, {file_error, _, _}} =\n\t\t xref:replace_module(s, x, Ybeam);\n\t _ ->\n\t\t true\n\t end,\n ?line ok = xref:remove_module(s, x),\n ?line {error, _, {no_debug_info, _}} = xref:add_module(s, Xbeam),\n\n %% \"app2\" is ignored, the old application name is kept\n ?line {ok, app1} = xref:replace_application(s, app1, A2),\n\n ?line xref:stop(s),\n ?line ok = file:delete(fname(EB1_0, \"x.beam\")),\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n ok.\n\nupdate(suite) -> [];\nupdate(doc) -> [\"The update() function\"];\nupdate(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"update\"),\n Source = fname(Dir, \"x.erl\"),\n Beam = fname(Dir, \"x.beam\"),\n ?line copy_file(fname(Dir, \"x.erl.1\"), Source),\n ?line {ok, x} = compile:file(Source, [debug_info, {outdir,Dir}]),\n\n ?line {ok, _} = start(s),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n ?line {ok, [x]} = xref:add_directory(s, Dir, [{builtins,true}]),\n ?line {error, _, {invalid_options,[not_an_option]}} =\n\txref:update(s, [not_an_option]),\n ?line {ok, []} = xref:update(s),\n ?line {ok, [{erlang,atom_to_list,1}]} = xref:q(s, \"XU\"),\n\n ?line [{x, ModInfo}] = xref:info(s, modules, x),\n ?line case keysearch(directory, 1, ModInfo) of\n\t {value, {directory, Dir}} -> ok\n\t end,\n\n timer:sleep(2000), % make sure modification time has changed\n ?line copy_file(fname(Dir, \"x.erl.2\"), Source),\n ?line {ok, x} = compile:file(Source, [debug_info, {outdir,Dir}]),\n ?line {ok, [x]} = xref:update(s, []),\n ?line {ok, [{erlang,list_to_atom,1}]} = xref:q(s, \"XU\"),\n\n timer:sleep(2000),\n ?line {ok, x} = compile:file(Source, [no_debug_info,{outdir,Dir}]),\n ?line {error, _, {no_debug_info, _}} = xref:update(s),\n\n ?line xref:stop(s),\n ?line ok = file:delete(Beam),\n ?line ok = file:delete(Source),\n ok.\n\ndeprecated(suite) -> [];\ndeprecated(doc) -> [\"OTP-4695: Deprecated functions.\"];\ndeprecated(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n File = fname(Dir, \"depr.erl\"),\n MFile_r9c = fname(Dir, \"depr_r9c\"),\n MFile = fname(Dir, \"depr\"),\n Beam = fname(Dir, \"depr.beam\"),\n %% This file has been compiled to ?datadir\/depr_r9c.beam\n %% using the R9C compiler. From R10B and onwards the linter\n %% checks the 'deprecated' attribute as well.\n% Test = <<\"-module(depr).\n\n% -export([t\/0,f\/1,bar\/2,f\/2,g\/3]).\n\n% -deprecated([{f,1}, % DF\n% {bar,2,eventually}]). % DF_3\n% -deprecated([{f,1,next_major_release}]). % DF_2 (again)\n% -deprecated([{frutt,0,next_version}]). % message...\n% -deprecated([{f,2,next_major_release}, % DF_2\n% {g,3,next_version}, % DF_1\n% {ignored,10,100}]). % message...\n% -deprecated([{does_not_exist,1}]). % message...\n\n% -deprecated(foo). % message...\n\n% t() ->\n% frutt(1),\n% g(1,2, 3),\n% ?MODULE:f(10).\n\n% f(A) ->\n% ?MODULE:f(A,A).\n\n% f(X, Y) ->\n% ?MODULE:g(X, Y, X).\n\n% g(F, G, H) ->\n% ?MODULE:bar(F, {G,H}).\n\n% bar(_, _) ->\n% true.\n\n% frutt(_) ->\n% frutt().\n\n% frutt() ->\n% true.\n% \">>,\n\n% ?line ok = file:write_file(File, Test),\n% ?line {ok, depr_r9c} = compile:file(File, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, depr_r9c} = xref:add_module(s, MFile_r9c),\n M9 = depr_r9c,\n DF_1 = usort([{{M9,f,2},{M9,g,3}}]),\n DF_2 = usort(DF_1++[{{M9,f,1},{M9,f,2}},{{M9,t,0},{M9,f,1}}]),\n DF_3 = usort(DF_2++[{{M9,g,3},{M9,bar,2}}]),\n DF = usort(DF_3++[{{M9,t,0},{M9,f,1}}]),\n\n ?line {ok,DF} = xref:analyze(s, deprecated_function_calls),\n ?line {ok,DF_1} =\n xref:analyze(s, {deprecated_function_calls,next_version}),\n ?line {ok,DF_2} =\n xref:analyze(s, {deprecated_function_calls,next_major_release}),\n ?line {ok,DF_3} =\n xref:analyze(s, {deprecated_function_calls,eventually}),\n\n D = to_external(range(from_term(DF))),\n D_1 = to_external(range(from_term(DF_1))),\n D_2 = to_external(range(from_term(DF_2))),\n D_3 = to_external(range(from_term(DF_3))),\n\n ?line {ok,D} = xref:analyze(s, deprecated_functions),\n ?line {ok,D_1} =\n xref:analyze(s, {deprecated_functions,next_version}),\n ?line {ok,D_2} =\n xref:analyze(s, {deprecated_functions,next_major_release}),\n ?line {ok,D_3} =\n xref:analyze(s, {deprecated_functions,eventually}),\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n Test2= <<\"-module(depr).\n\n -export([t\/0,f\/1,bar\/2,f\/2,g\/3]).\n\n -deprecated([{'_','_',eventually}]). % DF_3\n -deprecated([{f,'_',next_major_release}]). % DF_2\n -deprecated([{g,'_',next_version}]). % DF_1\n -deprecated([{bar,2}]). % DF\n\n t() ->\n g(1,2, 3),\n ?MODULE:f(10).\n\n f(A) ->\n ?MODULE:f(A,A).\n\n f(X, Y) ->\n ?MODULE:g(X, Y, X).\n\n g(F, G, H) ->\n ?MODULE:bar(F, {G,H}).\n\n bar(_, _) ->\n ?MODULE:t().\n \">>,\n\n ?line ok = file:write_file(File, Test2),\n ?line {ok, depr} = compile:file(File, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, depr} = xref:add_module(s, MFile),\n\n M = depr,\n DFa_1 = usort([{{M,f,2},{M,g,3}}]),\n DFa_2 = usort(DFa_1++[{{M,f,1},{M,f,2}},{{M,t,0},{M,f,1}}]),\n DFa_3 = usort(DFa_2++[{{M,bar,2},{M,t,0}},{{M,g,3},{M,bar,2}}]),\n DFa = DFa_3,\n\n ?line {ok,DFa} = xref:analyze(s, deprecated_function_calls),\n ?line {ok,DFa_1} =\n xref:analyze(s, {deprecated_function_calls,next_version}),\n ?line {ok,DFa_2} =\n xref:analyze(s, {deprecated_function_calls,next_major_release}),\n ?line {ok,DFa_3} =\n xref:analyze(s, {deprecated_function_calls,eventually}),\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n %% All of the module is deprecated.\n Test3= <<\"-module(depr).\n\n -export([t\/0,f\/1,bar\/2,f\/2,g\/3]).\n\n -deprecated([{f,'_',next_major_release}]). % DF_2\n -deprecated([{g,'_',next_version}]). % DF_1\n -deprecated(module). % DF\n\n t() ->\n g(1,2, 3),\n ?MODULE:f(10).\n\n f(A) ->\n ?MODULE:f(A,A).\n\n f(X, Y) ->\n ?MODULE:g(X, Y, X).\n\n g(F, G, H) ->\n ?MODULE:bar(F, {G,H}).\n\n bar(_, _) ->\n ?MODULE:t().\n \">>,\n\n ?line ok = file:write_file(File, Test3),\n ?line {ok, depr} = compile:file(File, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, depr} = xref:add_module(s, MFile),\n\n DFb_1 = usort([{{M,f,2},{M,g,3}}]),\n DFb_2 = usort(DFb_1++[{{M,f,1},{M,f,2}},{{M,t,0},{M,f,1}}]),\n DFb_3 = DFb_2,\n DFb = usort(DFb_2++[{{M,bar,2},{M,t,0}},{{M,g,3},{M,bar,2}}]),\n\n ?line {ok,DFb} = xref:analyze(s, deprecated_function_calls),\n ?line {ok,DFb_1} =\n xref:analyze(s, {deprecated_function_calls,next_version}),\n ?line {ok,DFb_2} =\n xref:analyze(s, {deprecated_function_calls,next_major_release}),\n ?line {ok,DFb_3} =\n xref:analyze(s, {deprecated_function_calls,eventually}),\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File),\n ?line ok = file:delete(Beam),\n ok.\n\n\ntrycatch(suite) -> [];\ntrycatch(doc) -> [\"OTP-5152: try\/catch, final (?) version.\"];\ntrycatch(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n File = fname(Dir, \"trycatch.erl\"),\n MFile = fname(Dir, \"trycatch\"),\n Beam = fname(Dir, \"trycatch.beam\"),\n Test = <<\"-module(trycatch).\n\n -export([trycatch\/0]).\n\n trycatch() ->\n try\n foo:bar(),\n bar:foo() of\n 1 -> foo:foo();\n 2 -> bar:bar()\n catch\n error:a -> err:e1();\n error:b -> err:e2()\n after\n fini:shed()\n end.\n \">>,\n\n ?line ok = file:write_file(File, Test),\n ?line {ok, trycatch} = compile:file(File, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, trycatch} = xref:add_module(s, MFile),\n A = trycatch,\n {ok,[{{{A,A,0},{bar,bar,0}},[10]},\n {{{A,A,0},{bar,foo,0}},[8]},\n {{{A,A,0},{err,e1,0}},[12]},\n {{{A,A,0},{err,e2,0}},[13]},\n {{{A,A,0},{fini,shed,0}},[15]},\n {{{A,A,0},{foo,bar,0}},[7]},\n {{{A,A,0},{foo,foo,0}},[9]}]} =\n xref:q(s, \"(Lin) (E | trycatch:trycatch\/0)\"),\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File),\n ?line ok = file:delete(Beam),\n ok.\n\n\nfun_mfa(suite) -> [];\nfun_mfa(doc) -> [\"OTP-5653: fun M:F\/A.\"];\nfun_mfa(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n File = fname(Dir, \"fun_mfa.erl\"),\n MFile = fname(Dir, \"fun_mfa\"),\n Beam = fname(Dir, \"fun_mfa.beam\"),\n Test = <<\"-module(fun_mfa).\n\n -export([t\/0, t1\/0, t2\/0, t3\/0]).\n\n t() ->\n F = fun ?MODULE:t\/0,\n (F)().\n\n t1() ->\n F = fun t\/0,\n (F)().\n\n t2() ->\n fun ?MODULE:t\/0().\n\n t3() ->\n fun t3\/0().\n \">>,\n\n ?line ok = file:write_file(File, Test),\n A = fun_mfa,\n ?line {ok, A} = compile:file(File, [debug_info,{outdir,Dir}]),\n ?line {ok, _} = xref:start(s),\n ?line {ok, A} = xref:add_module(s, MFile, {warnings,false}),\n ?line {ok, [{{{A,t,0},{'$M_EXPR','$F_EXPR',0}},[7]},\n {{{A,t,0},{A,t,0}},[6]},\n {{{A,t1,0},{'$M_EXPR','$F_EXPR',0}},[11]},\n {{{A,t1,0},{A,t,0}},[10]},\n {{{A,t2,0},{A,t,0}},[14]},\n {{{A,t3,0},{fun_mfa,t3,0}},[17]}]} =\n xref:q(s, \"(Lin) E\"),\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File),\n ?line ok = file:delete(Beam),\n ok.\n\n%% Same as the previous test case, except that we use a BEAM file\n%% that was compiled by an R14 compiler to test backward compatibility.\nfun_mfa_r14(Conf) when is_list(Conf) ->\n Dir = ?config(data_dir, Conf),\n MFile = fname(Dir, \"fun_mfa_r14\"),\n\n A = fun_mfa_r14,\n {ok, _} = xref:start(s),\n {ok, A} = xref:add_module(s, MFile, {warnings,false}),\n {ok, [{{{A,t,0},{'$M_EXPR','$F_EXPR',0}},[7]},\n\t {{{A,t,0},{A,t,0}},[6]},\n\t {{{A,t1,0},{'$M_EXPR','$F_EXPR',0}},[11]},\n\t {{{A,t1,0},{A,t,0}},[10]},\n\t {{{A,t2,0},{A,t,0}},[14]},\n\t {{{A,t3,0},{A,t3,0}},[17]}]} =\n xref:q(s, \"(Lin) E\"),\n\n ok = check_state(s),\n xref:stop(s),\n\n ok.\n\n%% fun M:F\/A with varibles.\nfun_mfa_vars(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n File = fname(Dir, \"fun_mfa_vars.erl\"),\n MFile = fname(Dir, \"fun_mfa_vars\"),\n Beam = fname(Dir, \"fun_mfa_vars.beam\"),\n Test = <<\"-module(fun_mfa_vars).\n\n -export([t\/1, t1\/1, t2\/3]).\n\n t(Mod) ->\n F = fun Mod:bar\/2,\n (F)(a, b).\n\n t1(Name) ->\n F = fun ?MODULE:Name\/1,\n (F)(a).\n\n t2(Mod, Name, Arity) ->\n F = fun Mod:Name\/Arity,\n (F)(a).\n\n t3(Arity) ->\n F = fun ?MODULE:t\/Arity,\n (F)(1, 2, 3).\n\n t4(Mod, Name) ->\n F = fun Mod:Name\/3,\n (F)(a, b, c).\n\n t5(Mod, Arity) ->\n F = fun Mod:t\/Arity,\n (F)().\n \">>,\n\n ok = file:write_file(File, Test),\n A = fun_mfa_vars,\n {ok, A} = compile:file(File, [report,debug_info,{outdir,Dir}]),\n {ok, _} = xref:start(s),\n {ok, A} = xref:add_module(s, MFile, {warnings,false}),\n {ok, [{{{A,t,1},{'$M_EXPR','$F_EXPR',2}},[7]},\n\t {{{A,t,1},{'$M_EXPR',bar,2}},[6]},\n\t {{{A,t1,1},{'$M_EXPR','$F_EXPR',1}},[11]},\n\t {{{A,t1,1},{A,'$F_EXPR',1}},[10]},\n\t {{{A,t2,3},{'$M_EXPR','$F_EXPR',-1}},[14]},\n\t {{{A,t2,3},{'$M_EXPR','$F_EXPR',1}},[15]},\n\t {{{A,t3,1},{'$M_EXPR','$F_EXPR',3}},[19]},\n\t {{{A,t3,1},{fun_mfa_vars,t,-1}},[18]},\n\t {{{A,t4,2},{'$M_EXPR','$F_EXPR',3}},[22,23]},\n\t {{{A,t5,2},{'$M_EXPR','$F_EXPR',0}},[27]},\n\t {{{A,t5,2},{'$M_EXPR',t,-1}},[26]}]} =\n\txref:q(s, \"(Lin) E\"),\n\n ok = check_state(s),\n xref:stop(s),\n\n ok = file:delete(File),\n ok = file:delete(Beam),\n ok.\n\nqlc(suite) -> [];\nqlc(doc) -> [\"OTP-5195: A bug fix when using qlc:q\/1,2.\"];\nqlc(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n File = fname(Dir, \"qlc.erl\"),\n MFile = fname(Dir, \"qlc\"),\n Beam = fname(Dir, \"qlc.beam\"),\n Test = <<\"-module(qlc).\n\n -include_lib(\\\"stdlib\/include\/qlc.hrl\\\").\n\n -export([t\/0]).\n\n t() ->\n dets:open_file(t, []),\n dets:insert(t, [{1,a},{2,b},{3,c},{4,d}]),\n MS = ets:fun2ms(fun({X,Y}) when (X > 1) or (X < 5) -> {Y}\n end),\n QH1 = dets:table(t, [{traverse, {select, MS}}]),\n QH2 = qlc:q([{Y} || {X,Y} <- dets:table(t),\n (X > 1) or (X < 5)]),\n true = qlc:info(QH1) =:= qlc:info(QH2),\n dets:close(t),\n ok.\n \">>,\n\n ?line ok = file:write_file(File, Test),\n A = qlc,\n ?line {ok, A} = compile:file(File, [debug_info,{outdir,Dir}]),\n ?line {ok, _} = xref:start(s),\n ?line {ok, A} = xref:add_module(s, MFile, {warnings,false}),\n ?line {ok, _} = xref:q(s, \"(Lin) E\"), % is can be loaded\n\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File),\n ?line ok = file:delete(Beam),\n ok.\n\n\n\nanalyze(suite) -> [];\nanalyze(doc) -> [\"Simple analyses\"];\nanalyze(Conf) when is_list(Conf) ->\n S0 = new(),\n ?line {{error, _, {invalid_options,[not_an_option]}}, _} =\n\txref_base:analyze(S0, undefined_function_calls, [not_an_option]),\n ?line {{error, _, {invalid_query,{q}}}, _} = xref_base:q(S0,{q}),\n ?line {{error, _, {unknown_analysis,foo}}, _} = xref_base:analyze(S0, foo),\n ?line {{error, _, {unknown_constant,\"foo:bar\/-1\"}}, _} =\n xref_base:analyze(S0, {use,{foo,bar,-1}}),\n\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"rel2\"),\n X = fname(Dir, \"x.erl\"),\n Y = fname(Dir, \"y.erl\"),\n A1_1 = fname([Dir,\"lib\",\"app1-1.1\"]),\n A2 = fname([Dir,\"lib\",\"app2-1.1\"]),\n EB1_1 = fname(A1_1, \"ebin\"),\n EB2 = fname(A2, \"ebin\"),\n Xbeam = fname(EB2, \"x.beam\"),\n Ybeam = fname(EB1_1, \"y.beam\"),\n\n ?line {ok, x} = compile:file(X, [debug_info, {outdir,EB2}]),\n ?line {ok, y} = compile:file(Y, [debug_info, {outdir,EB1_1}]),\n\n ?line {ok, rel2, S1} = xref_base:add_release(S0, Dir, [{verbose,false}]),\n ?line S = set_up(S1),\n\n ?line {ok, _} =\n analyze(undefined_function_calls, [{{x,xx,0},{x,undef,0}}], S),\n ?line {ok, _} = analyze(undefined_functions, [{x,undef,0}], S),\n ?line {ok, _} = analyze(locals_not_used, [{x,l,0},{x,l1,0}], S),\n ?line {ok, _} = analyze(exports_not_used, [{x,xx,0},{y,t,0}], S),\n\n ?line {ok, _} =\n analyze(deprecated_function_calls, [{{y,t,0},{x,t,0}}], S),\n ?line {ok, _} = analyze({deprecated_function_calls,next_version}, [], S),\n ?line {ok, _} =\n analyze({deprecated_function_calls,next_major_release}, [], S),\n ?line {ok, _} = analyze({deprecated_function_calls,eventually},\n [{{y,t,0},{x,t,0}}], S),\n ?line {ok, _} = analyze(deprecated_functions, [{x,t,0}], S),\n ?line {ok, _} = analyze({deprecated_functions,next_version}, [], S),\n ?line {ok, _} =\n analyze({deprecated_functions,next_major_release}, [], S),\n ?line {ok, _} = analyze({deprecated_functions,eventually}, [{x,t,0}], S),\n\n ?line {ok, _} = analyze({call, {x,xx,0}}, [{x,undef,0}], S),\n ?line {ok, _} =\n analyze({call, [{x,xx,0},{x,l,0}]}, [{x,l1,0},{x,undef,0}], S),\n ?line {ok, _} = analyze({use, {x,l,0}}, [{x,l1,0}], S),\n ?line {ok, _} =\n analyze({use, [{x,l,0},{x,l1,0}]}, [{x,l,0},{x,l1,0}], S),\n\n ?line {ok, _} = analyze({module_call, x}, [x], S),\n ?line {ok, _} = analyze({module_call, [x,y]}, [x], S),\n ?line {ok, _} = analyze({module_use, x}, [x,y], S),\n ?line {ok, _} = analyze({module_use, [x,y]}, [x,y], S),\n\n ?line {ok, _} = analyze({application_call, app1}, [app2], S),\n ?line {ok, _} = analyze({application_call, [app1,app2]}, [app2], S),\n ?line {ok, _} = analyze({application_use, app2}, [app1,app2], S),\n ?line {ok, _} = analyze({application_use, [app1,app2]}, [app1,app2], S),\n\n ?line ok = xref_base:delete(S),\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n ok.\n\nbasic(suite) -> [];\nbasic(doc) -> [\"Use of operators\"];\nbasic(Conf) when is_list(Conf) ->\n ?line S0 = new(),\n\n F1 = {m1,f1,1},\n F6 = {m1,f2,6}, % X\n F2 = {m2,f1,2},\n F3 = {m2,f2,3}, % X\n F7 = {m2,f3,7}, % X\n F4 = {m3,f1,4}, % X\n F5 = {m3,f2,5},\n\n UF1 = {m1,f12,17},\n UF2 = {m17,f17,177},\n\n E1 = {F1,F3}, % X\n E2 = {F6,F7}, % X\n E3 = {F2,F6}, % X\n E4 = {F1,F4}, % X\n E5 = {F4,F5},\n E6 = {F7,F4}, % X\n E7 = {F1,F6},\n\n UE1 = {F2,UF2}, % X\n UE2 = {F5,UF1}, % X\n\n D1 = {F1,12},\n D6 = {F6,3},\n DefAt_m1 = [D1,D6],\n X_m1 = [F6],\n % L_m1 = [F1],\n XC_m1 = [E1,E2,E4],\n LC_m1 = [E7],\n LCallAt_m1 = [{E7,12}],\n XCallAt_m1 = [{E1,13},{E2,17},{E4,7}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n D2 = {F2,7},\n D3 = {F3,9},\n D7 = {F7,19},\n DefAt_m2 = [D2,D3,D7],\n X_m2 = [F3,F7],\n % L_m2 = [F2],\n XC_m2 = [E3,E6,UE1],\n LC_m2 = [],\n LCallAt_m2 = [],\n XCallAt_m2 = [{E3,96},{E6,12},{UE1,77}],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n D4 = {F4,6},\n D5 = {F5,97},\n DefAt_m3 = [D4,D5],\n X_m3 = [F4],\n % L_m3 = [F5],\n XC_m3 = [UE2],\n LC_m3 = [E5],\n LCallAt_m3 = [{E5,19}],\n XCallAt_m3 = [{UE2,22}],\n Info3 = #xref_mod{name = m3, app_name = [a3]},\n ?line S3 = add_module(S2, Info3, DefAt_m3, X_m3, LCallAt_m3, XCallAt_m3,\n\t\t\t XC_m3, LC_m3),\n\n Info4 = #xref_mod{name = m4, app_name = [a2]},\n ?line S4 = add_module(S3, Info4, [], [], [], [], [], []),\n\n AppInfo1 = #xref_app{name = a1, rel_name = [r1]},\n ?line S9 = add_application(S4, AppInfo1),\n AppInfo2 = #xref_app{name = a2, rel_name = [r1]},\n ?line S10 = add_application(S9, AppInfo2),\n AppInfo3 = #xref_app{name = a3, rel_name = [r2]},\n ?line S11 = add_application(S10, AppInfo3),\n\n RelInfo1 = #xref_rel{name = r1},\n ?line S12 = add_release(S11, RelInfo1),\n RelInfo2 = #xref_rel{name = r2},\n ?line S13 = add_release(S12, RelInfo2),\n\n ?line S = set_up(S13),\n\n ?line {ok, _} = eval(\"[m1,m2] + m:f\/1\", unknown_constant, S),\n ?line {ok, _} = eval(\"[m1, m2, m:f\/1]\", type_mismatch, S),\n\n ?line {ok, _} = eval(\"[m1, m1->m2]\", type_mismatch, S),\n ?line {ok, _} = eval(\"components:f\/1\", unknown_constant, S),\n ?line {ok, _} = eval(\"'of':f\/1\", unknown_constant, S),\n ?line {ok, _} = eval(\"of:f\/1\", parse_error, S),\n ?line {ok, _} = eval(\"components\", unknown_constant, S),\n ?line {ok, _} = eval(\"[components, of, closure]\", parse_error, S),\n ?line {ok, _} = eval(\"[components, 'of', closure]\", unknown_constant, S),\n\n ?line {ok, _} = eval(\"[a1->a2,m1->m2]\", type_mismatch, S),\n ?line {ok, _} = eval(\"a1->a2,m1->m2\", parse_error, S),\n\n ?line {ok, _} = eval(\"m1->a1\", type_mismatch, S),\n ?line {ok, _} = eval(\"[{m1,f1,1}] : App\", parse_error, S),\n ?line {ok, _} = eval(\"[{m1,f1,1}] : Fun\", [F1], S),\n ?line {ok, _} = eval(\"range X\", type_error, S),\n ?line {ok, _} = eval(\"domain X\", type_error, S),\n ?line {ok, _} = eval(\"range M\", type_error, S),\n ?line {ok, _} = eval(\"domain M\", type_error, S),\n\n % Misc.\n ?line {ok, _} = eval(\"not_a_prefix_operator m1\", parse_error, S),\n ?line {ok, _} = eval(f(\"(Mod) ~p\", [[F1,F6,F5]]), [m1,m3], S),\n ?line {ok, _} = eval(\"(Lin) M - (Lin) m1\",\n\t\t\t [{F2,7},{F3,9},{F7,19},{F4,6},{F5,97},{UF2,0}], S),\n ?line {ok, _} = eval(f(\"(Lin) M * (Lin) ~p\", [[F1,F6]]),\n\t\t\t [{F1,12},{F6,3}], S),\n\n ?line {ok, _} = eval(f(\"X * ~p\", [[F1, F2, F3, F4, F5]]), [F3, F4], S),\n ?line {ok, _} = eval(\"X\", [F6,F3,F7,F4], S),\n ?line {ok, _} = eval(\"X * AM\", [F6,F3,F7,F4], S),\n ?line {ok, _} = eval(\"X * a2\", [F3,F7], S),\n\n ?line {ok, _} = eval(\"L * r1\", [F1,F2], S),\n ?line {ok, _} = eval(\"U\", [UF1, UF2], S),\n ?line {ok, _} = eval(\"U * AM\", [UF1], S),\n ?line {ok, _} = eval(\"U * UM\", [UF2], S),\n ?line {ok, _} = eval(\"XU * [m1, m2]\", [F6,F3,F7,UF1], S),\n ?line {ok, _} = eval(\"LU * [m3, m4]\", [F5], S),\n ?line {ok, _} = eval(\"UU\", [F1,F2], S),\n\n ?line {ok, _} = eval(\"XC | m1\", [E1,E2,E4], S),\n ?line {ok, _} = eval(f(\"XC | ~p\", [F1]), [E1,E4], S),\n ?line {ok, _} = eval(f(\"(XXL) (Lin) (XC | ~p)\", [F1]),\n\t\t\t [{{D1,D3},[13]},{{D1,D4},[7]}],S),\n ?line {ok, _} = eval(f(\"XC | (~p + ~p)\", [F1, F2]), [E1,E4,E3,UE1], S),\n ?line {ok, _} = eval(f(\"(XXL) (Lin) (XC | ~p)\", [F1]),\n\t\t\t [{{D1,D3},[13]},{{D1,D4},[7]}], S),\n ?line {ok, _} = eval(\"LC | m3\", [E5], S),\n ?line {ok, _} = eval(f(\"LC | ~p\", [F1]), [E7], S),\n ?line {ok, _} = eval(f(\"LC | (~p + ~p)\", [F1, F4]), [E7, E5], S),\n ?line {ok, _} = eval(\"E | m1\", [E1,E2,E4,E7], S),\n ?line {ok, _} = eval(f(\"E | ~p\", [F1]), [E1,E7,E4], S),\n ?line {ok, _} = eval(f(\"E | (~p + ~p)\", [F1, F2]), [E1,E7,E4,E3,UE1], S),\n\n ?line {ok, _} = eval(\"XC || m1\", [E3,UE2], S),\n ?line {ok, _} = eval(f(\"XC || ~p\", [F6]), [E3], S),\n ?line {ok, _} = eval(f(\"XC || (~p + ~p)\", [F4, UF2]), [UE1,E4,E6], S),\n ?line {ok, _} = eval(\"LC || m3\", [E5], S),\n ?line {ok, _} = eval(f(\"LC || ~p\", [F1]), [], S),\n ?line {ok, _} = eval(f(\"LC || ~p\", [F6]), [E7], S),\n ?line {ok, _} = eval(f(\"LC || (~p + ~p)\", [F5, F6]), [E7,E5], S),\n ?line {ok, _} = eval(\"E || m1\", [E3,UE2,E7], S),\n ?line {ok, _} = eval(f(\"E || ~p\", [F6]), [E3,E7], S),\n ?line {ok, _} = eval(f(\"E || (~p + ~p)\", [F3,F4]), [E1,E4,E6], S),\n\n ?line {ok, _} = eval(f(\"~p + ~p\", [F1,F2]), [F1,F2], S),\n ?line {ok, _} = eval(f(\"~p * ~p\", [m1,[F1,F6,F2]]), [F1,F6], S),\n ?line {ok, _} = eval(f(\"~p * ~p\", [F1,F2]), [], S),\n\n %% range, domain\n ?line {ok, _} = eval(\"range (E || m1)\", [F6,UF1], S),\n ?line {ok, _} = eval(\"domain (E || m1)\", [F1,F2,F5], S),\n ?line {ok, _} = eval(f(\"E | domain ~p\", [[E1, {F2,F4}]]),\n\t\t\t [E1,E7,E4,E3,UE1], S),\n\n %% components, condensation, use, call\n ?line {ok, _} = eval(\"(Lin) components E\", type_error, S),\n ?line {ok, _} = eval(\"components (Lin) E\", type_error, S),\n ?line {ok, _} = eval(\"components V\", type_error, S),\n ?line {ok, _} = eval(\"components E + components E\", type_error, S),\n\n ?line {ok, _} = eval(f(\"range (closure E | ~p)\", [[F1,F2]]),\n\t\t\t [F6,F3,F7,F4,F5,UF1,UF2], S),\n ?line {ok, _} =\n\teval(f(\"domain (closure E || ~p)\", [[UF2,F7]]), [F1,F2,F6], S),\n ?line {ok, _} = eval(\"components E\", [], S),\n ?line {ok, _} = eval(\"components (Mod) E\", [[m1,m2,m3]], S),\n ?line {ok, _} = eval(\"components closure (Mod) E\", [[m1,m2,m3]], S),\n ?line {ok, _} = eval(\"condensation (Mod) E\",\n\t\t\t [{[m1,m2,m3],[m17]}], S),\n ?line {ok, _} = eval(\"condensation closure (Mod) E\",\n\t\t\t [{[m1,m2,m3],[m17]}], S),\n ?line {ok, _} = eval(\"condensation closure closure closure (Mod) E\",\n\t\t\t [{[m1,m2,m3],[m17]}], S),\n ?line {ok, _} = eval(\"weak condensation (Mod) E\",\n\t [{[m1,m2,m3],[m1,m2,m3]},{[m1,m2,m3],[m17]},{[m17],[m17]}], S),\n ?line {ok, _} = eval(\"strict condensation (Mod) E\",\n\t\t\t [{[m1,m2,m3],[m17]}], S),\n ?line {ok, _} = eval(\"range condensation (Mod) E\",\n\t\t\t [[m17]], S),\n ?line {ok, _} = eval(\"domain condensation (Mod) E\",\n\t\t\t [[m1,m2,m3]], S),\n\n %% |, ||, |||\n ?line {ok, _} = eval(\"(Lin) E || V\", type_error, S),\n ?line {ok, _} = eval(\"E ||| (Lin) V\", type_error, S),\n ?line {ok, _} = eval(\"E ||| m1\", [E7], S),\n ?line {ok, _} = eval(\"closure E ||| m1\", [E7,{F1,UF1},{F6,UF1}], S),\n ?line {ok, _} = eval(\"closure E ||| [m1,m2]\",\n\t [{F1,UF1},{F2,F7},{F1,F7},{F6,UF1},{F2,UF1},{F7,UF1},E7,E1,E2,E3], S),\n ?line {ok, _} = eval(\"AE | a1\", [{a1,a1},{a1,a2},{a1,a3}], S),\n\n %% path ('of')\n ?line {ok, _} = eval(\"(Lin) {m1,m2} of E\", type_error, S),\n ?line {ok, _} = eval(\"{m1,m2} of (Lin) E\", type_error, S),\n ?line [m1,m2] = eval(\"{m1,m2} of {m1,m2}\", S),\n ?line {ok, _} = eval(\"{m1,m2} of m1\", type_error, S),\n ?line {ok, _} = eval(\"{a3,m1} of ME\", type_mismatch, S),\n ?line [m1,m1] = eval(\"{m1} of ME\", S),\n ?line [m1,m1] = eval(\"{m1} of closure closure ME\", S),\n ?line false = eval(\"{m17} of ME\", S),\n ?line [m2,m1,m2] = eval(\"{m2} : Mod of ME\", S),\n ?line [m1,m2,m17] = eval(\"{m1, m17} of ME\", S),\n ?line [m1,m2,m17] = eval(\"m1 -> m17 of ME\", S),\n ?line {ok, _} = eval(\"[m1->m17,m17->m1] of ME\", type_error, S),\n ?line case eval(f(\"~p of E\", [{F1,F7,UF1}]), S) of\n\t [F1,F6,F7,F4,F5,UF1] -> ok\n\t end,\n ?line [a2,a1,a2] = eval(\"{a2} of AE\", S),\n\n %% weak\/strict\n ?line {ok, _} = eval(\"weak {m1,m2}\", [{m1,m1},{m1,m2},{m2,m2}], S),\n ?line {ok, _} = eval(\"strict [{m1,m1},{m1,m2},{m2,m2}]\", [{m1,m2}], S),\n ?line {ok, _} = eval(\"range weak [{m1,m2}] : Mod\", [m1,m2], S),\n ?line {ok, _} = eval(\"domain strict [{m1,m1},{m1,m2},{m2,m2}]\", [m1], S),\n\n %% #, number of\n ?line {ok, _} = eval(\"# [{r1,r2}] : Rel\", 1, S),\n ?line {ok, _} = eval(\"# [{a3,a1}] : App\", 1, S),\n ?line {ok, _} = eval(\"# AE\", 7, S),\n ?line {ok, _} = eval(\"# ME\", 8, S),\n ?line {ok, _} = eval(\"# AE + # ME\", 15, S),\n ?line {ok, _} = eval(\"# AE * # ME\", 56, S),\n ?line {ok, _} = eval(\"# AE - # ME\", -1, S),\n ?line {ok, _} = eval(\"# E\", 9, S),\n ?line {ok, _} = eval(\"# V\", 9, S),\n ?line {ok, _} = eval(\"# (Lin) E\", 9, S),\n ?line {ok, _} = eval(\"# (ELin) E\", 7, S),\n ?line {ok, _} = eval(\"# closure E\", type_error, S),\n ?line {ok, _} = eval(\"# weak {m1,m2}\", 3, S),\n ?line {ok, _} = eval(\"#strict condensation (Mod) E\", 1, S),\n ?line {ok, _} = eval(\"#components closure (Mod) E\", 1, S),\n ?line {ok, _} = eval(\"# range strict condensation (Mod) E\", 1, S),\n ok.\n\nmd(suite) -> [];\nmd(doc) -> [\"The xref:m() and xref:d() functions\"];\nmd(Conf) when is_list(Conf) ->\n CopyDir = ?copydir,\n Dir = fname(CopyDir,\"md\"),\n X = fname(Dir, \"x__x.erl\"),\n Y = fname(Dir, \"y__y.erl\"),\n Xbeam = fname(Dir, \"x__x.beam\"),\n Ybeam = fname(Dir, \"y__y.beam\"),\n\n ?line {error, _, {invalid_filename,{foo,bar}}} = xref:m({foo,bar}),\n ?line {error, _, {invalid_filename,{foo,bar}}} = xref:d({foo,bar}),\n\n ?line {ok, x__x} = compile:file(X, [debug_info, {outdir,Dir}]),\n ?line {ok, y__y} = compile:file(Y, [debug_info, {outdir,Dir}]),\n\n ?line {error, _, {no_such_module, foo_bar}} = xref:m(foo_bar),\n ?line OldPath = code:get_path(),\n ?line true = code:set_path([Dir | OldPath]),\n ?line MInfo = xref:m(x__x),\n ?line [{{x__x,t,1},{y__y,t,2}}] = info_tag(MInfo, undefined),\n ?line [] = info_tag(MInfo, unused),\n ?line [] = info_tag(MInfo, deprecated),\n ?line DInfo = xref:d(Dir),\n ?line [{{x__x,t,1},{y__y,t,2}}] = info_tag(DInfo, undefined),\n ?line [{y__y,l,0},{y__y,l1,0}] = info_tag(DInfo, unused),\n ?line [] = info_tag(MInfo, deprecated),\n\n %% Switch from 'functions' mode to 'modules' mode.\n ?line {ok, x__x} = compile:file(X, [no_debug_info, {outdir,Dir}]),\n ?line {ok, y__y} = compile:file(Y, [no_debug_info, {outdir,Dir}]),\n ?line MInfoMod = xref:m(x__x),\n ?line [{y__y,t,2}] = info_tag(MInfoMod, undefined),\n ?line [] = info_tag(MInfo, deprecated),\n ?line DInfoMod = xref:d(Dir),\n ?line [{y__y,t,2}] = info_tag(DInfoMod, undefined),\n ?line [] = info_tag(MInfo, deprecated),\n\n ?line true = code:set_path(OldPath),\n ?line ok = file:delete(Xbeam),\n ?line ok = file:delete(Ybeam),\n ok.\n\nq(suite) -> [];\nq(doc) -> [\"User queries\"];\nq(Conf) when is_list(Conf) ->\n ?line S0 = new(),\n ?line {ok, _} = eval(\"'foo\", parse_error, S0),\n ?line {ok, _} = eval(\"TT = E, TT = V\", variable_reassigned, S0),\n ?line {ok, _} = eval(\"TT = E, TTT\", unknown_variable, S0),\n ?line {ok, S} = eval(\"TT := E\", [], S0),\n ?line {ok, S1} = eval(\"TT * TT * TT\", [], S),\n ?line {ok, _S2} = xref_base:forget(S1, 'TT'),\n ok.\n\nvariables(suite) -> [];\nvariables(doc) -> [\"Setting and getting values of query variables\"];\nvariables(Conf) when is_list(Conf) ->\n ?line Sa = new(),\n ?line {{error, _, {invalid_options,[not_an_option]}}, _} =\n\txref_base:variables(Sa, [not_an_option]),\n ?line {error, _, {not_user_variable,foo}} = xref_base:forget(Sa, foo),\n ?line Sa1 = set_up(Sa),\n ?line {error, _, {not_user_variable,foo}} = xref_base:forget(Sa1, foo),\n ?line ok = xref_base:delete(Sa1),\n\n ?line S0 = new(),\n\n F1 = {m1,f1,1},\n F2 = {m2,f1,2},\n Lib = {lib1,f1,1}, % undefined\n\n E1 = {F1,F2},\n E2 = {F2,F1},\n E3 = {F1,Lib},\n\n D1 = {F1,12},\n DefAt_m1 = [D1],\n X_m1 = [F1],\n % L_m1 = [],\n XC_m1 = [E1,E3],\n LC_m1 = [],\n LCallAt_m1 = [],\n XCallAt_m1 = [{E1,13},{E3,17}],\n Info1 = #xref_mod{name = m1, app_name = [a1]},\n ?line S1 = add_module(S0, Info1, DefAt_m1, X_m1, LCallAt_m1, XCallAt_m1,\n\t\t\t XC_m1, LC_m1),\n\n D2 = {F2,7},\n DefAt_m2 = [D2],\n X_m2 = [F2],\n % L_m2 = [],\n XC_m2 = [E2],\n LC_m2 = [],\n LCallAt_m2 = [],\n XCallAt_m2 = [{E2,96}],\n Info2 = #xref_mod{name = m2, app_name = [a2]},\n ?line S2 = add_module(S1, Info2, DefAt_m2, X_m2, LCallAt_m2, XCallAt_m2,\n\t\t\t XC_m2, LC_m2),\n\n ?line S = set_up(S2),\n\n ?line eval(\"T1=E, T2=E*T1, T3 = T2*T2, T4=range T3, T5=T3|T4, T5\",\n\t [E1,E2,E3], S),\n ?line eval(\"((E*E)*(E*E)) | (range ((E*E)*(E*E)))\",\n\t [E1,E2,E3], S),\n ?line eval(\"T1=V*V,T2=T1*V,T3=V*V*V,T3\",\n\t [F1,F2,Lib], S),\n ?line eval(\"T1=V*V, T2=V*V, T1*T2\",\n\t [F1,F2,Lib], S),\n\n ?line {ok, S100} = eval(\"T0 := E\", [E1, E2, E3], S),\n ?line {ok, S101} = eval(\"T1 := E | m1\", [E1, E3], S100),\n ?line {ok, S102} = eval(\"T2 := E | m2\", [E2], S101),\n ?line {{ok, [{user, ['T0', 'T1', 'T2']}]}, _} = xref_base:variables(S102),\n ?line {ok, S103} = xref_base:forget(S102, 'T0'),\n ?line {{ok, [{user, ['T1', 'T2']}]}, S104} =\n\txref_base:variables(S103, [user]),\n ?line {ok, S105} = xref_base:forget(S104),\n ?line {{ok, [{user, []}]}, S106} = xref_base:variables(S105),\n ?line {{ok, [{predefined,_}]}, S107_0} =\n\txref_base:variables(S106, [predefined]),\n\n ?line {ok, S107_1} =\n\teval(\"TT := E, TT2 := V, TT1 := TT * TT\", [E1,E2,E3], S107_0),\n ?line {{ok, [{user, ['TT', 'TT1', 'TT2']}]}, _} =\n\txref_base:variables(S107_1),\n ?line {ok, S107} = xref_base:forget(S107_1),\n\n CopyDir = ?copydir,\n ?line Dir = fname(CopyDir,\"lib_test\"),\n Beam = fname(Dir, \"lib1.beam\"),\n\n ?line copy_file(fname(Dir, \"lib1.erl\"), Beam),\n ?line {ok, S108} =\n\txref_base:set_library_path(S107, [Dir], [{verbose,false}]),\n ?line {{error, _, _}, _} = xref_base:variables(S108, [{verbose,false}]),\n ?line {ok, S109} = xref_base:set_library_path(S108, [], [{verbose,false}]),\n\n ?line Tabs = length(ets:all()),\n\n ?line {ok, S110} = eval(\"Eplus := closure E, TT := Eplus\",\n\t\t\t 'closure()', S109),\n ?line {{ok, [{user, ['Eplus','TT']}]}, S111} = xref_base:variables(S110),\n ?line {ok, S112} = xref_base:forget(S111, ['TT','Eplus']),\n ?line true = Tabs =:= length(ets:all()),\n\n ?line {ok, NS0} = eval(\"Eplus := closure E\", 'closure()', S112),\n ?line {{ok, [{user, ['Eplus']}]}, NS} = xref_base:variables(NS0),\n ?line ok = xref_base:delete(NS),\n ?line true = Tabs =:= length(ets:all()),\n\n ?line ok = file:delete(Beam),\n ok.\n\nunused_locals(suite) -> [];\nunused_locals(doc) -> [\"OTP-5071. Too many unused functions.\"];\nunused_locals(Conf) when is_list(Conf) ->\n Dir = ?copydir,\n\n File1 = fname(Dir, \"a.erl\"),\n MFile1 = fname(Dir, \"a\"),\n Beam1 = fname(Dir, \"a.beam\"),\n Test1 = <<\"-module(a).\n -export([f\/1, g\/2]).\n\n f(X) ->\n Y = b:f(X),\n Z = b:g(Y),\n start(b, h, [Z]).\n\n g(X, Y) ->\n ok.\n\n start(M, F, A) ->\n spawn(M, F, A).\n \">>,\n ?line ok = file:write_file(File1, Test1),\n ?line {ok, a} = compile:file(File1, [debug_info,{outdir,Dir}]),\n\n File2 = fname(Dir, \"b.erl\"),\n MFile2 = fname(Dir, \"b\"),\n Beam2 = fname(Dir, \"b.beam\"),\n Test2 = <<\"-module(b).\n -export([f\/1, g\/2]).\n\n f(X) ->\n io:write(\\\"~w\\\", [X]),\n a:start(timer, sleep, [1000]).\n\n g(X, Y) ->\n apply(a, g, [X, Y]).\n \">>,\n\n ?line ok = file:write_file(File2, Test2),\n ?line {ok, b} = compile:file(File2, [debug_info,{outdir,Dir}]),\n\n ?line {ok, _} = xref:start(s),\n ?line {ok, a} = xref:add_module(s, MFile1),\n ?line {ok, b} = xref:add_module(s, MFile2),\n ?line {ok, []} = xref:analyse(s, locals_not_used),\n ?line ok = check_state(s),\n ?line xref:stop(s),\n\n ?line ok = file:delete(File1),\n ?line ok = file:delete(Beam1),\n ?line ok = file:delete(File2),\n ?line ok = file:delete(Beam2),\n ok.\n\n\nformat_error(suite) -> [];\nformat_error(doc) -> [\"Format error messages\"];\nformat_error(Conf) when is_list(Conf) ->\n ?line {ok, _Pid} = start(s),\n ?line ok = xref:set_default(s, [{verbose,false}, {warnings, false}]),\n\n %% Parse error messages.\n ?line \"Invalid regular expression \\\"add(\\\"\" ++ _ =\n fstring(xref:q(s,'\"add(\"')),\n ?line 'Invalid operator foo\\n' =\n\tfatom(xref:q(s,'foo E')),\n ?line 'Invalid wildcard variable \\'_Var\\' (only \\'_\\' is allowed)\\n'\n = fatom(xref:q(s,\"module:function\/_Var\")),\n ?line 'Missing type of regular expression \".*\"\\n'\n = fatom(xref:q(s,'\".*\"')),\n ?line 'Type does not match structure of constant: \\'M\\' : Fun\\n'\n = fatom(xref:q(s,\"'M' : Fun\")),\n ?line 'Type does not match structure of constant: \".*\" : Fun\\n'\n = fatom(xref:q(s,'\".*\" : Fun')),\n ?line 'Type does not match structure of constant: [m:f\/1, m1:f2\/3] : App\\n'\n\t= fatom(xref:q(s,\"[m:f\/1,m1:f2\/3] : App\")),\n ?line 'Parse error on line 1: syntax error before: \\'-\\'\\n' =\n\tfatom(xref:q(s,\"E + -\")),\n ?line \"Parse error on line 1: unterminated atom starting with 'foo'\\n\"\n = flatten(xref:format_error(xref:q(s,\"'foo\"))),\n ?line 'Parse error at end of string: syntax error before: \\n' =\n\tfatom(xref:q(s,\"E +\")),\n ?line 'Parse error on line 1: syntax error before: \\'Lin\\'\\n' =\n\tfatom(xref:q(s,\"Lin\")),\n\n %% Other messages\n ?line 'Variable \\'QQ\\' used before set\\n' =\n\tfatom(xref:q(s,\"QQ\")),\n ?line 'Unknown constant a\\n' =\n\tfatom(xref:q(s,\"{a} of E\")),\n\n %% Testing xref_parser:t2s\/1.\n ?line 'Variable assigned more than once: E := E + E\\n' =\n\tfatom(xref:q(s,\"E:=E + E\")),\n ?line 'Variable assigned more than once: E = E + E\\n' =\n\tfatom(xref:q(s,\"E=E + E\")),\n ?line \"Operator applied to argument(s) of different or invalid type(s): \"\n\t \"E + V * V\\n\" =\n\tflatten(xref:format_error(xref:q(s,\"E + (V * V)\"))),\n ?line {error,xref_compiler,{type_error,\"(V + V) * E\"}} =\n\txref:q(s,\"(V + V) * E\"),\n ?line \"Type does not match structure of constant: [m:f\/3 -> g:h\/17] : \"\n\t \"App\\n\" =\n flatten(xref:format_error(xref:q(s,\"[{{m,f,3},{g,h,17}}] : App\"))),\n ?line 'Type does not match structure of constant: [m -> f, g -> h] : Fun\\n'\n = fatom(xref:q(s,\"[{m,f},g->h] : Fun\")),\n ?line 'Type does not match structure of constant: {m, n, o} : Fun\\n' =\n\tfatom(xref:q(s,\"{m,n,o} : Fun\")),\n ?line {error,xref_compiler,{type_error,\"range (Lin) V\"}} =\n\txref:q(s,\"range ((Lin) V)\"),\n ?line {error,xref_compiler,{type_error,\"condensation range E\"}} =\n\txref:q(s,\"condensation (range E)\"),\n ?line {error,xref_compiler,{type_error,\"condensation (# E + # V)\"}} =\n\txref:q(s,\"condensation (# E + # V)\"),\n ?line {error,xref_compiler,{type_error,\"range (# E + # E)\"}} =\n\txref:q(s,\"range (#E + #E)\"),\n ?line {error,xref_compiler,{type_error,\"range (# E)\"}} =\n\txref:q(s,\"range #E\"), % Hm...\n ?line {error,xref_compiler,{type_error,\"E + # E\"}} =\n\txref:q(s,\"E + #E + #E\"), % Hm...\n ?line {error,xref_compiler,{type_error,\"V * E || V | V\"}} =\n\txref:q(s,\"V * (E || V) | V\"),\n ?line {error,xref_compiler,{type_error,\"E || (E | V)\"}} =\n\txref:q(s,\"V * E || (E | V)\"),\n ?line {error,xref_compiler,{type_error,\"E * \\\"m\\\" : Mod\"}} =\n\txref:q(s,'E * \"m\" : Mod'),\n ?line {error,xref_compiler,{type_error,\"E * (\\\"m\\\":f\/_ + m:\\\"f\\\"\/3)\"}} =\n\txref:q(s,'E * (\"m\":f\/_ + m:\"f\"\/3)'),\n\n ?line xref:stop(s),\n ok.\n\notp_7423(suite) -> [];\notp_7423(doc) -> [\"OTP-7423. Xref scanner bug.\"];\notp_7423(Conf) when is_list(Conf) ->\n ?line {ok, _Pid} = start(s),\n S = \"E | [compiler] : App || [{erlang,\n size,\n 1}] : Fun\",\n ?line {error,xref_compiler,{unknown_constant,\"compiler\"}} = xref:q(s,S),\n ?line xref:stop(s),\n ok.\n\notp_7831(suite) -> [];\notp_7831(doc) -> [\"OTP-7831. Allow anonymous Xref processes.\"];\notp_7831(Conf) when is_list(Conf) ->\n ?line {ok, Pid1} = xref:start([]),\n ?line xref:stop(Pid1),\n ?line {ok, Pid2} = xref:start([{xref_mode, modules}]),\n ?line xref:stop(Pid2),\n ok.\n\notp_10192(suite) -> [];\notp_10192(doc) ->\n [\"OTP-10192. Allow filenames with character codes greater than 126.\"];\notp_10192(Conf) when is_list(Conf) ->\n PrivDir = ?privdir,\n {ok, _Pid} = xref:start(s),\n Dir = filename:join(PrivDir, \"\u00e4\"),\n ok = file:make_dir(Dir),\n {ok, []} = xref:add_directory(s, Dir),\n xref:stop(s),\n ok.\n\n%%%\n%%% Utilities\n%%%\n\ncopy_file(Src, Dest) ->\n file:copy(Src, Dest).\n\nfname(N) ->\n filename:join(N).\n\nfname(Dir, Basename) ->\n filename:join(Dir, Basename).\n\nnew() ->\n ?line {ok, S} = xref_base:new(),\n S.\n\nset_up(S) ->\n ?line {ok, S1} = xref_base:set_up(S, [{verbose, false}]),\n S1.\n\neval(Query, E, S) ->\n ?format(\"------------------------------~n\", []),\n ?format(\"Evaluating ~p~n\", [Query]),\n ?line {Answer, NewState} = xref_base:q(S, Query, [{verbose, false}]),\n {Reply, Expected} =\n\tcase Answer of\n\t {ok, R} when is_list(E) ->\n\t\t{unsetify(R), sort(E)};\n\t {ok, R} ->\n\t\t{unsetify(R), E};\n\t {error, _Module, Reason} ->\n\t\t{element(1, Reason), E}\n\tend,\n if\n\tReply =:= Expected ->\n\t ?format(\"As expected, got ~n~p~n\", [Expected]),\n\t {ok, NewState};\n\ttrue ->\n\t ?format(\"Expected ~n~p~nbut got ~n~p~n\", [Expected, Reply]),\n\t not_ok\n end.\n\nanalyze(Query, E, S) ->\n ?format(\"------------------------------~n\", []),\n ?format(\"Evaluating ~p~n\", [Query]),\n ?line {{ok, L}, NewState} =\n\txref_base:analyze(S, Query, [{verbose, false}]),\n case {unsetify(L), sort(E)} of\n\t{X,X} ->\n\t ?format(\"As was expected, got ~n~p~n\", [X]),\n\t {ok, NewState};\n\t{_R,_X} ->\n\t ?format(\"Expected ~n~p~nbut got ~n~p~n\", [_X, _R]),\n\t not_ok\n end.\n\nunsetify(S) ->\n case is_sofs_set(S) of\n\ttrue -> to_external(S);\n\tfalse -> S\n end.\n\n%% Note: assumes S has been set up; the new state is not returned\neval(Query, S) ->\n ?line {{ok, Answer}, _NewState} =\n\txref_base:q(S, Query, [{verbose, false}]),\n unsetify(Answer).\n\nadd_module(S, XMod, DefAt, X, LCallAt, XCallAt, XC, LC) ->\n Attr = {[], [], []},\n Depr0 = {[], [], [], []},\n DBad = [],\n Depr = {Depr0,DBad},\n Data = {DefAt, LCallAt, XCallAt, LC, XC, X, Attr, Depr},\n Unres = [],\n ?line {ok, _Module, _Bad, State} =\n\txref_base:do_add_module(S, XMod, Unres, Data),\n State.\n\nadd_application(S, XApp) ->\n ?line xref_base:do_add_application(S, XApp).\n\nadd_release(S, XRel) ->\n ?line xref_base:do_add_release(S, XRel).\n\nremove_module(S, M) ->\n ?line xref_base:do_remove_module(S, M).\n\ninfo_tag(Info, Tag) ->\n {value, {_Tag, Value}} = lists:keysearch(Tag, 1, Info),\n Value.\n\nmake_ufile(FileName) ->\n ?line ok = file:write_file(FileName, term_to_binary(foo)),\n ?line hide_file(FileName).\n\nmake_udir(Dir) ->\n ?line ok = file:make_dir(Dir),\n ?line hide_file(Dir).\n\nhide_file(FileName) ->\n ?line {ok, FileInfo} = file:read_file_info(FileName),\n ?line NewFileInfo = FileInfo#file_info{mode = 0},\n ?line ok = file:write_file_info(FileName, NewFileInfo).\n\n%% Note that S has to be set up before calling this checking function.\ncheck_state(S) ->\n ?line Info = xref:info(S),\n\n ?line modules_mode_check(S, Info),\n case info(Info, mode) of\n\tmodules ->\n\t ok;\n\tfunctions ->\n\t functions_mode_check(S, Info)\n end.\n\n%% The manual mentions some facts that should always hold.\n%% Here they are again.\nfunctions_mode_check(S, Info) ->\n %% F = L + X,\n ?line {ok, F} = xref:q(S, \"F\"),\n ?line {ok, F} = xref:q(S, \"L + X\"),\n\n %% V = X + L + B + U,\n ?line {ok, V} = xref:q(S, \"V\"),\n ?line {ok, V} = xref:q(S, \"X + L + B + U\"),\n\n %% X, L, B and U are disjoint.\n ?line {ok, []} =\n\txref:q(S, \"X * L + X * B + X * U + L * B + L * U + B * U\"),\n\n %% V = UU + XU + LU,\n ?line {ok, V} = xref:q(S, \"UU + XU + LU\"),\n\n %% E = LC + XC\n ?line {ok, E} = xref:q(S, \"E\"),\n ?line {ok, E} = xref:q(S, \"LC + XC\"),\n\n %% U subset of XU,\n ?line {ok, []} = xref:q(S, \"U - XU\"),\n\n %% LU = range LC\n ?line {ok, []} = xref:q(S, \"(LU - range LC) + (range LC - LU)\"),\n\n %% XU = range XC\n ?line {ok, []} = xref:q(S, \"(XU - range XC) + (range XC - XU)\"),\n\n %% LU subset F\n ?line {ok, []} = xref:q(S, \"LU - F\"),\n\n %% UU subset F\n ?line {ok, []} = xref:q(S, \"UU - F\"),\n\n %% ME = (Mod) E\n ?line {ok, ME} = xref:q(S, \"ME\"),\n ?line {ok, ME} = xref:q(S, \"(Mod) E\"),\n\n %% AE = (App) E\n ?line {ok, AE} = xref:q(S, \"AE\"),\n ?line {ok, AE} = xref:q(S, \"(App) E\"),\n\n %% RE = (Rel) E\n ?line {ok, RE} = xref:q(S, \"RE\"),\n ?line {ok, RE} = xref:q(S, \"(Rel) E\"),\n\n %% (Mod) V subset of M\n ?line {ok, []} = xref:q(S, \"(Mod) V - M\"),\n\n %% range UC subset of U\n ?line {ok, []} = xref:q(S, \"range UC - U\"),\n\n %% Some checks on the numbers returned by the info functions.\n\n ?line {Resolved, Unresolved} = info(Info, no_calls),\n ?line AllCalls = Resolved + Unresolved,\n ?line {ok, AllCalls} = xref:q(S, \"# (XLin) E + # (LLin) E\"),\n\n ?line {Local, Exported} = info(Info, no_functions),\n ?line LX = Local+Exported,\n ?line {ok, LXs} = xref:q(S, 'Extra = _:module_info\/\"(0|1)\" + LM,\n\t\t\t\t # (F - Extra)'),\n ?line true = LX =:= LXs,\n\n ?line {LocalCalls, ExternalCalls, UnresCalls} =\n info(Info, no_function_calls),\n ?line LEU = LocalCalls + ExternalCalls + UnresCalls,\n ?line {ok, LEU} = xref:q(S, \"# LC + # XC\"),\n\n ?line InterFunctionCalls = info(Info, no_inter_function_calls),\n ?line {ok, InterFunctionCalls} = xref:q(S, \"# EE\"),\n\n %% And some more checks on counters...\n ?line check_count(S),\n\n %% ... and more\n ?line {ok, []} = xref:q(S, \"LM - X - U - B\"),\n\n ok.\n\nmodules_mode_check(S, Info) ->\n %% B subset of XU,\n ?line {ok, []} = xref:q(S, \"B - XU\"),\n\n %% M = AM + LM + UM\n ?line {ok, M} = xref:q(S, \"M\"),\n ?line {ok, M} = xref:q(S, \"AM + LM + UM\"),\n\n %% DF is a subset of X U B, etc.\n ?line {ok, []} = xref:q(S, \"DF - X - B\"),\n ?line {ok, []} = xref:q(S, \"DF_3 - DF\"),\n ?line {ok, []} = xref:q(S, \"DF_2 - DF_3\"),\n ?line {ok, []} = xref:q(S, \"DF_1 - DF_2\"),\n\n %% AM, LM and UM are disjoint.\n ?line {ok, []} = xref:q(S, \"AM * LM + AM * UM + LM * UM\"),\n\n %% (App) M subset of A\n ?line {ok, []} = xref:q(S, \"(App) M - A\"),\n\n ?line AM = info(Info, no_analyzed_modules),\n ?line {ok, AM} = xref:q(S, \"# AM\"),\n\n ?line A = info(Info, no_applications),\n ?line {ok, A} = xref:q(S, \"# A\"),\n\n ?line NoR = info(Info, no_releases),\n ?line {ok, NoR} = xref:q(S, \"# R\"),\n\n ok.\n\n%% Checks the counters of some of the overall and modules info functions.\n%% (Applications and releases are not checked.)\ncheck_count(S) ->\n %%{ok, R} = xref:q(S, 'R'),\n %% {ok, A} = xref:q(S, 'A'),\n {ok, M} = xref:q(S, 'AM'),\n\n {ok, _} = xref:q(S,\n\t \"Extra := _:module_info\/\\\"(0|1)\\\" + LM\"),\n\n %% info\/1:\n {ok, NoR} = xref:q(S, '# R'),\n {ok, NoA} = xref:q(S, '# A'),\n {ok, NoM} = xref:q(S, '# AM'),\n {ok, NoCalls} = xref:q(S, '# (XLin) E + # (LLin) E'),\n {ok, NoFunCalls} = xref:q(S, '# E'),\n {ok, NoXCalls} = xref:q(S, '# XC'),\n {ok, NoLCalls} = xref:q(S, '# LC'),\n {ok, NoLXCalls} = xref:q(S, '# (XC * LC)'),\n NoAllCalls = NoXCalls + NoLCalls,\n {ok, NoFun} = xref:q(S, '# (F - Extra)'),\n {ok, NoICalls} = xref:q(S, '# EE'),\n\n Info = xref:info(S),\n NoR = info(Info, no_releases),\n NoA = info(Info, no_applications),\n NoM = info(Info, no_analyzed_modules),\n {NoResolved, NoUC} = info(Info, no_calls),\n NoCalls = NoResolved + NoUC,\n {NoLocal, NoExternal, NoUnres} = info(Info, no_function_calls),\n NoAllCalls = NoLocal + NoExternal + NoUnres,\n NoAllCalls = NoFunCalls + NoLXCalls,\n {NoLocalFuns, NoExportedFuns} = info(Info, no_functions),\n NoFun = NoLocalFuns + NoExportedFuns,\n NoICalls = info(Info, no_inter_function_calls),\n\n %% per module\n info_module(M, S),\n\n ok.\n\ninfo_module([M | Ms], S) ->\n {ok, NoCalls} = per_module(\"T = (E | ~p : Mod), # (XLin) T + # (LLin) T\",\n\t\t\t M, S),\n {ok, NoFunCalls} = per_module(\"# (E | ~p : Mod)\", M, S),\n {ok, NoXCalls} = per_module(\"# (XC | ~p : Mod)\", M, S),\n {ok, NoLCalls} = per_module(\"# (LC | ~p : Mod)\", M, S),\n {ok, NoLXCalls} = per_module(\"# ((XC * LC) | ~p : Mod)\", M, S),\n NoAllCalls = NoXCalls + NoLCalls,\n {ok, NoFun} = per_module(\"# (F * ~p : Mod - Extra)\", M, S),\n {ok, NoICalls} = per_module(\"# (EE | ~p : Mod)\", M, S),\n\n [{_M,Info}] = xref:info(S, modules, M),\n {NoResolved, NoUC} = info(Info, no_calls),\n NoCalls = NoResolved + NoUC,\n {NoLocal, NoExternal, NoUnres} = info(Info, no_function_calls),\n NoAllCalls = NoLocal + NoExternal + NoUnres,\n NoAllCalls = NoFunCalls + NoLXCalls,\n {NoLocalFuns, NoExportedFuns} = info(Info, no_functions),\n NoFun = NoLocalFuns + NoExportedFuns,\n NoICalls = info(Info, no_inter_function_calls),\n\n info_module(Ms, S);\ninfo_module([], _S) ->\n ok.\n\nper_module(Q, M, S) ->\n xref:q(S, f(Q, [M])).\n\ninfo(Info, What) ->\n {value, {What, Value}} = lists:keysearch(What, 1, Info),\n Value.\n\nf(S, A) ->\n flatten(io_lib:format(S, A)).\n\nfatom(R) ->\n list_to_atom(fstring(R)).\n\nfstring(R) ->\n flatten(xref:format_error(R)).\n\nstart(Server) ->\n ?line case xref:start(Server) of\n\t {error, {already_started, _Pid}} ->\n\t\t ?line xref:stop(Server),\n\t\t ?line xref:start(Server);\n\t R -> R\n\t end.\n\nadd_erts_code_path(KernelPath) ->\n VersionDirs =\n\tfilelib:is_dir(\n\t filename:join(\n\t [code:lib_dir(),\n\t lists:flatten(\n\t [\"kernel-\",\n\t\t[X ||\n\t\t {kernel,_,X} <-\n\t\t\tapplication_controller:which_applications()]])])),\n case VersionDirs of\n\ttrue ->\n\t case code:lib_dir(erts) of\n\t\tString when is_list(String) ->\n\t\t [KernelPath, fname(String,\"ebin\")];\n\t\t_Other1 ->\n\t\t [KernelPath]\n\t end;\n\tfalse ->\n\t % Clearcase?\n\t PrelPath = filename:join([code:lib_dir(),\"..\",\"erts\",\"preloaded\"]),\n\t case filelib:is_dir(PrelPath) of\n\t\ttrue ->\n\t\t [KernelPath, fname(PrelPath,\"ebin\")];\n\t\tfalse ->\n\t\t [KernelPath]\n\t end\n end.\n\n\n","avg_line_length":34.3812898653,"max_line_length":94,"alphanum_fraction":0.5195930904} +{"size":184,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(rebar3_shaderc).\n\n-export([init\/1]).\n\n-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.\ninit(State) ->\n {ok, State1} = rebar3_shaderc_prv:init(State),\n {ok, State1}.\n","avg_line_length":20.4444444444,"max_line_length":53,"alphanum_fraction":0.6358695652} +{"size":377,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"-module(hackerlrank).\n\n%% API exports\n-export([]).\n\n%%====================================================================\n%% API functions\n%%====================================================================\n\n\n%%====================================================================\n%% Internal functions\n%%====================================================================\n","avg_line_length":26.9285714286,"max_line_length":70,"alphanum_fraction":0.1644562334} +{"size":3517,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%-------------------------------------------------------------------\n%%% @author Annette Jebastina\n%%% @copyright (C) 2020\n%%% @doc\n%%%\n%%% @end\n%%% Created : December 03 2020\n%%%-------------------------------------------------------------------\n\n-module(dynamodbtask_client).\n\n-behaviour(gen_server).\n\n-include(\"dynamodbtask_pb.hrl\").\n-include(\"defines.hrl\").\n\n-export([start_link\/0,\n stop\/0,\n set_request\/2,\n get_request\/1]).\n\n-export([init\/1,\n handle_call\/3,\n handle_cast\/2,\n handle_info\/2,\n terminate\/2,\n code_change\/3]).\n\n-record(state, {socket}).\n\nstart_link() ->\n gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).\n\nset_request(Key, Value) ->\n gen_server:call(?MODULE, {set_request, Key, Value}).\n\nget_request(Key) ->\n gen_server:call(?MODULE, {get_request, Key}).\n\nstop() -> gen_server:stop(?MODULE).\n \n%%------------------------------------------------------------------------------\ninit([]) ->\n {ok, Socket} = gen_tcp:connect(\"localhost\", ?PORT, [binary, {active, false}, {packet, 0},{keepalive,true}, {recbuf, 99999}], infinity),% Change the server's IP if needed\n {ok, #state{socket = Socket}}.\n\nhandle_call({set_request, Key, Value}, _From, #state{socket = Socket} = State) ->\n Request = #set_request{req = #data{key = Key, value = Value}},\n Binary_Request = dynamodbtask_pb:encode_msg(#req_envelope{type = set_request_t, set_req = Request}),\n ok = gen_tcp:send(Socket, base64:encode(Binary_Request)),\n case recv_resp(Socket) of\n {error, Error} -> \n gen_tcp:close(Socket),\n {stop, closed, {error, Error}, State};\n Response -> \n Reply = decode_message(Response),\n {reply, Reply, State}\n end;\nhandle_call({get_request, Key}, _From, #state{socket = Socket} = State) ->\n Request = #get_request{key = Key},\n Binary_Request = dynamodbtask_pb:encode_msg(#req_envelope{type = get_request_t, get_req = Request}),\n ok = gen_tcp:send(Socket, base64:encode(Binary_Request)),\n case recv_resp(Socket) of\n {error, Error} -> \n gen_tcp:close(Socket),\n {stop, closed, {error, Error}, State};\n Response -> \n Reply = decode_message(Response),\n {reply, Reply, State}\n end;\nhandle_call(_Request, _From, State) ->\n {reply, ok, State}.\n\nhandle_cast(_Request, State) ->\n {noreply, State}.\n\nhandle_info(tcp_closed, State) ->\n gen_tcp:close(State#state.socket),\n {stop, closed, State};\nhandle_info(_Info, State) ->\n {noreply, State}.\n\nterminate(_Reason, State) ->\n gen_tcp:close(State#state.socket).\n\ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n\n%%------------------------------------------------------------------------------\n%% Internal Functions\n%%------------------------------------------------------------------------------\nrecv_resp(Socket) ->\n case gen_tcp:recv(Socket, 0, 3000) of\n {ok, Data} -> Data;\n Error -> Error\n end.\n\ndecode_message(Msg) ->\n DecodedMsg = dynamodbtask_pb:decode_msg(Msg, req_envelope),\n process_message(DecodedMsg).\n\nprocess_message(#req_envelope{type = set_response_t, set_resp = #set_response{error = Error}}) -> Error;\n\nprocess_message(#req_envelope{type = get_response_t, get_resp = #get_response{error = ok, req = #data{value = Value}}}) -> Value;\n\nprocess_message(#req_envelope{type = get_response_t, get_resp = #get_response{error = Error}}) -> {error, Error}.\n","avg_line_length":32.8691588785,"max_line_length":173,"alphanum_fraction":0.5624111459} +{"size":1652,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% Copyright (c) 2018 EMQ Technologies Co., Ltd. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n-module(emqx_mqtt_types).\n\n-include(\"emqx_mqtt.hrl\").\n\n-export_type([version\/0, qos\/0, qos_name\/0]).\n-export_type([connack\/0, reason_code\/0]).\n-export_type([properties\/0, subopts\/0]).\n-export_type([topic_filters\/0]).\n-export_type([packet_id\/0, packet_type\/0, packet\/0]).\n\n-type(qos() :: ?QOS_0 | ?QOS_1 | ?QOS_2).\n-type(version() :: ?MQTT_PROTO_V3 | ?MQTT_PROTO_V4 | ?MQTT_PROTO_V5).\n-type(qos_name() :: qos0 | at_most_once |\n qos1 | at_least_once |\n qos2 | exactly_once).\n-type(packet_type() :: ?RESERVED..?AUTH).\n-type(connack() :: ?CONNACK_ACCEPT..?CONNACK_AUTH).\n-type(reason_code() :: 0..16#FF).\n-type(packet_id() :: 1..16#FFFF).\n-type(properties() :: #{atom() => term()}).\n-type(subopts() :: #{rh := 0 | 1 | 2,\n rap := 0 | 1,\n nl := 0 | 1,\n qos := qos(),\n rc => reason_code()\n }).\n-type(topic_filters() :: [{emqx_topic:topic(), subopts()}]).\n-type(packet() :: #mqtt_packet{}).\n","avg_line_length":38.4186046512,"max_line_length":75,"alphanum_fraction":0.6222760291} +{"size":1485,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(wallet_server).\n-export([start_link\/0, deposit\/1, withdraw\/1, get_balance\/0]).\n\n%% gen_server callbacks\n-export([init\/1, handle_call\/3, handle_cast\/2, handle_info\/2, terminate\/2,\n code_change\/3]).\n\n-include_lib(\"kernel\/include\/logger.hrl\").\n-include(\"..\/exo_records.hrl\").\n\n-behaviour(gen_server).\n-define(SERVER, ?MODULE).\n-record(state, {}).\n\nstart_link() ->\n gen_server:start_link({global, ?SERVER}, ?MODULE, [], []). \n\ndeposit(Amount) ->\n gen_server:call({global, ?MODULE}, {deposit, Amount}).\n\nwithdraw(Amount) ->\n gen_server:call({global, ?MODULE}, {withdraw, Amount}).\n\nget_balance() ->\n gen_server:call({global, ?MODULE}, {get_balance}).\n\ninit([]) ->\n ?LOG_NOTICE(\"Wallet server has been started - ~p\", [self()]),\n {ok, #state{}}.\n\nhandle_call({deposit, Amount}, _From, State) ->\n NewBalance=State#wallet.balance+Amount,\n {reply, {ok, NewBalance}, State#wallet{balance=NewBalance}};\n\nhandle_call({withdraw, Amount}, _From, State) when State#wallet.balance\n {reply, not_enough_money, State};\n\nhandle_call({withdraw, Amount}, _From, State) ->\n NewBalance=State#wallet.balance-Amount,\n {reply, {ok, NewBalance}, State#wallet{balance=NewBalance}};\n\nhandle_call(_Request, _From, State) ->\n {noreply, State}.\n \nhandle_cast(_Request, State) ->\n {noreply, State}.\n \nhandle_info(_Info, State) ->\n {noreply, State}.\n \nterminate(_Reason, _State) ->\n ok.\n \ncode_change(_OldVsn, State, _Extra) ->\n {ok, State}.\n","avg_line_length":26.5178571429,"max_line_length":81,"alphanum_fraction":0.67003367} +{"size":118,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(proper_dialyzer).\n\n-export([gen\/0]).\n\n-include_lib(\"proper\/include\/proper.hrl\").\n\ngen() ->\n oneof([1, 2]).\n","avg_line_length":13.1111111111,"max_line_length":42,"alphanum_fraction":0.6271186441} +{"size":2355,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%% ==========================================================================================================\n%% PHPASS - A simple implementation of PHPass\u2019 Portable Hash.\n%%\n%% The MIT License (MIT)\n%%\n%% Copyright (c) 2019 Roberto Ostinelli .\n%%\n%% Permission is hereby granted, free of charge, to any person obtaining a copy\n%% of this software and associated documentation files (the \"Software\"), to deal\n%% in the Software without restriction, including without limitation the rights\n%% to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n%% copies of the Software, and to permit persons to whom the Software is\n%% furnished to do so, subject to the following conditions:\n%%\n%% The above copyright notice and this permission notice shall be included in\n%% all copies or substantial portions of the Software.\n%%\n%% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n%% THE SOFTWARE.\n%% ==========================================================================================================\n-module(phpass_sup).\n-behaviour(supervisor).\n\n%% API\n-export([start_link\/0]).\n\n%% Supervisor callbacks\n-export([init\/1]).\n\n%% Helper macro for declaring children of supervisor\n-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 10000, Type, [I]}).\n\n\n%% ===================================================================\n%% API\n%% ===================================================================\n-spec start_link() -> {ok, pid()} | {already_started, pid()} | shutdown.\nstart_link() ->\n supervisor:start_link({local, ?MODULE}, ?MODULE, []).\n\n%% ===================================================================\n%% Callbacks\n%% ===================================================================\n-spec init([]) ->\n {ok, {{supervisor:strategy(), non_neg_integer(), pos_integer()}, [supervisor:child_spec()]}}.\ninit([]) ->\n Children = [],\n {ok, {{one_for_one, 10, 10}, Children}}.\n","avg_line_length":43.6111111111,"max_line_length":109,"alphanum_fraction":0.5639065817} +{"size":30388,"ext":"hrl","lang":"Erlang","max_stars_count":null,"content":"%% @author Marc Worrell \n%% @copyright 2011-2016 Marc Worrell\n%% @doc Notifications used in Zotonic core\n\n%% Copyright 2011-2016 Marc Worrell\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n\n%% @doc Try to find the site for the request\n%% Called when the request Host doesn't match any active site.\n%% Type: first\n%% Return: ``{ok, #dispatch_redirect{}}`` or ``undefined``\n-record(dispatch_host, {\n host = <<>> :: binary(),\n path = <<>> :: binary(),\n method = <<\"GET\">> :: binary(),\n protocol = http :: http|https\n}).\n\n%% @doc Final try for dispatch, try to match the request.\n%% Called when the site is known, but no match is found for the path\n%% Type: first\n%% Return: ``{ok, RscId::integer()}``, ``{ok, #dispatch_match{}}``, ``{ok, #dispatch_redirect{}}`` or ``undefined``\n-record(dispatch, {\n host = <<>> :: binary(),\n path = <<>> :: binary(),\n method = <<\"GET\">> :: binary(),\n protocol = http :: http|https,\n tracer_pid = undefined :: pid()|undefined\n}).\n\n-record(dispatch_redirect, {\n location = <<>> :: binary(),\n is_permanent = false :: boolean()\n}).\n-record(dispatch_match, {\n dispatch_name = undefined :: atom(),\n mod :: atom(),\n mod_opts = [] :: list(),\n path_tokens = [] :: list(binary()),\n bindings = [] :: list({atom(), binary()})\n}).\n\n\n%% @doc Modify cookie options, used for setting http_only and secure options. (foldl)\n-record(cookie_options, {name, value}).\n\n% 'module_ready' - Sent when modules have changed, z_module_indexer reindexes all modules' templates, actions etc.\n\n%% @doc A module has been activated and started. (notify)\n-record(module_activate, {\n module :: atom(),\n pid :: pid()\n}).\n\n%% @doc A module has been stopped and deactivated. (notify)\n-record(module_deactivate, {\n module :: atom()\n}).\n\n\n%% @doc Possibility to overrule a property of a resource (currently only the title)\n-record(rsc_property, {\n id :: m_rsc:resource(),\n property :: atom(),\n value :: term()\n}).\n\n%% @doc Get available content types and their dispatch rules\n%% Example: {\"text\/html\", page}\n%% A special dispatch rule is 'page_url', which refers to the page_url property of the resource.\n%% Type: foldr\n%% Return: ``[{ContentType, DispatchRule}]``\n-record(content_types_dispatch, {\n id :: m_rsc:resource()\n}).\n\n%% @doc Check where to go after a user logs on.\n%% Type: first\n%% Return: a URL or ``undefined``\n-record(logon_ready_page, {\n request_page = [] :: string()\n}).\n\n%% @doc Determine post-logon actions; args are the arguments passed to the logon\n%% submit wire\n-record(logon_actions, {\n args = [] :: list()\n}).\n\n%% @doc Handle a user logon. The posted query args are included.\n%% Type: first\n%% Return:: ``{ok, UserId}`` or ``{error, Reason}``\n-record(logon_submit, {\n query_args = [] :: list()\n}).\n\n%% @doc Request to send a verification to the user. Return ok or an error\n%% Type: first\n%% Identity may be undefined, or is a identity used for the verification.\n-record(identity_verification, {user_id, identity}).\n\n%% @doc Notification that a user's identity has been verified.\n%% Type: notify\n-record(identity_verified, {user_id, type, key}).\n\n-record(identity_password_match, {rsc_id, password, hash}).\n\n\n%% @doc Handle a signup of a user, return the follow on page for after the signup.\n%% Type: first\n%% Return ``{ok, Url}``\n%% 'props' is a proplist with properties for the person resource (email, name, etc)\n%% 'signup_props' is a proplist with 'identity' definitions and optional follow on url 'ready_page'\n%% An identity definition is {Kind, Identifier, IsUnique, IsVerified}\n-record(signup_url, {\n props = [] :: list(),\n signup_props = [] :: list()\n}).\n\n%% @doc Request a signup of a new or existing user. Arguments are similar to #signup_url{}\n%% Returns {ok, UserId} or {error, Reason}\n-record(signup, {\n id :: integer(),\n props = [] :: list(),\n signup_props = [] :: list(),\n request_confirm = false :: boolean()\n}).\n\n%% @doc Signup failed, give the error page URL. Return {ok, Url} or undefined.\n%% Reason is returned by the signup handler for the particular signup method (username, facebook etc)\n%% Type: first\n-record(signup_failed_url, {\n reason\n}).\n\n%% signup_check\n%% Check if the signup can be handled, a fold over all modules.\n%% Fold argument\/result is {ok, Props, SignupProps} or {error, Reason}\n%% Type: foldl\n%% Return: ``{ok, Props, SignupProps}`` or ``{error, Reason}``\n-record(signup_check, {\n props = [] :: list(),\n signup_props = [] :: list()\n}).\n\n%% @doc Signal that a user has been signed up (map, result is ignored)\n-record(signup_done, {\n id :: m_rsc:resource(),\n is_verified :: boolean(),\n props :: list(),\n signup_props :: list()\n}).\n\n%% @doc Signal that a user has been confirmed. (map, result is ignored)\n-record(signup_confirm, {\n id :: m_rsc:resource()\n}).\n\n%% @doc Fetch the page a user is redirected to after signing up with a confirmed identity (first)\n%% Return: a URL or ``undefined``\n-record(signup_confirm_redirect, {\n id :: m_rsc:resource()\n}).\n\n\n%% @doc Handle a javascript notification from the postback handler. The 'message' is the z_msg argument of\n%% the request. (first), 'trigger' the id of the element which triggered the postback, and 'target' the\n%% id of the element which should receive possible updates. Note: postback_notify is also used as an event.\n%% Return: ``undefined`` or ``#context{}`` with the result of the postback\n-record(postback_notify, {message, trigger, target, data}).\n\n%% @doc Message sent by a user-agent on a postback event. Encapsulates the encoded postback and any\n%% additional data. This is handled by z_transport.erl, which will call the correct event\/2 functions.\n-record(postback_event, {postback, trigger, target, triggervalue, data}).\n\n%% @doc Notification to signal an inserted comment.\n%% 'comment_id' is the id of the inserted comment, 'id' is the id of the resource commented on.\n%% Type: notify\n-record(comment_insert, {comment_id, id}).\n\n%% @doc Notify that the session's language has been changed\n%% Type: notify\n-record(language, {language}).\n\n%% @doc Set the language of the context to a user's prefered language\n%% Type: first\n-record(set_user_language, {id}).\n\n%% @doc Make a generated URL absolute, optionally called after url_rewrite by z_dispatcher\n%% Type: first\n-record(url_abs, {url, dispatch, dispatch_options}).\n\n%% @doc Rewrite a URL after it has been generated using the z_dispatcher\n%% Type: foldl\n-record(url_rewrite, {\n dispatch :: atom(),\n args = [] :: list()\n}).\n\n%% @doc Rewrite a URL before it will be dispatched using the z_sites_dispatcher\n%% Type: foldl\n-record(dispatch_rewrite, {\n is_dir = false :: boolean(),\n path = \"\" :: string(),\n host\n}).\n\n%% @doc Request the SSL certificates for this site. The server_name property contains the hostname used by the client. (first)\n%% Returns either 'undefined' or a list of ssl options (type ssl:ssl_option())\n-record(ssl_options, {server_name :: binary()}).\n\n%% @doc Used in the admin to fetch the possible blocks for display\n%% Type: foldl\n-record(admin_edit_blocks, {id}).\n\n%% @doc Used in the admin to process a submitted resource form\n-record(admin_rscform, {id, is_a}).\n\n%% @doc Used for fetching the menu in the admin.\n%% Type: foldl\n%% Return: list of admin menu items\n-record(admin_menu, {}).\n\n%% @doc Fetch the menu id belonging to a certain resource\n%% Type: first\n-record(menu_rsc, {\n id :: m_rsc:resource()\n}).\n\n%% @doc An activity in Zotonic. When this is handled as a notification then return a list\n%% of patterns matching this activity. These patterns are then used to find interested\n%% subscribers.\n%% Type: map\n-record(activity, {\n version = 1 :: pos_integer(),\n posted_time,\n actor,\n verb = post :: atom(),\n object, target\n}).\n\n%% @doc Push a list of activities via a 'channel' (eg 'email') to a recipient.\n%% The activities are a list of #activity{} records.\n%% Type: first\n-record(activity_send, {\n recipient_id,\n channel,\n queue,\n activities = [] :: list()\n}).\n\n\n%% @doc e-mail notification used by z_email and z_email_server.\n-record(email, {\n to = [] :: list(),\n cc = [] :: list(),\n bcc = [] :: list(),\n from = [] :: list(),\n reply_to,\n headers = [] :: list(),\n body,\n raw,\n subject,\n text,\n html,\n text_tpl,\n html_tpl,\n vars = [] :: list(),\n attachments = [] :: list(),\n queue = false :: boolean()\n}).\n\n%% @doc Notification sent to a site when e-mail for that site is received\n-record(email_received, {\n to,\n from,\n localpart,\n localtags,\n domain,\n reference,\n email,\n headers,\n is_bulk = false :: boolean(),\n is_auto = false :: boolean(),\n decoded,\n raw\n}).\n\n% E-mail received notification:\n% {z_convert:to_atom(Notification), received, UserId, ResourceId, Received}\n% The {Notification, UserId, ResourceId} comes from m_email_receive_recipient:get_by_recipient\/2.\n\n%% @doc Email status notification, sent when the validity of an email recipient changes\n%% Type: notify\n-record(email_status, {\n recipient :: binary(),\n is_valid :: boolean(),\n is_final :: boolean()\n}).\n\n%% @doc Bounced e-mail notification. The recipient is the e-mail that is bouncing. When the\n%% the message_nr is unknown the it is set to 'undefined'. This can happen if it is a \"late bounce\".\n%% If the recipient is defined then the Context is the depickled z_email:send\/2 context.\n%% (notify)\n-record(email_bounced, {\n message_nr :: binary(),\n recipient :: undefined | binary()\n}).\n\n%% @doc Notify that we could send an e-mail (there might be a bounce later...)\n%% The Context is the depickled z_email:send\/2 context.\n%% Type: notify\n-record(email_sent, {\n message_nr :: binary(),\n recipient :: binary(),\n is_final :: boolean() % Set to true after waiting 4 hours for bounces\n}).\n\n%% @doc Notify that we could NOT send an e-mail (there might be a bounce later...)\n%% The Context is the depickled z_email:send\/2 context.\n%% Type: notify\n-record(email_failed, {\n message_nr :: binary(),\n recipient :: binary(),\n is_final :: boolean(),\n reason :: retry | illegal_address | smtphost | error,\n status :: binary()\n}).\n\n\n%% @doc Add a handler for receiving e-mail notifications\n%% Type: first\n%% Return: ``{ok, LocalFrom}``, the unique localpart of an e-mail address on this server.\n-record(email_add_handler, {notification, user_id, resource_id}).\n-record(email_ensure_handler, {notification, user_id, resource_id}).\n\n%% @doc Drop an e-mail handler for a user\/resource id. (notify).\n%% The notification, user and resource should be the same as when the handler was registered.\n-record(email_drop_handler, {notification, user_id, resource_id}).\n\n\n%% @doc Send a page to a mailinglist (notify)\n%% Use {single_test_address, Email} when sending to a specific e-mail address.\n-record(mailinglist_mailing, {list_id, page_id}).\n\n%% @doc Send a welcome or goodbye message to the given recipient. (notify).\n%% The recipient is either an e-mail address or a resource id.\n%% 'what' is send_welcome, send_confirm, send_goobye or silent.\n-record(mailinglist_message, {what, list_id, recipient}).\n\n%% @doc Save (and update) the complete category hierarchy (notify)\n-record(category_hierarchy_save, {tree}).\n\n%% @doc Save the menu tree of a menu resource (notify)\n-record(menu_save, {id, tree}).\n\n%% @doc Signal that the hierarchy underneath a resource has been changed by mod_menu\n%% Type: notify\n-record(hierarchy_updated, {\n root_id :: binary() | integer(),\n predicate :: atom(),\n inserted_ids = [] :: list(integer()),\n deleted_ids = [] :: list(integer())\n}).\n\n%% @doc Resource is read, opportunity to add computed fields\n%% Used in a foldr with the read properties as accumulator.\n-record(rsc_get, {id}).\n\n%% @doc Resource will be deleted.\n%% This notification is part of the delete transaction, it's purpose is to clean up\n%% associated data.\n%% Type: notify\n-record(rsc_delete, {id, is_a}).\n\n%% @doc Foldr for an resource insert, modify the insertion properties.\n%% Type: foldr\n-record(rsc_insert, {}).\n\n%% @doc Map to signal merging two resources. Move any information from the looser to the\n%% winner. The looser will be deleted.\n-record(rsc_merge, {\n winner_id :: integer(),\n looser_id :: integer()\n}).\n\n%% @doc An updated resource is about to be persisted.\n%% Observe this notification to change the resource properties before they are\n%% persisted.\n%% The props are the resource's props _before_ the update.\n%% The folded value is {IsChanged, UpdateProps} for the update itself.\n%% Set IsChanged to true if you modify the UpdateProps.\n%% Type: foldr\n%% Return: ``{true, ChangedProps}`` or ``{false, Props}``\n-record(rsc_update, {\n action :: insert | update,\n id :: m_rsc:resource(),\n props :: list()\n}).\n\n%% @doc An updated resource has just been persisted. Observe this notification to\n%% execute follow-up actions for a resource update.\n%% Type: notify\n%% Return: return value is ignored\n-record(rsc_update_done, {\n action :: insert | update | delete,\n id :: m_rsc:resource(),\n pre_is_a :: list(),\n post_is_a :: list(),\n pre_props :: list(),\n post_props :: list()\n}).\n\n%% @doc Upload and replace the the resource with the given data. The data is in the given format.\n%% Return {ok, Id} or {error, Reason}, return {error, badarg} when the data is corrupt.\n-record(rsc_upload, {id, format :: json|bert, data}).\n\n%% @doc Add custom pivot fields to a resource's search index (map)\n%% Result is a list of {module, props} pairs.\n%% This will update a table \"pivot_\".\n%% You must ensure that the table exists.\n%% Type: map\n-record(custom_pivot, {\n id :: m_rsc:resource()\n}).\n\n% 'pivot_rsc_data' - foldl over the resource props to extend\/remove data to be pivoted\n\n%% @doc Pivot just before a m_rsc_update update. Used to pivot fields before the pivot itself.\n%% Type: foldr\n-record(pivot_update, {\n id :: m_rsc:resource(),\n raw_props :: list()\n}).\n\n%% @doc Foldr to change or add pivot fields for the main pivot table.\n%% The rsc contains all rsc properties for this resource, including pivot properties.\n-record(pivot_fields, {\n id :: m_rsc:resource(),\n rsc :: list()\n}).\n\n%% @doc Signal that a resource pivot has been done.\n%% Type: notify\n-record(rsc_pivot_done, {\n id :: m_rsc:resource(),\n is_a = [] :: list()\n}).\n\n\n%% @doc Sanitize an HTML element.\n%% Type: foldl\n-record(sanitize_element, {\n element :: {binary(), list(), list()},\n stack :: list()\n}).\n\n%% @doc Sanitize an embed url. The hostpart is of the format: <<\"youtube.com\/v...\">>.\n%% Return: ``undefined``, ``false`` or a binary with a acceptable hostpath\n-record(sanitize_embed_url, {\n hostpath :: binary()\n}).\n\n\n%% @doc Check if a user is the owner of a resource.\n%% ``id`` is the resource id.\n%% Type: first\n%% Return: ``true``, ``false`` or ``undefined`` to let the next observer decide\n-record(acl_is_owner, {\n id :: integer(),\n creator_id :: integer(),\n user_id :: integer()\n}).\n\n%% @doc Check if a user is authorized to perform an operation on a an object\n%% (some resource or module). Observe this notification to do complex or more\n%% fine-grained authorization checks than you can do through the ACL rules admin\n%% interface. Defaults to ``false``.\n%% Type: first\n%% Return: ``true`` to allow the operation, ``false`` to deny it or ``undefined`` to let the next observer decide\n-record(acl_is_allowed, {\n action :: view | update | delete | insert | use | atom(),\n object :: term()\n}).\n\n%% @doc Check if a user is authorizded to perform an action on a property.\n%% Defaults to ``true``.\n%% Type: first\n%% Return: ``true`` to grant access, ``false`` to deny it, ``undefined`` to let the next observer decide\n-record(acl_is_allowed_prop, {\n action :: view | update | delete | insert | atom(),\n object :: term(),\n prop :: atom()\n}).\n\n%% @doc Set the context to a typical authenticated uses. Used by m_acl.erl\n%% Type: first\n%% Return: authenticated ``#context{}`` or ``undefined``\n-record(acl_context_authenticated, {\n\n}).\n\n%% @doc Initialize context with the access policy for the user.\n%% Type: first\n%% Return: updated ``#context`` or ``undefined``\n-record(acl_logon, {id}).\n\n%% @doc Clear the associated access policy for the context.\n%% Type: first\n%% Return: updated ``#context{}`` or ``undefined``\n-record(acl_logoff, {}).\n\n%% @doc Confirm a user id.\n%% Type: foldl\n%% Return: ``context{}``\n-record(auth_confirm, {}).\n\n%% @doc A user id has been confirmed.\n%% Type: notify\n-record(auth_confirm_done, {}).\n\n%% @doc User logs on. Add user-related properties to the session.\n%% Type: foldl\n%% Return: ``context{}``\n-record(auth_logon, {}).\n\n%% @doc User has logged on.\n%% Type: notify\n-record(auth_logon_done, {}).\n\n%% @doc User is about to log off. Remove authentication from the current session.\n%% Type: foldl\n%% Return: ``context{}``\n-record(auth_logoff, {}).\n\n%% @doc User has logged off.\n%% Type: notify\n-record(auth_logoff_done, {}).\n\n%% @doc Check if automatic logon is enabled for this session. Sent for new\n%% sessions from ``z_auth:logon_from_session\/1``. Please note this notification\n%% is sent for every single request.\n%% Type: first\n%% Return: ``{ok, UserId}`` when a user should be logged on.\n-record(auth_autologon, {}).\n\n%% @doc Authentication against some (external or internal) service was validated\n-record(auth_validated, {\n service :: atom(),\n service_uid :: binary(),\n service_props = [] :: list(),\n props = [] :: list({atom(), any()}),\n is_connect = false :: boolean()\n}).\n\n%% @doc Called after parsing the query arguments\n%% Type: foldl\n%% Return: ``#context{}``\n-record(request_context, {}).\n\n%% @doc Initialize a context from the current session.\n%% Called for every request that has a session.\n%% Type: foldl\n%% Return: ``#context{}``\n-record(session_context, {}).\n\n%% @doc A new session has been intialized: session_pid is in the context.\n%% Called for every request that has a session.\n%% Type: notify\n%% Return: ``#context{}``\n-record(session_init, {}).\n\n%% @doc Foldl over the context containing a new session.\n%% Called for every request that has a session.\n%% Type: foldl\n%% Return: ``#context{}``\n-record(session_init_fold, {}).\n\n%% @doc Check if a user is enabled. Enabled users are allowed to log in.\n%% Type: first\n%% Return ``true``, ``false`` or ``undefined``. If ``undefined`` is returned,\n%% the user is considered enabled if the user resource is published.\n-record(user_is_enabled, {id}).\n\n%% @doc Set #context fields depending on the user and\/or the preferences of the user.\n%% Type: foldl\n-record(user_context, {id}).\n\n%% @doc Request API logon\n-record(service_authorize, {service_module}).\n\n%% @doc Fetch the url of a resource's html representation\n%% Type: first\n%% Return: ``{ok, Url}`` or ``undefined``\n-record(page_url, {id, is_a}).\n\n%% @doc Handle custom named search queries in your function.\n%% Type: first\n%% Return: ``#search_sql{}``, ``#search_result{}`` or ``undefined``\n-record(search_query, {\n search :: {\n SearchName :: atom(),\n SearchProps :: list()\n },\n offsetlimit :: {\n Offset :: pos_integer(),\n Limit :: pos_integer()\n }\n}).\n\n%% @doc An edge has been inserted\n%% Type: notify\n%% Return: return value is ignored\n-record(edge_insert, {\n subject_id :: m_rsc:resource(),\n predicate :: atom(),\n object_id :: m_rsc:resource(),\n edge_id :: pos_integer()\n}).\n\n%% @doc An edge has been deleted\n%% Type: notify\n%% Return: return value is ignored\n-record(edge_delete, {\n subject_id :: m_rsc:resource(),\n predicate :: atom(),\n object_id :: m_rsc:resource(),\n edge_id :: pos_integer()\n}).\n\n%% @doc An edge has been updated\n%% Type: notify\n%% Return: return value is ignored\n-record(edge_update, {\n subject_id :: m_rsc:resource(),\n predicate :: atom(),\n object_id :: m_rsc:resource(),\n edge_id :: pos_integer()\n}).\n\n%% @doc Site configuration parameter was changed\n%% Type: notify\n%% Return: return value is ignored\n-record(m_config_update, {\n module :: atom(),\n key :: term(),\n value :: term()\n}).\n\n%% @doc Site configuration parameter was changed\n%% Type: notify\n%% Return: return value is ignored\n-record(m_config_update_prop, {module, key, prop, value}).\n\n%% @doc Notification for fetching #media_import_props{} from different modules.\n%% This is used by z_media_import.erl for fetching properties and medium information\n%% about resources.\n-record(media_import, {\n url :: binary(),\n host_rev :: list(binary()),\n mime :: binary,\n metadata :: tuple()\n}).\n\n-record(media_import_props, {\n prio = 5 :: pos_integer(), % 1 for perfect match (ie. host specific importer)\n category :: atom(),\n module :: atom(),\n description :: binary() | {trans, list()},\n rsc_props :: list(),\n medium_props :: list(),\n medium_url :: binary(),\n preview_url :: binary()\n}).\n\n%% @doc Notification to translate or map a file after upload, before insertion into the database\n%% Used in mod_video to queue movies for conversion to mp4.\n%% You can set the post_insert_fun to something like fun(Id, Medium, Context) to receive the\n%% medium record as it is inserted.\n%% Type: first\n%% Return: modified ``#media_upload_preprocess{}``\n-record(media_upload_preprocess, {\n id :: integer() | 'insert_rsc',\n mime :: binary(),\n file :: file:filename(),\n original_filename :: file:filename(),\n medium :: list(),\n post_insert_fun :: function()\n}).\n\n%% @doc Notification that a medium file has been uploaded.\n%% This is the moment to change properties, modify the file etc.\n%% Type: foldl\n%% Return: modified ``#media_upload_props{}``\n-record(media_upload_props, {\n id :: integer() | 'insert_rsc',\n mime :: binary(),\n archive_file,\n options\n}).\n\n%% @doc Notification that a medium file has been uploaded.\n%% This is the moment to change resource properties, modify the file etc.\n%% Type: foldl\n%% Return: modified ``#media_upload_rsc_props{}``\n-record(media_upload_rsc_props, {\n id :: integer() | 'insert_rsc',\n mime :: binary(),\n archive_file,\n options :: list(),\n medium :: list()\n}).\n\n%% @doc Notification that a medium file has been changed (notify)\n%% The id is the resource id, medium contains the medium's property list.\n%% Type: notify\n%% Return: return value is ignored\n-record(media_replace_file, {id, medium}).\n\n%% @doc Media update done notification.\n%% action is 'insert', 'update' or 'delete'\n-record(media_update_done, {action, id, pre_is_a, post_is_a, pre_props, post_props}).\n\n\n%% @doc Send a notification that the resource 'id' is added to the query query_id.\n%% Type: notify\n-record(rsc_query_item, {\n query_id,\n match_id\n}).\n\n\n%% @doc Add extra javascript with the {% script %} tag. (map)\n%% Used to let modules inject extra javascript depending on the arguments of the {% script %} tag.\n%% Must return an iolist()\n-record(scomp_script_render, {\n is_nostartup = false :: boolean(),\n args = [] :: list()\n}).\n\n\n%% @doc Render the javascript for a custom action event type.\n%% The custom event type must be a tuple, for example:\n%% {% wire type={live id=myid} action={...} %}<\/code>\n%% Must return {ok, Javascript, Context}\n-record(action_event_type, {\n event :: tuple(),\n trigger_id :: string(),\n trigger :: string(),\n postback_js :: iolist(),\n postback_pickled :: string()|binary(),\n action_js :: iolist()\n}).\n\n%% @doc Find an import definition for a CSV file by checking the filename of the to be imported file.\n%% Type: first\n%% Return: ``#import_csv_definition{}`` or ``undefined`` (in which case the column headers are used as property names)\n-record(import_csv_definition, {basename, filename}).\n\n\n%% @doc Handle an uploaded file which is part of a multiple file upload from a user-agent.\n%% The upload is a #upload record or a filename on the server.\n%% Type: first\n%% Return: ``#context{}`` with the result or ``undefined``\n-record(multiupload, {\n upload :: term() | string(),\n query_args = [] :: list()\n}).\n\n%% @doc Handle a new file received in the 'files\/dropbox' folder of a site.\n%% Unhandled files are deleted after a hour.\n%% Type: first\n-record(dropbox_file, {filename}).\n\n%% @doc Try to identify a file, returning a list of file properties.\n%% Type: first\n-record(media_identify_file, {filename, original_filename, extension}).\n\n%% @doc Try to find a filename extension for a mime type (example: \".jpg\")\n%% Type: first\n-record(media_identify_extension, {\n mime :: binary(),\n preferred :: undefined | binary()\n}).\n\n%% @doc Request to generate a HTML media viewer for a resource\n%% Type: first\n%% Return: ``{ok, Html}`` or ``undefined``\n-record(media_viewer, {\n id,\n props :: list(),\n filename,\n options = [] :: list()\n}).\n\n%% @doc See if there is a 'still' image preview of a media item. (eg posterframe of a movie)\n%% Return:: ``{ok, ResourceId}`` or ``undefined``\n-record(media_stillimage, {id, props = []}).\n\n\n%% @doc Fetch lisy of handlers.\n%% Type: foldr\n-record(survey_get_handlers, {}).\n\n%% @doc A survey has been filled in and submitted.\n%% Type: first\n-record(survey_submit, {id, handler, answers, missing, answers_raw}).\n\n%% @doc Check if the current user is allowed to download a survey.\n%% Type: first\n-record(survey_is_allowed_results_download, {id}).\n\n%% @doc Check if a question is a submitting question.\n%% Type: first\n-record(survey_is_submit, {block = []}).\n\n%% @doc Put a value into the typed key\/value store\n-record(tkvstore_put, {type, key, value}).\n\n%% @doc Get a value from the typed key\/value store\n-record(tkvstore_get, {type, key}).\n\n%% @doc Delete a value from the typed key\/value store\n-record(tkvstore_delete, {type, key}).\n\n%% @doc Subscribe a function to an MQTT topic.\n%% The function will be called from a temporary process, and must be of the form:\n%% m:f(#emqtt_msg{}, A, Context)\n-record(mqtt_subscribe, {topic, qos = 0 :: 0 | 1 | 2, mfa}).\n\n%% @doc Unsubscribe a function from an MQTT topic.\n%% The MFA _must_ match the one supplied with #mqtt_subscribe{}\n-record(mqtt_unsubscribe, {topic, mfa}).\n\n%% @doc MQTT acl check, called via the normal acl notifications.\n%% Actions for these checks: subscribe, publish\n-record(acl_mqtt, {\n type :: 'wildcard' | 'direct',\n topic :: binary(),\n words :: list(binary() | integer()),\n site :: binary(),\n page_id :: 'undefined' | binary()\n}).\n\n%% @doc Broadcast notification.\n-record(broadcast, {title = [], message = [], is_html = false, stay = true, type = \"error\"}).\n\n%% @doc Internal message of mod_development. Start a stream with debug information to the user agent.\n%% 'target' is the id of the HTML element where the information is inserted.\n%% 'what' is the kind of debug information being streamed to the user-agent.\n-record(debug_stream, {target, what = template}).\n\n%% @doc Push some information to the debug page in the user-agent.\n%% Will be displayed with io_lib:format(\"~p: ~p~n\", [What, Arg]), be careful with escaping information!\n-record(debug, {what, arg = []}).\n\n%% @doc An external feed delivered a resource. First handler can import it.\n-record(import_resource, {\n source :: atom() | binary(),\n source_id :: integer() | binary(),\n source_url :: binary(),\n source_user_id :: binary() | integer(),\n user_id :: integer(),\n name :: binary(),\n props :: list(),\n urls :: list(),\n media_urls :: list(),\n data :: any()\n}).\n\n%% @doc mod_export - Check if the resource or dispatch is visible for export.\n%% Type: first\n%% Return: ``true`` or ``false``\n-record(export_resource_visible, {\n dispatch :: atom(),\n id :: integer()\n}).\n\n%% @doc mod_export -\n%% Return: ``{ok, \"text\/csv\"})`` for the dispatch rule\/id export.\n-record(export_resource_content_type, {\n dispatch :: atom(),\n id :: integer()\n}).\n\n%% @doc mod_export - return the {ok, Filename} for the content disposition.\n%% Type: first\n%% Return: ``{ok, Filename}}`` or ``undefined``\n-record(export_resource_filename, {\n dispatch :: atom(),\n id :: integer(),\n content_type :: string()\n}).\n\n%% @doc mod_export - Fetch the header for the export.\n%% Type: first\n%% Return: ``{ok, list()|binary()}``, ``{ok, list()|binary(), ContinuationState}`` or ``{error, Reason}``\n-record(export_resource_header, {\n dispatch :: atom(),\n id :: integer(),\n content_type :: string()\n}).\n\n%% @doc mod_export - fetch a row for the export, can return a list of rows, a binary, and optionally a continuation state.\n%% Where Values is [ term() ], i.e. a list of opaque values, to be formatted with #export_resource_format.\n%% Return the empty list of values to signify the end of the data stream.\n%% Type: first\n%% Return: ``{ok, Values|binary()}``, ``{ok, Values|binary(), ContinuationState}`` or ``{error, Reason}``\n-record(export_resource_data, {\n dispatch :: atom(),\n id :: integer(),\n content_type :: string(),\n state :: term()\n}).\n\n%% @doc mod_export - Encode a single data element.\n%% Type: first\n%% Return: ``{ok, binary()}``, ``{ok, binary(), ContinuationState}`` or ``{error, Reason}``\n-record(export_resource_encode, {\n dispatch :: atom(),\n id :: integer(),\n content_type :: string(),\n data :: term(),\n state :: term()\n}).\n\n%% @doc mod_export - Fetch the footer for the export. Should cleanup the continuation state, if needed.\n%% Type: first\n%% Return: ``{ok, binary()}`` or ``{error, Reason}``\n-record(export_resource_footer, {\n dispatch :: atom(),\n id :: integer(),\n content_type :: string(),\n state :: term()\n}).\n\n%% @doc Notify modules of a data model entry defined in manage_schema\n%% Type: first\n%% Return: ``ok`` or ``undefined``\n-record(manage_data, {\n module :: atom(),\n props :: list()\n}).\n\n% Simple mod_development notifications:\n% development_reload - Reload all template, modules etc\n% development_make - Perform a 'make' on Zotonic, reload all new beam files\n","avg_line_length":31.6871741397,"max_line_length":126,"alphanum_fraction":0.6723706726} +{"size":1553,"ext":"erl","lang":"Erlang","max_stars_count":21.0,"content":"%%\n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2009-2016. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%%%-------------------------------------------------------------------\n%%% File : sudoku.erl\n%%% Author : Dan Gudmundsson \n%%% Description : Sudoku\n%%%\n%%% Created : 13 Mar 2007 by Dan Gudmundsson \n%%%-------------------------------------------------------------------\n\n-module(sudoku).\n\n-export([go\/0]).\n\n-compile(export_all).\n\n-include(\"sudoku.hrl\").\n\nstart() -> \n spawn_link(fun() -> init(halt) end).\ngo() -> \n spawn_link(fun() -> init(keep) end).\n\ninit(Halt) ->\n ?TC(sudoku_gui:new(self())),\n receive {gfx, GFX} -> ok end,\n case sudoku_game:init(GFX) of\n\tHalt -> erlang:halt();\n\tStop -> exit(Stop)\n end.\n\ntc(Fun,Mod,Line) ->\n case timer:tc(erlang, apply, [Fun,[]]) of\n {_,{'EXIT',Reason}} -> exit(Reason);\n {T,R} ->\n io:format(\"~p:~p: Time: ~p\\n\", [Mod, Line, T]),\n R\n end.\n","avg_line_length":28.2363636364,"max_line_length":75,"alphanum_fraction":0.5801674179} +{"size":124,"ext":"erl","lang":"Erlang","max_stars_count":487.0,"content":"bin_test(Var1) ->\n <>,\n <<(Var1 + Var1):4\/integer>>,\n <<(Var1 * Var1):4\/integer-little>>.","avg_line_length":31.0,"max_line_length":37,"alphanum_fraction":0.6048387097} +{"size":33645,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%\n%% wings_edge.erl --\n%%\n%% This module contains most edge command and edge utility functions.\n%%\n%% Copyright (c) 2001-2011 Bjorn Gustavsson.\n%%\n%% See the file \"license.terms\" for information on usage and redistribution\n%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.\n%%\n%% $Id$\n%%\n\n-module(wings_edge).\n\n%% Utilities.\n-export([from_vs\/2,to_vertices\/2,from_faces\/2,\n\t select_region\/1,\n reachable_faces\/3,\n\t select_edge_ring\/1,select_edge_ring_incr\/1,select_edge_ring_decr\/1,\n\t cut\/3,fast_cut\/3,screaming_cut\/3,\n\t dissolve_edges\/2,dissolve_edge\/2,\n dissolve_isolated_vs\/2,\n\t hardness\/3,\n\t patch_edge\/4,patch_edge\/5,\n\t select_nth_ring\/2,\n\t select_nth_loop\/2,\n\t length\/2\n\t]).\n\n-export_type([edge_num\/0]).\n\n-include(\"wings.hrl\").\n-import(lists, [foldl\/3,sort\/1]).\n\n-type edge_num() :: non_neg_integer().\n\nlength(Ei, #we{es=Etab,vp=VPos}) ->\n #edge{vs=VS,ve=VE} = array:get(Ei,Etab),\n Pt1 = array:get(VS,VPos),\n Pt2 = array:get(VE,VPos),\n e3d_vec:dist(Pt1,Pt2).\n\nfrom_vs(Vs, We) when is_list(Vs) ->\n from_vs(Vs, We, []);\nfrom_vs(Vs, We) ->\n gb_sets:from_list(from_vs(gb_sets:to_list(Vs), We, [])).\n\nfrom_vs([V|Vs], We, Acc0) ->\n Acc = wings_vertex:fold(fun(E, _, _, A) -> [E|A] end, Acc0, V, We),\n from_vs(Vs, We, Acc);\nfrom_vs([], _, Acc) -> Acc.\n\n%% to_vertices(EdgeGbSet, We) -> VertexGbSet\n%% Convert a set of edges to a set of vertices.\n\nto_vertices(Edges, #we{es=Etab}) when is_list(Edges) ->\n to_vertices(Edges, Etab, []);\nto_vertices(Edges, #we{es=Etab}) ->\n to_vertices(gb_sets:to_list(Edges), Etab, []).\n\nto_vertices([E|Es], Etab, Acc) ->\n #edge{vs=Va,ve=Vb} = array:get(E, Etab),\n to_vertices(Es, Etab, [Va,Vb|Acc]);\nto_vertices([], _Etab, Acc) -> ordsets:from_list(Acc).\n\n%% from_faces(FaceSet, We) -> EdgeSet\n%% Convert faces to edges.\nfrom_faces(Faces, We) ->\n gb_sets:from_ordset(wings_face:to_edges(Faces, We)).\n\n%% cut(Edge, Parts, We0) -> {We,NewVertex,NewEdge}\n%% Cut an edge into Parts parts.\ncut(Edge, 2, We) ->\n fast_cut(Edge, default, We);\ncut(Edge, N, #we{es=Etab}=We) ->\n #edge{vs=Va,ve=Vb} = array:get(Edge, Etab),\n PosA = wings_vertex:pos(Va, We),\n PosB = wings_vertex:pos(Vb, We),\n Vec = e3d_vec:mul(e3d_vec:sub(PosB, PosA), 1\/N),\n cut_1(N, Edge, PosA, Vec, We).\n\n%% fast_cut(Edge, Position, We0) -> {We,NewElement}\n%% NewElement = ID for the new vertex and the new Edge\n%% Cut an edge in two parts. Position can be given as\n%% the atom `default', in which case the position will\n%% be set to the midpoint of the edge.\n\nfast_cut(Edge, Pos0, We0) ->\n {NewEdge=NewV,We1} = wings_we:new_ids(1, We0),\n #we{es=Etab0,vc=Vct0,vp=Vtab0,he=Htab0} = We1,\n Template = array:get(Edge, Etab0),\n #edge{vs=Vstart,ve=Vend,ltpr=EdgeA,rtsu=EdgeB} = Template,\n VendPos = array:get(Vend, Vtab0),\n Vct1 = array:set(Vend, NewEdge, Vct0),\n VstartPos = wings_vertex:pos(Vstart, Vtab0),\n if\n\tPos0 =:= default ->\n\t NewVPos0 = e3d_vec:average(VstartPos, VendPos);\n\ttrue ->\n\t NewVPos0 = Pos0\n end,\n NewVPos = wings_util:share(NewVPos0),\n Vct = array:set(NewV, NewEdge, Vct1),\n Vtab = array:set(NewV, NewVPos, Vtab0),\n\n NewEdgeRec = Template#edge{vs=NewV,ltsu=Edge,rtpr=Edge},\n Etab1 = array:set(NewEdge, NewEdgeRec, Etab0),\n Etab2 = patch_edge(EdgeA, NewEdge, Edge, Etab1),\n Etab3 = patch_edge(EdgeB, NewEdge, Edge, Etab2),\n EdgeRec = Template#edge{ve=NewV,rtsu=NewEdge,ltpr=NewEdge},\n Etab = array:set(Edge, EdgeRec, Etab3),\n Htab = case gb_sets:is_member(Edge, Htab0) of\n\t false -> Htab0;\n\t true -> gb_sets:insert(NewEdge, Htab0)\n\t end,\n We2 = We1#we{es=Etab,vc=Vct,vp=Vtab,he=Htab},\n\n %% Now interpolate and set vertex attributes.\n Weight = if\n\t\t Pos0 =:= default -> 0.5;\n\t\t VstartPos =:= VendPos -> 0.5;\n\t\t Pos0 =:= VstartPos -> 0.0;\n\t\t Pos0 =:= VendPos -> 1.0;\n\t\t true ->\n\t\t ADist = e3d_vec:dist(Pos0, VstartPos),\n\t\t BDist = e3d_vec:dist(Pos0, VendPos),\n\t\t ADist\/(ADist+BDist)\n\t end,\n AttrMidLeft = wings_va:edge_attrs(Edge, left, Weight, We1),\n AttrMidRight = wings_va:edge_attrs(Edge, right, Weight, We1),\n AttrEndLeft = wings_va:edge_attrs(Edge, right, We1),\n\n We3 = wings_va:set_edge_attrs(Edge, right, AttrMidRight, We2),\n We = wings_va:set_both_edge_attrs(NewEdge, AttrMidLeft, AttrEndLeft, We3),\n\n {We,NewV}.\n\n%% screaming_cut(Edge, Position, We0) -> {We,NewVertex,NewEdge}\n%% Cut an edge in two parts screamlingly fast. Does not handle\n%% vertex colors or UV coordinates.\n\nscreaming_cut(Edge, NewVPos, We0) ->\n {NewEdge=NewV,We} = wings_we:new_ids(1, We0),\n #we{es=Etab0,vc=Vct0,vp=Vtab0,he=Htab0} = We,\n Template = array:get(Edge, Etab0),\n #edge{ve=Vend,ltpr=EdgeA,rtsu=EdgeB} = Template,\n Vct1 = array:set(Vend, NewEdge, Vct0),\n Vct = array:set(NewV, NewEdge, Vct1),\n Vtab = array:set(NewV, NewVPos, Vtab0),\n\n NewEdgeRec = Template#edge{vs=NewV,ltsu=Edge,rtpr=Edge},\n Etab1 = array:set(NewEdge, NewEdgeRec, Etab0),\n Etab2 = patch_edge(EdgeA, NewEdge, Edge, Etab1),\n Etab3 = patch_edge(EdgeB, NewEdge, Edge, Etab2),\n EdgeRec = Template#edge{ve=NewV,rtsu=NewEdge,ltpr=NewEdge},\n Etab = array:set(Edge, EdgeRec, Etab3),\n\n Htab = case gb_sets:is_member(Edge, Htab0) of\n\t false -> Htab0;\n\t true -> gb_sets:insert(NewEdge, Htab0)\n\t end,\n {We#we{es=Etab,vc=Vct,vp=Vtab,he=Htab},NewV}.\n\n%%%\n%%% Dissolve.\n%%%\n\ndissolve_edge(Edge, We) ->\n dissolve_edges([Edge], We).\n\ndissolve_edges(Edges, We) when is_list(Edges) ->\n Faces = gb_sets:to_list(wings_face:from_edges(Edges, We)),\n dissolve_edges(Edges, Faces, We);\ndissolve_edges(Edges, We) ->\n dissolve_edges(gb_sets:to_list(Edges), We).\n\n\n%% dissolve_isolated_vs([Vertex], We) -> We'\n%% Remove all isolated vertices (\"winged vertices\", or vertices\n%% having exactly two edges).\ndissolve_isolated_vs([_|_]=Vs, We) ->\n dissolve_isolated_vs_1(Vs, We, []);\ndissolve_isolated_vs([], We) -> We.\n\n%%%\n%%% Setting hard\/soft edges.\n%%%\n\nhardness(Edge, soft, Htab) -> gb_sets:delete_any(Edge, Htab);\nhardness(Edge, hard, Htab) -> gb_sets:add(Edge, Htab).\n\n%%%\n%%% \"Select faces on one side of an edge loop.\"\n%%%\n%%% This description is pretty ambigous. If there are\n%%% multiple edge loops, it is not clear what to select.\n%%%\n%%% What we do for each object is to collect all faces\n%%% sandwhiched between one or more edge loops. We then\n%%% partition all those face collection into one partition\n%%% for each sub-object (if there are any). For each\n%%% sub-object, we arbitrarily pick the face collection\n%%% having the smallest number of faces.\n%%%\n\nselect_region(#st{selmode=edge}=St) ->\n wings_sel:update_sel(fun select_region\/2, face, St);\nselect_region(St) -> St.\n\n\n%%\n%% Collect all faces reachable from Face, without crossing\n%% any of the edges in Edges.\n%%\n\n-spec reachable_faces(Face, Edges, We) -> Faces when\n Face :: wings_face:face_num(),\n Edges :: wings_sel:edge_set(),\n We :: #we{},\n Faces :: wings_sel:face_set().\n\nreachable_faces(Face, Edges, We) ->\n collect_faces(gb_sets:singleton(Face), We, Edges, gb_sets:empty()).\n\n%%%\n%%% Edge Ring. (Based on Anders Conradi's plug-in.)\n%%%\n\nselect_edge_ring(#st{selmode=edge}=St) ->\n wings_sel:update_sel(fun build_selection\/2, St);\nselect_edge_ring(St) -> St.\n\nselect_edge_ring_incr(#st{selmode=edge}=St) ->\n wings_sel:update_sel(fun incr_ring_selection\/2, St);\nselect_edge_ring_incr(St) -> St.\n\nselect_edge_ring_decr(#st{selmode=edge}=St) ->\n wings_sel:update_sel(fun decr_ring_selection\/2, St);\nselect_edge_ring_decr(St) -> St.\n\n\n%%%\n%%% Local functions\n%%%\n\ncut_1(2, Edge, _, _, We) ->\n fast_cut(Edge, default, We);\ncut_1(N, Edge, Pos0, Vec, We0) ->\n Pos = e3d_vec:add(Pos0, Vec),\n {We,NewE} = fast_cut(Edge, Pos, We0),\n cut_1(N-1, NewE, Pos, Vec, We).\n\n%%% Dissolving edges.\n\ndissolve_edges(Edges0, Faces, We0) when is_list(Edges0) ->\n #we{es=Etab} = We1 = foldl(fun internal_dissolve_edge\/2, We0, Edges0),\n case [E || E <- Edges0, array:get(E, Etab) =\/= undefined] of\n Edges0 ->\n %% No edge was deleted in the last pass. We are done.\n We2 = wings_we:rebuild(We0),\n #we{fs=Ftab}=We = wings_we:validate_mirror(We2),\n lists:foreach(fun(Face) ->\n case gb_trees:is_defined(Face, Ftab) of\n true ->\n case wings_we:is_face_consistent(Face, We) of\n true ->\n ok;\n false ->\n wings_u:error_msg(?__(1,\"Dissolving would cause a badly formed face.\"))\n end;\n false ->\n ok\n end\n end, Faces),\n We;\n Edges ->\n dissolve_edges(Edges, Faces, We1)\n end.\n\ninternal_dissolve_edge(Edge, #we{es=Etab}=We0) ->\n case array:get(Edge, Etab) of\n\tundefined -> We0;\n\t#edge{ltpr=Same,ltsu=Same,rtpr=Same,rtsu=Same} ->\n\t EmptyGbTree = gb_trees:empty(),\n\t Empty = array:new(),\n\t We0#we{vc=Empty,vp=Empty,es=Empty,fs=EmptyGbTree,he=gb_sets:empty()};\n\t#edge{rtpr=Back,ltsu=Back}=Rec ->\n\t merge_edges(backward, Edge, Rec, We0);\n\t#edge{rtsu=Forward,ltpr=Forward}=Rec ->\n\t merge_edges(forward, Edge, Rec, We0);\n\tRec ->\n\t try dissolve_edge_1(Edge, Rec, We0) of\n\t\tWe -> We\n\t catch\n\t\tthrow:hole -> We0\n\t end\n end.\n\n%% dissolve_edge_1(Edge, EdgeRecord, We) -> We\n%% Remove an edge and a face. If one of the faces is degenerated\n%% (only consists of two edges), remove that one. If no face is\n%% degenerated, prefer to keep an invisible face (if an edge\n%% bordering a hole is dissolved, we except except the hole to\n%% expand). Otherwise, it does not matter which face we keep.\n%%\ndissolve_edge_1(Edge, #edge{lf=Remove,rf=Keep,ltpr=Same,ltsu=Same}=Rec, We) ->\n dissolve_edge_2(Edge, Remove, Keep, Rec, We);\ndissolve_edge_1(Edge, #edge{lf=Keep,rf=Remove,rtpr=Same,rtsu=Same}=Rec, We) ->\n dissolve_edge_2(Edge, Remove, Keep, Rec, We);\ndissolve_edge_1(Edge, #edge{lf=Lf,rf=Rf}=Rec, We) ->\n if\n\tLf < 0 ->\n\t %% Keep left face.\n\t if\n\t\tRf < 0 ->\n\t\t %% The right face is also hidden. (Probably unusual\n\t\t %% in practice.) It might also be a hole.\n\t\t Holes = ordsets:del_element(Rf, We#we.holes),\n\t\t dissolve_edge_2(Edge, Rf, Lf, Rec, We#we{holes=Holes});\n\t\ttrue ->\n\t\t dissolve_edge_2(Edge, Rf, Lf, Rec, We)\n\t end;\n\tRf < 0 ->\n\t %% Keep the right face. Remove the (visible) left face.\n\t dissolve_edge_2(Edge, Lf, Rf, Rec, We);\n\ttrue ->\n\t %% It does not matter which one we keep.\n\t dissolve_edge_2(Edge, Rf, Lf, Rec, We)\n end.\n\ndissolve_edge_2(Edge, FaceRemove, FaceKeep,\n\t\t#edge{vs=Va,ve=Vb,ltpr=LP,ltsu=LS,rtpr=RP,rtsu=RS},\n\t\t#we{fs=Ftab0,es=Etab0,vc=Vct0,he=Htab0}=We0) ->\n %% First change the face for all edges surrounding the face we will remove.\n Etab1 = wings_face:fold(\n\t fun (_, E, _, IntEtab) when E =:= Edge -> IntEtab;\n\t\t (_, E, R, IntEtab) ->\n\t\t case R of\n\t\t\t #edge{lf=FaceRemove,rf=FaceKeep} ->\n\t\t\t throw(hole);\n\t\t\t #edge{rf=FaceRemove,lf=FaceKeep} ->\n\t\t\t throw(hole);\n\t\t\t #edge{lf=FaceRemove} ->\n\t\t\t array:set(E, R#edge{lf=FaceKeep}, IntEtab);\n\t\t\t #edge{rf=FaceRemove} ->\n\t\t\t array:set(E, R#edge{rf=FaceKeep}, IntEtab)\n\t\t end\n\t end, Etab0, FaceRemove, We0),\n\n %% Patch all predecessors and successor of the edge we will remove.\n Etab2 = patch_edge(LP, RS, Edge, Etab1),\n Etab3 = patch_edge(LS, RP, Edge, Etab2),\n Etab4 = patch_edge(RP, LS, Edge, Etab3),\n Etab5 = patch_edge(RS, LP, Edge, Etab4),\n\n %% Remove the edge.\n Etab = array:reset(Edge, Etab5),\n Htab = hardness(Edge, soft, Htab0),\n\n %% Update the incident vertex table for both vertices\n %% to make sure they point to the correct existing edges.\n %%\n %% We used to simply set the 'vc' field to 'undefined' to\n %% force a complete rebuild of the vertex table, but that\n %% could cause Extrude (for regions) to become slow for certain\n %% selection shapes, as the Extrude command internally does a\n %% collapse of one edge in a triangle face, which in turns causes\n %% a dissolve of one of the remaining edges.\n Vct = case Vct0 of\n\t undefined ->\n\t\t Vct0;\n\t _ ->\n\t\t %% For the vertices Va and Vb, pick one of the still existing\n\t\t %% edges emanating from the vertex.\n\t\t %%\n\t\t %% The edges LS ('ltsu') and RP ('rtpr') emanate from Va ('vs').\n\t\t %% The edges LP ('ltpr') and RS ('rtsu') emanate from Vb ('ve').\n\t\t Vct1 = array:set(Va, LS, Vct0),\n\t\t array:set(Vb, RS, Vct1)\n\t end,\n\n %% Remove the face. Update the incident face to make sure\n %% the face points to an existing edge.\n Ftab1 = gb_trees:delete(FaceRemove, Ftab0),\n We1 = wings_facemat:delete_face(FaceRemove, We0),\n AnEdge = LP,\n Ftab = gb_trees:update(FaceKeep, AnEdge, Ftab1),\n\n %% Store all updated tables.\n We = We1#we{es=Etab,fs=Ftab,vc=Vct,he=Htab},\n\n %% If the kept face (FaceKeep) has become a two-edge face,\n %% we must get rid of that face by dissolving one of its edges.\n case array:get(AnEdge, Etab) of\n\t#edge{lf=FaceKeep,ltpr=Same,ltsu=Same} ->\n\t internal_dissolve_edge(AnEdge, We);\n\t#edge{rf=FaceKeep,rtpr=Same,rtsu=Same} ->\n\t internal_dissolve_edge(AnEdge, We);\n\t_Other -> We\n end.\n\n%% Since the dissolve operation will not keep the incident\n%% edge table for vertices updated, we'll need to lookup\n%% all incident edges now before we have started to dissolve.\ndissolve_isolated_vs_1([V|Vs], #we{vc=Vct}=We, Acc) ->\n case array:get(V, Vct) of\n\tundefined ->\n\t %% A previous pass has already removed this vertex.\n\t dissolve_isolated_vs_1(Vs, We, Acc);\n\tEdge ->\n\t dissolve_isolated_vs_1(Vs, We, [{V,Edge}|Acc])\n end;\ndissolve_isolated_vs_1([], We, Vc) ->\n dissolve_isolated_vs_2(Vc, We, []).\n\n%% Now do all dissolving.\ndissolve_isolated_vs_2([{V,Edge}|T], We0, Acc) ->\n case dissolve_vertex(V, Edge, We0) of\n\tdone -> dissolve_isolated_vs_2(T, We0, Acc);\n\tWe -> dissolve_isolated_vs_2(T, We, [V|Acc])\n end;\ndissolve_isolated_vs_2([], We, []) ->\n %% Nothing was done in the last pass. We don't need to do a vertex GC.\n We;\ndissolve_isolated_vs_2([], We0, Vs) ->\n We = wings_we:rebuild(We0#we{vc=undefined}),\n\n %% Now do another pass over the vertices still in our list.\n %% Reason:\n %%\n %% 1. An incident edge may have become wrong by a previous\n %% dissolve (on another vertex). Do another try now that\n %% the incident table has been rebuilt.\n %%\n %% 2. A vertex may have be connected to two faces that\n %% have no edge in common. In that case, all edges\n %% are not reachable from the incident edge.\n dissolve_isolated_vs(Vs, We).\n\n%% dissolve(V, Edge, We0) -> We|done\n%% Dissolve the given vertex. The 'done' return value means\n%% that the vertex is already non-existing (or is not isolated).\n%% If a We is returned, the caller must call this function again\n%% (after rebuilding the incident table) since there might be more\n%% work to do.\ndissolve_vertex(V, Edge, #we{es=Etab}=We0) ->\n case array:get(Edge, Etab) of\n\t#edge{vs=V,ltsu=AnEdge,rtpr=AnEdge}=Rec ->\n\t merge_edges(backward, Edge, Rec, We0);\n\t#edge{ve=V,rtsu=AnEdge,ltpr=AnEdge}=Rec ->\n\t merge_edges(forward, Edge, Rec, We0);\n\n\t%% Handle the case that the incident edge is correct for\n\t%% the given vertex, but the vertex is NOT isolated.\n\t#edge{vs=V} -> done;\n\t#edge{ve=V} -> done;\n\n\t%% The incident edge is either non-existing or no longer\n\t%% references the given edge. In this case, we'll need\n\t%% to try dissolving the vertex again in the next\n\t%% pass after the incident table has been rebuilt.\n\tundefined -> We0;\n\t_ -> We0\n end.\n\n%%\n%% We like winged edges, but not winged vertices (a vertex with\n%% only two edges connected to it). We will remove the winged vertex\n%% by joining the two edges connected to it.\n%%\n\nmerge_edges(Dir, Edge, Rec, #we{es=Etab}=We) ->\n {Va,Vb,_,_,To,To} = half_edge(Dir, Rec),\n case array:get(To, Etab) of\n\t#edge{vs=Va,ve=Vb} ->\n\t del_2edge_face(Dir, Edge, Rec, To, We);\n\t#edge{vs=Vb,ve=Va} ->\n\t del_2edge_face(Dir, Edge, Rec, To, We);\n\t_Other ->\n\t merge_1(Dir, Edge, Rec, To, We)\n end.\n\nmerge_1(Dir, Edge, Rec, To, #we{es=Etab0,fs=Ftab0,he=Htab0}=We0) ->\n OtherDir = reverse_dir(Dir),\n {Vkeep,Vdelete,Lf,Rf,L,R} = half_edge(OtherDir, Rec),\n Etab1 = patch_edge(L, To, Edge, Etab0),\n Etab2 = patch_edge(R, To, Edge, Etab1),\n Etab3 = patch_half_edge(To, Vkeep, Lf, L, Rf, R, Vdelete, Etab2),\n Htab = hardness(Edge, soft, Htab0),\n Etab = array:reset(Edge, Etab3),\n #edge{lf=Lf,rf=Rf} = Rec,\n Ftab1 = update_face(Lf, To, Edge, Ftab0),\n Ftab = update_face(Rf, To, Edge, Ftab1),\n We1 = We0#we{es=Etab,fs=Ftab,he=Htab,vc=undefined},\n We = case {wings_va:any_attributes(We1),Dir} of\n\t {false,_} ->\n\t\t We1;\n\t {_,backward} ->\n\t\t Attr = wings_va:edge_attrs(Edge, right, We0),\n\t\t We2 = wings_va:set_edge_attrs(To, Rf, Attr, We1),\n\t\t wings_va:del_edge_attrs(Edge, We2);\n\t {_,forward} ->\n\t\t Attr = wings_va:edge_attrs(Edge, left, We0),\n\t\t We2 = wings_va:set_edge_attrs(To, Lf, Attr, We1),\n\t\t wings_va:del_edge_attrs(Edge, We2)\n\t end,\n merge_2(To, We).\n\nmerge_2(Edge, #we{es=Etab}=We) ->\n %% If the merged edge is part of a two-edge face, we must\n %% remove that edge too.\n case array:get(Edge, Etab) of\n\t#edge{ltpr=Same,ltsu=Same} ->\n\t internal_dissolve_edge(Edge, We);\n\t#edge{rtpr=Same,rtsu=Same} ->\n\t internal_dissolve_edge(Edge, We);\n\t_Other -> We\n end.\n\nupdate_face(Face, Edge, OldEdge, Ftab) ->\n case gb_trees:get(Face, Ftab) of\n\tOldEdge -> gb_trees:update(Face, Edge, Ftab);\n\t_Other -> Ftab\n end.\n\ndel_2edge_face(Dir, EdgeA, RecA, EdgeB,\n\t #we{es=Etab0,fs=Ftab0,he=Htab0,holes=Holes0}=We) ->\n {_,_,Lf,Rf,_,_} = half_edge(reverse_dir(Dir), RecA),\n RecB = array:get(EdgeB, Etab0),\n Del = gb_sets:from_list([EdgeA,EdgeB]),\n EdgeANear = stabile_neighbor(RecA, Del),\n EdgeBNear = stabile_neighbor(RecB, Del),\n Etab1 = patch_edge(EdgeANear, EdgeBNear, EdgeA, Etab0),\n Etab2 = patch_edge(EdgeBNear, EdgeANear, EdgeB, Etab1),\n Etab3 = array:reset(EdgeA, Etab2),\n Etab = array:reset(EdgeB, Etab3),\n\n %% Patch hardness table.\n Htab1 = hardness(EdgeA, soft, Htab0),\n Htab = hardness(EdgeB, soft, Htab1),\n\n %% Patch the face table.\n #edge{lf=Klf,rf=Krf} = array:get(EdgeANear, Etab),\n KeepFaces = ordsets:from_list([Klf,Krf]),\n EdgeAFaces = ordsets:from_list([Lf,Rf]),\n [DelFace] = ordsets:subtract(EdgeAFaces, KeepFaces),\n Ftab1 = gb_trees:delete(DelFace, Ftab0),\n [KeepFace] = ordsets:intersection(KeepFaces, EdgeAFaces),\n Ftab2 = update_face(KeepFace, EdgeANear, EdgeA, Ftab1),\n Ftab = update_face(KeepFace, EdgeBNear, EdgeB, Ftab2),\n\n %% It is probably unusual that 2 edge face is a hole,\n %% but better safe than sorry.\n Holes = ordsets:del_element(DelFace, Holes0),\n\n %% Return result.\n We#we{vc=undefined,es=Etab,fs=Ftab,he=Htab,holes=Holes}.\n\nstabile_neighbor(#edge{ltpr=Ea,ltsu=Eb,rtpr=Ec,rtsu=Ed}, Del) ->\n [Edge] = foldl(fun(E, A) ->\n\t\t\t case gb_sets:is_member(E, Del) of\n\t\t\t true -> A;\n\t\t\t false -> [E|A]\n\t\t\t end\n\t\t end, [], [Ea,Eb,Ec,Ed]),\n Edge.\n\n%%% Select region helpers.\n\nselect_region(Edges0, We) ->\n Part = wings_edge_loop:partition_edges(Edges0, We),\n Edges = select_region_borders(Edges0, We),\n FaceSel = select_region_1(Part, Edges, We, []),\n gb_sets:from_ordset(wings_we:visible(FaceSel, We)).\n\nselect_region_1([[AnEdge|_]|Ps], Edges, #we{es=Etab}=We, Acc) ->\n #edge{lf=Lf,rf=Rf} = array:get(AnEdge, Etab),\n Left = reachable_faces(Lf, Edges, We),\n Right = reachable_faces(Rf, Edges, We),\n\n %% We'll let AnEdge identify the edge loop that each\n %% face collection borders to.\n select_region_1(Ps, Edges, We, [{Left,AnEdge},{Right,AnEdge}|Acc]);\nselect_region_1([], _Edges, _We, Acc) ->\n %% Now we have all collections of faces sandwhiched between\n %% one or more edge loops. Using the face collections as keys,\n %% we will partition the edge loop identifiers into groups.\n\n Rel0 = [{gb_sets:to_list(Set),Edge} || {Set,Edge} <- Acc],\n Rel = sofs:relation(Rel0),\n Fam = sofs:relation_to_family(Rel),\n DirectCs = sofs:to_external(sofs:range(Fam)),\n\n %% DirectCs now contains lists of edge loop identifiers that\n %% can reach each other through a collection of face.\n %% Using a digraph, partition edge loop into components\n %% (each edge loop in a component can reach any other edge loop\n %% directly or indirectly).\n\n G = digraph:new(),\n make_digraph(G, DirectCs),\n Cs = digraph_utils:components(G),\n digraph:delete(G),\n\n %% Now having the components, consisting of edge identifiers\n %% identifying the original edge loop, we now need to partition\n %% the actual collection of faces.\n\n PartKey0 = [[{K,sofs:from_term(F)} || K <- Ks] || [F|_]=Ks <- Cs],\n PartKey = gb_trees:from_orddict(sort(lists:append(PartKey0))),\n SetFun = fun(S) ->\n\t\t {_,[E|_]} = sofs:to_external(S),\n\t\t gb_trees:get(E, PartKey)\n\t end,\n Part = sofs:to_external(sofs:partition(SetFun, Fam)),\n\n %% We finally have one partition for each sub-object.\n\n Sel = [select_region_2(P) || P <- Part],\n lists:merge(Sel).\n\nselect_region_2(P) ->\n case [Fs || {Fs,[_]} <- P] of\n\t[_|_]=Fss when length(Fss) < length(P) ->\n\t lists:merge(Fss);\n\t_ ->\n\t [{_,Fs}|_] = sort([{length(Fs),Fs} || {Fs,_} <- P]),\n\t Fs\n end.\n\nselect_region_borders(Edges0, #we{mirror=Mirror,holes=Holes}=We) ->\n Bs = case Mirror of\n\t none -> Holes;\n\t _ -> [Mirror|Holes]\n\t end,\n case Bs of\n\t[] ->\n\t Edges0;\n\t[_|_] ->\n\t BorderEdges = wings_face:to_edges(Bs, We),\n\t gb_sets:union(gb_sets:from_list(BorderEdges), Edges0)\n end.\n\nmake_digraph(G, [Es|T]) ->\n make_digraph_1(G, Es),\n make_digraph(G, T);\nmake_digraph(_, []) -> ok.\n\nmake_digraph_1(G, [E]) ->\n digraph:add_vertex(G, E);\nmake_digraph_1(G, [E1|[E2|_]=Es]) ->\n digraph:add_vertex(G, E1),\n digraph:add_vertex(G, E2),\n digraph:add_edge(G, E1, E2),\n make_digraph_1(G, Es).\n\ncollect_faces(Work0, We, Edges, Acc0) ->\n case gb_sets:is_empty(Work0) of\n\ttrue -> Acc0;\n\tfalse ->\n\t {Face,Work1} = gb_sets:take_smallest(Work0),\n\t Acc = gb_sets:insert(Face, Acc0),\n\t Work = collect_maybe_add(Work1, Face, Edges, We, Acc),\n\t collect_faces(Work, We, Edges, Acc)\n end.\n\ncollect_maybe_add(Work, Face, Edges, We, Res) ->\n wings_face:fold(\n fun(_, Edge, Rec, A) ->\n\t case gb_sets:is_member(Edge, Edges) of\n\t\t true -> A;\n\t\t false ->\n\t\t Of = wings_face:other(Face, Rec),\n\t\t case gb_sets:is_member(Of, Res) of\n\t\t\t true -> A;\n\t\t\t false -> gb_sets:add(Of, A)\n\t\t end\n\t end\n end, Work, Face, We).\n\n%%% Edge ring functions.\n\n-record(r,{id,l,r,\n\t ls=gb_sets:empty(),\n\t rs=gb_sets:empty()}).\n\nbuild_selection(Edges, We) ->\n Init = init_edge_ring([],unknown,Edges,We,0,[]),\n Stops0 = foldl(fun(#r{id=MyId,ls=O},S0) ->\n\t\t\t gb_sets:fold(fun(E,S) -> [{E,MyId} | S] end,\n\t\t\t\t\tS0, O)\n\t\t end,[],Init),\n Stop = gb_trees:from_orddict(lists:sort(Stops0)),\n Sel0 = grow_rings(Init,[],Stop,We,gb_sets:empty()),\n Sel = wings_we:visible_edges(Sel0, We),\n gb_sets:union(Sel, Edges).\n\ngrow_rings([First = #r{id=This}|R0],Rest0,Stop,We,Acc) ->\n case grow_ring1(First,Stop,We) of\n\t{stop, This, Edges} ->\n\t grow_rings(R0,Rest0,Stop,We,gb_sets:union(Edges,Acc));\n\t{stop, Id, Edges} ->\n\t R = lists:keydelete(Id,2,R0),\n\t Rest = lists:keydelete(Id,2,Rest0),\n\t grow_rings(R,Rest,Stop,We,gb_sets:union(Edges,Acc));\n\t{cont,New} ->\n\t grow_rings(R0,[New|Rest0],Stop,We,Acc)\n end;\ngrow_rings([],[],_,_,Acc) -> Acc;\ngrow_rings([],Rest,Stop,We,Acc) ->\n grow_rings(Rest, [], Stop, We, Acc).\n\ngrow_ring1(#r{id=Id,l=unknown,r=unknown,ls=LS,rs=RS},_Stop,_We) ->\n {stop, Id, gb_sets:union(LS,RS)};\ngrow_ring1(This = #r{id=ID,l=L0,ls=LS0,r=R0,rs=RS0},Stop,We) ->\n case grow_ring2(ID,L0,LS0,Stop,We) of\n\t{L,LS} ->\n\t case grow_ring2(ID,R0,RS0,Stop,We) of\n\t\t{R,RS} -> {cont,This#r{l=L,ls=LS,r=R,rs=RS}};\n\t\tBreak -> Break\n\t end;\n\tBreak -> Break\n end.\n\ngrow_ring2(ID,Edge,Edges,Stop,We) ->\n case grow_ring3(Edge,Edges,Stop,We) of\n\t{stop, ID, Edges} -> {unknown,Edges};\n\tElse -> Else\n end.\n\ngrow_ring3(unknown,Edges,_Stop,_We) ->\n {unknown,Edges};\ngrow_ring3(Edge,Edges,Stop,We) ->\n case gb_trees:lookup(Edge,Stop) of\n\t{value,Id} -> \n\t {stop,Id,Edges};\n\tnone -> \n\t Left = opposing_edge(Edge, We, left),\n\t case gb_sets:is_member(Left,Edges) of\n\t\tfalse ->\n\t\t {Left,gb_sets:add(Edge,Edges)};\n\t\ttrue ->\n\t\t Right = opposing_edge(Edge, We, right),\n\t\t case gb_sets:is_member(Right,Edges) of\n\t\t\ttrue -> {unknown, Edges};\n\t\t\tfalse -> {Right,gb_sets:add(Edge,Edges)}\n\t\t end\n\t end\n end.\n\ninit_edge_ring([],unknown,Edges0,We,Id,Acc) -> \n case gb_sets:is_empty(Edges0) of\n\ttrue -> Acc;\n\tfalse ->\n\t {Edge,Edges} = gb_sets:take_smallest(Edges0),\n\t Left = opposing_edge(Edge, We, left),\n\t Right = opposing_edge(Edge, We, right),\n\t init_edge_ring([Left,Right],#r{id=Id,l=Edge,r=Edge},Edges,We,Id+1,Acc)\n end;\ninit_edge_ring([],EI = #r{ls=LS},Edges0,We,Id,Acc) ->\n init_edge_ring([],unknown,Edges0,We,Id,[EI#r{rs=LS}|Acc]);\ninit_edge_ring([unknown|Rest],EI,Edges0,We,Id,Acc) ->\n init_edge_ring(Rest,EI,Edges0,We,Id,Acc);\ninit_edge_ring([Edge|Rest],EI0,Edges0,We,Id,Acc) ->\n case gb_sets:is_member(Edge,Edges0) of\n\ttrue -> \n\t {Next,EI}=replace_edge(Edge,EI0,We),\n\t init_edge_ring([Next|Rest],EI,gb_sets:delete(Edge,Edges0),We,Id,Acc);\n\tfalse ->\n\t {_Next,EI}=replace_edge(Edge,EI0,We),\n\t init_edge_ring(Rest,EI,Edges0,We,Id,Acc)\n end.\n\nreplace_edge(Edge,#r{l=L,r=R,ls=O} = EI,We) ->\n case opposing_edge(Edge,We,left) of\n\tL -> {opposing_edge(Edge,We,right),EI#r{l=Edge,ls=gb_sets:add(L,O)}};\n\tR -> {opposing_edge(Edge,We,right),EI#r{r=Edge,ls=gb_sets:add(R,O)}};\n\tunknown ->\n\t case opposing_edge(Edge,We,right) of\n\t\tL -> {unknown, EI#r{l=Edge,ls=gb_sets:add(L,O)}};\n\t\tR -> {unknown, EI#r{r=Edge,ls=gb_sets:add(R,O)}}\n\t end;\n\tOther -> \n\t case opposing_edge(Edge,We,right) of\n\t\tL -> {Other, EI#r{l=Edge,ls=gb_sets:add(L,O)}};\n\t\tR -> {Other, EI#r{r=Edge,ls=gb_sets:add(R,O)}}\n\t end\n end.\n\nopposing_edge(Edge, #we{es=Es}=We, Side) ->\n #edge{lf=Left,rf=Right} = array:get(Edge, Es),\n Face = case Side of\n left -> Left;\n right -> Right\n end,\n %% Get opposing edge or fail.\n case wings_face:vertices(Face, We) of\n 4 -> next_edge(next_edge(Edge, Face, We), Face, We);\n _ -> unknown\n end.\n\nnext_edge(Edge, Face, #we{es=Etab})->\n case array:get(Edge, Etab) of\n #edge{lf=Face,ltsu=NextEdge} -> NextEdge;\n #edge{rf=Face,rtsu=NextEdge} -> NextEdge\n end.\n\nincr_ring_selection(Edges, We) ->\n gb_sets:fold(fun(Edge, EdgeAcc) ->\n\t\t\t Es = incr_from_edge(Edge, We, EdgeAcc),\n\t\t\t wings_we:visible_edges(Es, We)\n\t\t end, gb_sets:empty(), Edges).\n\nincr_from_edge(Edge, We, Acc) ->\n Selected = gb_sets:add(Edge, Acc),\n LeftSet =\n\tcase opposing_edge(Edge, We, left) of\n\t unknown -> Selected;\n\t Left -> gb_sets:add(Left, Selected)\n\tend,\n case opposing_edge(Edge, We, right) of\n\tunknown -> LeftSet;\n\tRight -> gb_sets:add(Right, LeftSet)\n end.\n\ndecr_ring_selection(Edges, We) ->\n gb_sets:fold(fun(Edge, EdgeAcc) ->\n\t\t\t decr_from_edge(Edge, We, Edges, EdgeAcc)\n\t\t end, Edges, Edges).\n\ndecr_from_edge(Edge, We, Orig, Acc) ->\n Left = opposing_edge(Edge, We, left),\n Right = opposing_edge(Edge, We, right),\n case (Left == unknown) or (Right == unknown) of\n\ttrue ->\n\t gb_sets:delete(Edge,Acc);\n\tfalse ->\n\t case gb_sets:is_member(Left, Orig) and\n\t\tgb_sets:is_member(Right, Orig) of\n\t\ttrue ->\n\t\t Acc;\n\t\tfalse ->\n\t\t gb_sets:delete(Edge, Acc)\n\t end\n end.\n\n%%%\n%%% Utilities.\n%%%\n\nreverse_dir(forward) -> backward;\nreverse_dir(backward) -> forward.\n\nhalf_edge(backward, #edge{vs=Va,ve=Vb,lf=Lf,rf=Rf,ltsu=L,rtpr=R}) ->\n {Va,Vb,Lf,Rf,L,R};\nhalf_edge(forward, #edge{ve=Va,vs=Vb,lf=Lf,rf=Rf,ltpr=L,rtsu=R}) ->\n {Va,Vb,Lf,Rf,L,R}.\n\npatch_half_edge(Edge, V, FaceA, Ea, FaceB, Eb, OrigV, Etab) ->\n New = case array:get(Edge, Etab) of\n\t #edge{vs=OrigV,lf=FaceA,rf=FaceB}=Rec ->\n\t\t Rec#edge{vs=V,ltsu=Ea,rtpr=Eb};\n\t #edge{vs=OrigV,lf=FaceB,rf=FaceA}=Rec ->\n\t\t Rec#edge{vs=V,ltsu=Eb,rtpr=Ea};\n\t #edge{ve=OrigV,lf=FaceA,rf=FaceB}=Rec ->\n\t\t Rec#edge{ve=V,ltpr=Ea,rtsu=Eb};\n\t #edge{ve=OrigV,lf=FaceB,rf=FaceA}=Rec ->\n\t\t Rec#edge{ve=V,ltpr=Eb,rtsu=Ea}\n\t end,\n array:set(Edge, New, Etab).\n\npatch_edge(Edge, ToEdge, OrigEdge, Etab) ->\n New = case array:get(Edge, Etab) of\n\t #edge{ltsu=OrigEdge}=R ->\n\t\t R#edge{ltsu=ToEdge};\n\t #edge{ltpr=OrigEdge}=R ->\n\t\t R#edge{ltpr=ToEdge};\n\t #edge{rtsu=OrigEdge}=R ->\n\t\t R#edge{rtsu=ToEdge};\n\t #edge{rtpr=OrigEdge}=R ->\n\t\t R#edge{rtpr=ToEdge}\n\t end,\n array:set(Edge, New, Etab).\n\npatch_edge(Edge, ToEdge, Face, OrigEdge, Etab) ->\n New = case array:get(Edge, Etab) of\n\t #edge{lf=Face,ltsu=OrigEdge}=R ->\n\t\t R#edge{ltsu=ToEdge};\n\t #edge{lf=Face,ltpr=OrigEdge}=R ->\n\t\t R#edge{ltpr=ToEdge};\n\t #edge{rf=Face,rtsu=OrigEdge}=R ->\n\t\t R#edge{rtsu=ToEdge};\n\t #edge{rf=Face,rtpr=OrigEdge}=R ->\n\t\t R#edge{rtpr=ToEdge}\n\t end,\n array:set(Edge, New, Etab).\n\n%%%% Select every nth ring\n\nselect_nth_ring(N, #st{selmode=edge}=St) ->\n wings_sel:update_sel(\n fun(Edges, We) ->\n\t EdgeRings = nth_ring_1(Edges, {N,N}, We, Edges, gb_sets:new()),\n\t wings_we:visible_edges(EdgeRings, We)\n end, St);\nselect_nth_ring(_N, St) ->\n St.\n\nnth_ring_1(Edges0, N, We, OrigEs, Acc) ->\n case gb_sets:is_empty(Edges0) of\n true -> Acc;\n false ->\n {Edge,Edges1} = gb_sets:take_smallest(Edges0),\n Rings = nth_ring_2(Edge, N, We, OrigEs, gb_sets:singleton(Edge)),\n Edges = gb_sets:subtract(Edges1, Rings),\n nth_ring_1(Edges, N, We, OrigEs, gb_sets:union(Rings,Acc))\n end.\n\nnth_ring_2(Edge, {N,Int}, We, OrigEs, Acc) ->\n case opposing_edge(Edge, We, left) of\n unknown ->\n case opposing_edge(Edge, We, right) of\n unknown ->\n Acc;\n NextEdge ->\n {_,Edges0} = nth_ring_3(NextEdge,Edge,Edge,{N-1,Int},right,left,We,OrigEs,Acc),\n Edges0\n end;\n NextEdge ->\n {Check0,Edges0} = case gb_sets:is_member(NextEdge,OrigEs) of\n true -> {stop,Acc};\n false -> nth_ring_3(NextEdge,Edge,Edge,{N-1,Int},left,right,We,OrigEs,Acc)\n end,\n case opposing_edge(Edge, We, right) of\n unknown ->\n Edges0;\n PrevEdge ->\n {Check1,Edges1} = case gb_sets:is_member(PrevEdge,OrigEs) of\n true -> {stop,Acc};\n false -> nth_ring_3(PrevEdge,Edge,Edge,{N-1,Int},right,left,We,OrigEs,Acc)\n end,\n nth_ring_4(Check0,Edges0,Check1,Edges1,OrigEs)\n end\n end.\n\nnth_ring_3(CurEdge,PrevEdge,LastEdge,{0,N},Side,Oposite,We,OrigEs,Acc0) ->\n Acc = gb_sets:insert(CurEdge,Acc0),\n nth_ring_3(CurEdge,PrevEdge,LastEdge,{N,N},Side,Oposite,We,OrigEs,Acc);\nnth_ring_3(CurEdge,PrevEdge,LastEdge,{N0,Int},Side,Oposite,We,OrigEs,Acc) ->\n case opposing_edge(CurEdge, We, Side) of\n unknown -> {ok,Acc};\n PrevEdge ->\n case opposing_edge(CurEdge, We, Oposite) of\n unknown -> {ok,Acc};\n PrevEdge -> {ok,Acc};\n LastEdge -> {ok,Acc};\n NextEdge ->\n case gb_sets:is_member(NextEdge,OrigEs) of\n true ->\n {stop,Acc};\n false ->\n nth_ring_3(NextEdge,CurEdge,LastEdge,{N0-1,Int},Oposite,Side,We,OrigEs,Acc)\n end\n end;\n LastEdge -> {ok,Acc};\n NextEdge ->\n case gb_sets:is_member(NextEdge,OrigEs) of\n true ->\n {stop,Acc};\n false ->\n nth_ring_3(NextEdge,CurEdge,LastEdge,{N0-1,Int},Side,Oposite,We,OrigEs,Acc)\n end\n end.\n\nnth_ring_4(_,Edges,_,Edges,_) ->\n Edges;\nnth_ring_4(Check0,Edges0,Check1,Edges1,OrigEs) ->\n S0 = gb_sets:size(Edges0),\n S1 = gb_sets:size(Edges1),\n if\n S0 =:= 1 -> Edges1;\n S1 =:= 1 -> Edges0;\n true -> nth_ring_5(Check0,S0,Edges0,Check1,S1,Edges1,OrigEs)\n end.\n\nnth_ring_5(ok,_,Edges0,ok,_,Edges1,_) ->\n gb_sets:union(Edges0,Edges1);\nnth_ring_5(stop,S0,Edges0,stop,S1,Edges1,_) ->\n case S0 > S1 of\n true -> Edges1;\n false -> Edges0\n end;\nnth_ring_5(stop,_,Edges0,_,_,Edges1,OrigEs) ->\n case gb_sets:is_subset(Edges0,OrigEs) of\n true -> Edges1;\n false -> Edges0\n end;\nnth_ring_5(_,_,Edges0,stop,_,Edges1,OrigEs) ->\n case gb_sets:is_subset(Edges1,OrigEs) of\n true -> Edges0;\n false -> Edges1\n end.\n\n%%%% Select every nth loop\n\nselect_nth_loop(0, St) -> St;\nselect_nth_loop(N, #st{selmode=edge}=St0) ->\n St = wings_edge_loop:stoppable_sel_loop(St0),\n wings_sel:update_sel(\n fun(Edges, We) ->\n Links = wings_edge_loop:edge_links(Edges, We),\n SelLoop0 = nth_loop(Links, N-1, []),\n SelLoop = gb_sets:from_list(SelLoop0),\n wings_we:visible_edges(SelLoop, We)\n end, St);\nselect_nth_loop(_N, St) ->\n St.\n\nnth_loop([], _, Acc) -> Acc;\nnth_loop([Es|Links], N, Acc) ->\n nth_loop(Links, N, nth_loop_1(Es, N, Acc)).\n\nnth_loop_1([{Last,_,_}], _, Acc) -> [Last|Acc];\nnth_loop_1([{E,_,_}|Es], N, Acc) ->\n nth_loop_1(skip_n(Es, N), N, [E|Acc]).\n\nskip_n([_]=Es, _) -> Es;\nskip_n(Edges, 0) -> Edges;\nskip_n([_|Edges], N) -> skip_n(Edges, N-1).\n","avg_line_length":32.6333656644,"max_line_length":103,"alphanum_fraction":0.6298112647} +{"size":265,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%% This module is ignorant about any features and thus use 'ifn',\n%% 'maybe' and 'then' as ordinary atoms.\n\n-module(feature_ignorant).\n\n-export([foo\/0]).\n\nfoo() ->\n [ifn, while, until].\n\nfrob(while) -> false.\n\nbar() ->\n [until, while].\n\nbaz(ifn) ->\n true.\n","avg_line_length":14.7222222222,"max_line_length":65,"alphanum_fraction":0.6075471698} +{"size":9001,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%-*-Mode:erlang;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-\n% ex: set ft=erlang fenc=utf-8 sts=4 ts=4 sw=4 et nomod:\n%% @doc Multicast Erlang node discovery protocol.\n%% Listens on a multicast channel for node discovery requests and \n%% responds by connecting to the node.\n%% @end\n\n-module(nodefinder_multicast).\n\n-behaviour(gen_server).\n\n%% external interface\n-export([start_link\/5,\n discover\/1]).\n\n%% gen_server callbacks\n-export([init\/1,\n handle_call\/3, handle_cast\/2, handle_info\/2,\n terminate\/2, code_change\/3]).\n\n-record(state,\n {\n socket_send :: gen_udp:socket(),\n socket_recv :: gen_udp:socket(),\n address :: inet:ip_address(),\n port :: inet:port_number(),\n timeout :: pos_integer(), % seconds\n connect :: visible | hidden,\n node :: binary(),\n key_v4 :: binary(),\n key_v3 :: binary(),\n key_v2 :: binary()\n }).\n\n-include(\"nodefinder.hrl\").\n-include(\"nodefinder_logging.hrl\").\n\n-define(MULTICAST_MESSAGE_NAME, \"ERLANG\/NODEFINDER\").\n-define(MULTICAST_MESSAGE_PROTOCOL_VERSION, \"4\").\n\n% how much time synchronization error to handle between nodes\n% (need to have ntpd running when using this source code)\n-define(MULTICAST_MESSAGE_VALID_SECONDS, 300). % 5 minutes\n\n%%%------------------------------------------------------------------------\n%%% External interface functions\n%%%------------------------------------------------------------------------\n\nstart_link(Interface, Address, Port, TTL, TimeoutSeconds) ->\n gen_server:start_link({local, ?MODULE}, ?MODULE,\n [Interface, Address, Port, TTL, TimeoutSeconds], []).\n\ndiscover(Timeout) ->\n try gen_server:call(?MODULE, discover, Timeout)\n catch\n exit:{Reason, _} ->\n {error, Reason}\n end.\n\n%%%------------------------------------------------------------------------\n%%% Callback functions from gen_server\n%%%------------------------------------------------------------------------\n\ninit([Interface, Address, Port, TTL, TimeoutSeconds]) ->\n Opts = [{active, once},\n {ip, Address},\n {multicast_if, Interface},\n {add_membership, {Address, Interface}},\n {multicast_loop, true},\n {reuseaddr, true},\n binary],\n {ok, SocketRecv} = gen_udp:open(Port, Opts),\n Connect = nodefinder_app:connect_type(),\n State = #state{socket_recv = SocketRecv,\n socket_send = send_socket(Interface, TTL),\n address = Address,\n port = Port,\n timeout = TimeoutSeconds,\n connect = Connect,\n node = erlang:atom_to_binary(node(), utf8),\n key_v4 = key_v4(),\n key_v3 = key_v3(),\n key_v2 = key_v2()},\n ok = send_discover(State),\n {ok, State}.\n\nhandle_call(discover, _From, State) ->\n ok = send_discover(State),\n {reply, ok, State};\nhandle_call(Request, _From, State) ->\n {stop, lists:flatten(io_lib:format(\"Unknown call \\\"~w\\\"\", [Request])),\n error, State}.\n\nhandle_cast(Request, State) ->\n {stop, lists:flatten(io_lib:format(\"Unknown cast \\\"~w\\\"\", [Request])),\n State}.\n\nhandle_info({udp, SocketRecv, IP, _InPortNo, Packet},\n #state{socket_recv = SocketRecv} = State) ->\n inet:setopts(SocketRecv, [{active, once}]),\n ok = process_packet(Packet, IP, State),\n {noreply, State};\n\nhandle_info(Request, State) ->\n {stop, lists:flatten(io_lib:format(\"Unknown info \\\"~w\\\"\", [Request])),\n State}.\n\nterminate(_Reason,\n #state{socket_recv = SocketRecv,\n socket_send = SocketSend}) ->\n gen_udp:close(SocketRecv),\n gen_udp:close(SocketSend),\n ok.\n\ncode_change(_OldVsn, State, _Extra) -> \n {ok, State}.\n\n%%%------------------------------------------------------------------------\n%%% Private functions\n%%%------------------------------------------------------------------------\n\nsend_discover(#state{socket_send = SocketSend,\n address = Address,\n port = Port,\n node = NodeBin,\n key_v4 = KeyV4}) ->\n Seconds = seconds_v4(),\n SecondsBin = <>,\n Identifier = identifier_v4([SecondsBin, NodeBin], KeyV4),\n Message = <>,\n case gen_udp:send(SocketSend, Address, Port, Message) of\n ok ->\n ok;\n {error, Reason} ->\n % enetunreach can occur here\n ?LOG_WARN(\"udp error: ~p\", [Reason]),\n ok\n end.\n\nprocess_packet(<>, IP,\n #state{timeout = Timeout,\n connect = Connect,\n key_v4 = KeyV4}) ->\n IdentifierExpected = identifier_v4([SecondsBin, NodeBin], KeyV4),\n if\n Identifier \/= IdentifierExpected ->\n ok; % ignored, different cookie\n true ->\n <> = SecondsBin,\n Delta = seconds_v4() - Seconds,\n if\n Delta >= (-1 * ?MULTICAST_MESSAGE_VALID_SECONDS),\n Delta < Timeout ->\n Node = erlang:binary_to_atom(NodeBin, utf8),\n connect_node(Connect, Node);\n true ->\n ?LOG_WARN(\"expired multicast from ~s (~p)\",\n [NodeBin, IP])\n end\n end,\n ok;\nprocess_packet(<<\"ERLANG\/NODEFINDER 3 \",\n Identifier:32\/binary, \" \",\n SecondsBin:8\/binary, \" \",\n NodeBin\/binary>>, IP,\n #state{timeout = Timeout,\n connect = Connect,\n key_v3 = KeyV3}) ->\n % nodefinder 1.7.3 support\n IdentifierExpected = identifier_v3([SecondsBin, NodeBin], KeyV3),\n if\n Identifier \/= IdentifierExpected ->\n ok; % ignored, different cookie\n true ->\n <> = SecondsBin,\n Delta = seconds_v3() - Seconds,\n if\n Delta >= (-1 * ?MULTICAST_MESSAGE_VALID_SECONDS),\n Delta < Timeout ->\n Node = erlang:binary_to_atom(NodeBin, utf8),\n connect_node(Connect, Node);\n true ->\n ?LOG_WARN(\"expired multicast from ~s (~p)\",\n [NodeBin, IP])\n end\n end,\n ok;\nprocess_packet(<<\"DISCOVERV2 \",\n Identifier:20\/binary, \" \", \n SecondsBin:8\/binary, \" \",\n NodeBin\/binary>>, IP,\n #state{timeout = Timeout,\n connect = Connect,\n key_v2 = KeyV2}) ->\n % nodefinder =< 1.7.2 support\n IdentifierExpected = identifier_v2([SecondsBin, NodeBin], KeyV2),\n if\n Identifier \/= IdentifierExpected ->\n ok; % ignored, different cookie\n true ->\n <> = SecondsBin,\n Delta = seconds_v2() - Seconds,\n if\n Delta >= (-1 * ?MULTICAST_MESSAGE_VALID_SECONDS),\n Delta < Timeout ->\n Node = erlang:binary_to_atom(NodeBin, latin1),\n connect_node(Connect, Node);\n true ->\n ?LOG_WARN(\"expired multicast from ~s (~p)\",\n [NodeBin, IP])\n end\n end,\n ok;\nprocess_packet(_Packet, _IP, _State) -> \n ok.\n\nidentifier_v4(Message, KeyV4) ->\n crypto:hmac(sha256, KeyV4, Message).\n\nidentifier_v3(Message, KeyV3) ->\n crypto:hmac(sha256, KeyV3, Message).\n\nidentifier_v2(Message, KeyV2) ->\n crypto:hmac(sha, KeyV2, Message).\n\nkey_v4() ->\n crypto:hash(sha256, erlang:atom_to_binary(erlang:get_cookie(), utf8)).\n\nkey_v3() ->\n crypto:hash(sha256, erlang:term_to_binary(erlang:get_cookie())).\n\nkey_v2() ->\n crypto:hash(sha, erlang:term_to_binary(erlang:get_cookie())).\n\nseconds_v4() ->\n seconds_v3().\n\n-ifdef(ERLANG_OTP_VERSION_20_FEATURES).\nseconds_v3() ->\n erlang:system_time(second).\n-else.\nseconds_v3() ->\n erlang:system_time(seconds).\n-endif.\n\nseconds_v2() ->\n calendar:datetime_to_gregorian_seconds(calendar:universal_time()).\n\nsend_socket(Interface, TTL) ->\n SendOpts = [{ip, Interface},\n {multicast_ttl, TTL}, \n {multicast_loop, true}],\n {ok, SocketSend} = gen_udp:open(0, SendOpts),\n SocketSend.\n\nconnect_node(_, Node)\n when Node =:= node() ->\n ok;\nconnect_node(visible, Node) ->\n net_kernel:connect_node(Node);\nconnect_node(hidden, Node) ->\n net_kernel:hidden_connect_node(Node).\n\n","avg_line_length":33.0919117647,"max_line_length":80,"alphanum_fraction":0.5268303522} +{"size":877,"ext":"erl","lang":"Erlang","max_stars_count":4.0,"content":"%%%\n%%% Copyright (c) 2016 The Talla Authors. All rights reserved.\n%%% Use of this source code is governed by a BSD-style\n%%% license that can be found in the LICENSE file.\n%%%\n%%% -----------------------------------------------------------\n%%% @author Alexander F\u00e6r\u00f8y \n%%% @doc Pub\/Sub API\n%%%\n%%% @end\n%%% -----------------------------------------------------------\n-module(onion_pubsub).\n\n%% API.\n-export([subscribe\/1,\n send\/2\n ]).\n\n%% @doc Subscribe to a given topic.\n-spec subscribe(Topic) -> true\n when\n Topic :: term().\nsubscribe(Topic) ->\n gproc:reg({p, l, {?MODULE, Topic}}).\n\n%% @doc Send a message to a given topic.\n-spec send(Topic, Message) -> {pid(), Topic, Message}\n when\n Topic :: term(),\n Message :: term().\nsend(Topic, Message) ->\n gproc:send({p, l, {?MODULE, Topic}}, {self(), Topic, Message}).\n","avg_line_length":26.5757575758,"max_line_length":67,"alphanum_fraction":0.5074116306} +{"size":1071,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(mero_util).\n\n-export([foreach\/2, to_int\/1, to_bin\/1]).\n\n%%%===================================================================\n%%% API\n%%%===================================================================\n\n-spec foreach(fun((Elem :: term()) -> {break, term()} | continue),\n list()) -> term().\nforeach(Fun, L) ->\n foreach(continue, Fun, L).\n\nto_int(Value) when is_integer(Value) ->\n Value;\nto_int(Value) when is_list(Value) ->\n list_to_integer(Value);\nto_int(Value) when is_binary(Value) ->\n to_int(binary_to_list(Value)).\n\nto_bin(Value) when is_binary(Value) ->\n Value;\nto_bin(Value) when is_integer(Value) ->\n to_bin(integer_to_list(Value));\nto_bin(Value) when is_list(Value) ->\n list_to_binary(Value).\n\n%%%===================================================================\n%%% Internal Functions\n%%%===================================================================\n\nforeach({break, Reason}, _Fun, _L) ->\n Reason;\nforeach(continue, _Fun, []) ->\n ok;\nforeach(continue, Fun, [H|Rest]) ->\n foreach(Fun(H), Fun, Rest).\n","avg_line_length":28.1842105263,"max_line_length":70,"alphanum_fraction":0.4705882353} +{"size":29809,"ext":"erl","lang":"Erlang","max_stars_count":13.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2002-2021. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n\n%%\n\n-module(odbc_connect_SUITE).\n\n%% Note: This directive should only be used in test suites.\n-compile(export_all).\n\n-include_lib(\"common_test\/include\/ct.hrl\").\n-include(\"odbc_test.hrl\").\n\n-define(MAX_SEQ_TIMEOUTS, 10).\n\n%%--------------------------------------------------------------------\n%% all(Arg) -> [Doc] | [Case] | {skip, Comment}\n%% Arg - doc | suite\n%% Doc - string()\n%% Case - atom() \n%%\tName of a test case function. \n%% Comment - string()\n%% Description: Returns documentation\/test cases in this test suite\n%%\t\tor a skip tuple if the platform is not supported. \n%%--------------------------------------------------------------------\n\nsuite() -> [{ct_hooks,[ts_install_cth]}].\n\nall() -> \n case odbc_test_lib:odbc_check() of\n\tok ->\n\t [not_exist_db, commit, rollback, not_explicit_commit,\n\t no_c_executable, port_dies, control_process_dies,\n\t {group, client_dies}, connect_timeout, timeout,\n\t many_timeouts, timeout_reset, disconnect_on_timeout,\n\t connection_closed, disable_scrollable_cursors,\n\t return_rows_as_lists, api_missuse, extended_errors];\n\tOther -> {skip, Other}\n end.\n\ngroups() -> \n [{client_dies, [],\n [client_dies_normal, client_dies_timeout,\n client_dies_error]}].\n\ninit_per_group(_GroupName, Config) ->\n Config.\n\nend_per_group(_GroupName, Config) ->\n Config.\n\n\n%%--------------------------------------------------------------------\n%% Function: init_per_suite(Config) -> Config\n%% Config - [tuple()]\n%% A list of key\/value pairs, holding the test case configuration.\n%% Description: Initiation before the whole suite\n%%\n%% Note: This function is free to add any key\/value pairs to the Config\n%% variable, but should NOT alter\/remove any existing entries.\n%%--------------------------------------------------------------------\ninit_per_suite(Config) when is_list(Config) ->\n file:write_file(filename:join([proplists:get_value(priv_dir,Config),\n\t\t\t\t \"..\",\"..\",\"..\",\"ignore_core_files\"]),\"\"),\n case odbc_test_lib:skip() of\n\ttrue ->\n\t {skip, \"ODBC not supported\"};\n\tfalse ->\n\t case (catch odbc:start()) of\n\t\tok ->\n\t\t case catch odbc:connect(?RDBMS:connection_string(),\n\t\t\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()) of\n\t\t\t{ok, Ref} ->\n\t\t\t odbc:disconnect(Ref),\n\t\t\t ct:timetrap(?default_timeout),\n\t\t\t [{tableName, odbc_test_lib:unique_table_name()} | Config];\n\t\t\t_ ->\n\t\t\t {skip, \"ODBC is not properly setup\"}\n\t\t end;\n\t\t_ ->\n\t\t {skip,\"ODBC not startable\"}\n\t end\n end.\n\n%%--------------------------------------------------------------------\n%% Function: end_per_suite(Config) -> _\n%% Config - [tuple()]\n%% A list of key\/value pairs, holding the test case configuration.\n%% Description: Cleanup after the whole suite\n%%--------------------------------------------------------------------\nend_per_suite(_Config) ->\n application:stop(odbc).\n\n%%--------------------------------------------------------------------\n%% Function: init_per_testcase(Case, Config) -> Config\n%% Case - atom()\n%% Name of the test case that is about to be run.\n%% Config - [tuple()]\n%% A list of key\/value pairs, holding the test case configuration.\n%%\n%% Description: Initiation before each test case\n%%\n%% Note: This function is free to add any key\/value pairs to the Config\n%% variable, but should NOT alter\/remove any existing entries.\n%%--------------------------------------------------------------------\ninit_per_testcase(connect_port_timeout, Config) ->\n odbc:stop(),\n application:load(odbc),\n application:set_env(odbc, port_timeout, 0),\n odbc:start(),\n init_per_testcase_common(Config);\ninit_per_testcase(_TestCase, Config) ->\n init_per_testcase_common(Config).\n\ninit_per_testcase_common(Config) ->\n ct:pal(\"ODBCINI = ~p~n\", [os:getenv(\"ODBCINI\")]),\n lists:keydelete(connection_ref, 1, Config).\n\n%%--------------------------------------------------------------------\n%% Function: end_per_testcase(Case, Config) -> _\n%% Case - atom()\n%% Name of the test case that is about to be run.\n%% Config - [tuple()]\n%% A list of key\/value pairs, holding the test case configuration.\n%% Description: Cleanup after each test case\n%%--------------------------------------------------------------------\n\nend_per_testcase(connect_port_timeout, Config) ->\n application:unset_env(odbc, port_timeout),\n odbc:stop(),\n odbc:start(),\n end_per_testcase_common(Config);\nend_per_testcase(_TestCase, Config) ->\n end_per_testcase_common(Config).\n\nend_per_testcase_common(Config) ->\n Table = proplists:get_value(tableName, Config),\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n Result = odbc:sql_query(Ref, \"DROP TABLE \" ++ Table),\n io:format(\"Drop table: ~p ~p~n\", [Table, Result]),\n odbc:disconnect(Ref).\n\n%%-------------------------------------------------------------------------\n%% Test cases starts here.\n%%-------------------------------------------------------------------------\ncommit()->\n [{doc,\"Test the use of explicit commit\"}].\ncommit(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), \n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n\n Table = proplists:get_value(tableName, Config),\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10))\" ++ TransStr),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++\" VALUES(1,'bar')\"),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n\n ok = odbc:commit(Ref, commit),\n UpdateResult = ?RDBMS:update_result(),\n UpdateResult = \n\todbc:sql_query(Ref, \"SELECT * FROM \" ++ Table),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'bar' WHERE ID = 1\"),\n ok = odbc:commit(Ref, commit, ?TIMEOUT),\n InsertResult = ?RDBMS:insert_result(),\n InsertResult = \n\todbc:sql_query(Ref, \"SELECT * FROM \" ++ Table),\n\n {'EXIT', {function_clause, _}} = \n\t(catch odbc:commit(Ref, commit, -1)),\n\n ok = odbc:disconnect(Ref).\n%%-------------------------------------------------------------------------\n\nrollback()->\n [{doc,\"Test the use of explicit rollback\"}].\nrollback(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n\n Table = proplists:get_value(tableName, Config),\n\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} =\n\todbc:sql_query(Ref,\n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t\t \" (ID integer, DATA varchar(10))\" ++ TransStr),\n {updated, 1} =\n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n ok = odbc:commit(Ref, commit),\n\n {updated, 1} =\n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n ok = odbc:commit(Ref, rollback),\n InsertResult = ?RDBMS:insert_result(),\n InsertResult =\n\todbc:sql_query(Ref, \"SELECT * FROM \" ++ Table),\n {updated, 1} =\n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n ok = odbc:commit(Ref, rollback, ?TIMEOUT),\n InsertResult = ?RDBMS:insert_result(),\n InsertResult =\n\todbc:sql_query(Ref, \"SELECT * FROM \" ++ Table),\n\n {'EXIT', {function_clause, _}} =\n\t(catch odbc:commit(Ref, rollback, -1)),\n\n ok = odbc:disconnect(Ref).\n\n%%-------------------------------------------------------------------------\nnot_explicit_commit() ->\n [{doc,\"Test what happens if you try using commit on a auto_commit connection.\"}].\nnot_explicit_commit(_Config) ->\n {ok, Ref} = \n\todbc:connect(?RDBMS:connection_string(), [{auto_commit, on}] ++\n\t\t odbc_test_lib:platform_options()),\n {error, _} = odbc:commit(Ref, commit),\n ok = odbc:disconnect(Ref).\n\n%%-------------------------------------------------------------------------\nnot_exist_db() ->\n [{doc,\"Tests valid data format but invalid data in the connection parameters.\"}].\nnot_exist_db(_Config) ->\n {error, _} = odbc:connect(\"DSN=foo;UID=bar;PWD=foobar\",\n\t\t\t odbc_test_lib:platform_options()),\n %% So that the odbc control server can be stoped \"in the correct way\"\n ct:sleep(100).\n\n%%-------------------------------------------------------------------------\nno_c_executable() ->\n [{doc,\"Test what happens if the port-program cannot be found\"}].\nno_c_executable(_Config) ->\n process_flag(trap_exit, true),\n Dir = filename:nativename(filename:join(code:priv_dir(odbc), \n\t\t\t\t\t \"bin\")),\n FileName1 = filename:nativename(os:find_executable(\"odbcserver\", \n\t\t\t\t\t\t Dir)),\n FileName2 = filename:nativename(filename:join(Dir, \"odbcsrv\")),\n case file:rename(FileName1, FileName2) of\n\tok ->\n\t Result = \n\t\tcase catch odbc:connect(?RDBMS:connection_string(),\n\t\t\t\t\todbc_test_lib:platform_options()) of\n\t\t {error, port_program_executable_not_found} ->\n\t\t\tok;\n\t\t Else ->\n\t\t\tElse\n\t\tend,\n\t ok = file:rename(FileName2, FileName1), \n\t ok = Result;\n\t_ ->\n\t {skip, \"File permission issues\"}\n end.\n%%------------------------------------------------------------------------\n\nport_dies() ->\n [{doc,\"Tests what happens if the port program dies\"}].\nport_dies(_Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n {status, _} = process_info(Ref, status), \n process_flag(trap_exit, true),\n NamedPorts = [{P, erlang:port_info(P, name)} || P <- erlang:ports()],\n case [P || {P, {name, Name}} <- NamedPorts, is_odbcserver(Name)] of\n\t[Port] ->\n\t exit(Port, kill),\n\t %% Wait for exit_status from port 5000 ms (will not get a exit\n\t %% status in this case), then wait a little longer to make sure\n\t %% the port and the controlprocess has had time to terminate.\n\t ct:sleep(10000),\n\t undefined = process_info(Ref, status);\n\t[] ->\n\t ct:fail([erlang:port_info(P, name) || P <- erlang:ports()]) \n end.\n\n\n%%-------------------------------------------------------------------------\ncontrol_process_dies() ->\n [{doc,\"Tests what happens if the Erlang control process dies\"}].\ncontrol_process_dies(_Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n process_flag(trap_exit, true),\n NamedPorts = [{P, erlang:port_info(P, name)} || P <- erlang:ports()],\n case [P || {P, {name, Name}} <- NamedPorts, is_odbcserver(Name)] of\n\t[Port] ->\n\t {connected, Ref} = erlang:port_info(Port, connected), \n\t exit(Ref, kill),\n\t ct:sleep(500),\n\t undefined = erlang:port_info(Port, connected);\n\t%% Check for c-program still running, how?\n\t[] ->\n\t ct:fail([erlang:port_info(P, name) || P <- erlang:ports()]) \n end.\n\n%%-------------------------------------------------------------------------\nclient_dies_normal() ->\n [{doc,\"Client dies with reason normal.\"}].\nclient_dies_normal(Config) when is_list(Config) ->\n Pid = spawn(?MODULE, client_normal, [self()]),\n\n MonitorReference =\n\treceive \n\t {dbRef, Ref} ->\n\t\tMRef = erlang:monitor(process, Ref),\n\t\tPid ! continue,\n\t\tMRef\n\tend,\n\n receive \n\t{'DOWN', MonitorReference, _Type, _Object, _Info} ->\n\t ok\n after 5000 ->\n\t ct:fail(control_process_not_stopped)\n end.\n\nclient_normal(Pid) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n Pid ! {dbRef, Ref},\n receive \n\tcontinue ->\n\t ok\n end,\n exit(self(), normal).\n\n\n%%-------------------------------------------------------------------------\nclient_dies_timeout() ->\n [{doc,\"Client dies with reason timeout.\"}].\nclient_dies_timeout(Config) when is_list(Config) ->\n Pid = spawn(?MODULE, client_timeout, [self()]),\n\n MonitorReference =\n\treceive \n\t {dbRef, Ref} ->\n\t\tMRef = erlang:monitor(process, Ref),\n\t\tPid ! continue,\n\t\tMRef\n\tend,\n\n receive \n\t{'DOWN', MonitorReference, _Type, _Object, _Info} ->\n\t ok\n after 5000 ->\n\t ct:fail(control_process_not_stopped)\n end.\n\nclient_timeout(Pid) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n Pid ! {dbRef, Ref},\n receive \n\tcontinue ->\n\t ok\n end,\n exit(self(), timeout).\n\n\n%%-------------------------------------------------------------------------\nclient_dies_error() ->\n [{doc,\"Client dies with reason error.\"}].\nclient_dies_error(Config) when is_list(Config) ->\n Pid = spawn(?MODULE, client_error, [self()]),\n\n MonitorReference =\n\treceive \n\t {dbRef, Ref} ->\n\t\tMRef = erlang:monitor(process, Ref),\n\t\tPid ! continue,\n\t\tMRef\n\tend,\n\n receive \n\t{'DOWN', MonitorReference, _Type, _Object, _Info} ->\n\t ok\n after 5000 ->\n\t ct:fail(control_process_not_stopped)\n end.\n\nclient_error(Pid) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n Pid ! {dbRef, Ref},\n receive \n\tcontinue ->\n\t ok\n end,\n exit(self(), error).\n\n\n%%-------------------------------------------------------------------------\nconnect_timeout() ->\n [{doc,\"Test the timeout for the connect function.\"}].\nconnect_timeout(Config) when is_list(Config) ->\n {'EXIT',timeout} = (catch odbc:connect(?RDBMS:connection_string(),\n\t\t\t\t\t [{timeout, 0}] ++\n\t\t\t\t\t odbc_test_lib:platform_options())),\n %% Need to return ok here \"{'EXIT',timeout} return value\" will\n %% be interpreted as that the testcase has timed out.\n ok.\n\n%%-------------------------------------------------------------------------\nconnect_port_timeout() ->\n [{\"Test the timeout for the port program to connect back to the odbc \"\n \"application within the connect function.\"}].\nconnect_port_timeout(Config) when is_list(Config) ->\n %% Application environment var 'port_timeout' has been set to 0 by\n %% init_per_testcase\/2.\n {error,timeout} = odbc:connect(?RDBMS:connection_string(),\n odbc_test_lib:platform_options()).\n\n%%-------------------------------------------------------------------------\ntimeout() ->\n [{\"Test that timeouts don't cause unwanted behavior sush as receiving\"\n \" an anwser to a previously tiemed out query.\"}].\ntimeout(Config) when is_list(Config) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}]),\n Table = proplists:get_value(tableName, Config),\n\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\" ++ TransStr),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n ok = odbc:commit(Ref, commit),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(2,'baz')\"),\n\n Pid = spawn_link(?MODULE, update_table_timeout, [Table, 5000, self()]),\n\n receive \n\ttimout_occurred ->\n\t ok = odbc:commit(Ref, commit),\n\t Pid ! continue\n end,\n\n receive \n\taltered ->\n\t ok\n end,\n\n {selected, Fields, [{\"foobar\"}]} = \n\todbc:sql_query(Ref, \"SELECT DATA FROM \" ++ Table ++ \" WHERE ID = 1\"),\n [\"DATA\"] = odbc_test_lib:to_upper(Fields),\n\n ok = odbc:commit(Ref, commit),\n ok = odbc:disconnect(Ref).\n\nupdate_table_timeout(Table, TimeOut, Pid) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n UpdateQuery = \"UPDATE \" ++ Table ++ \" SET DATA = 'foobar' WHERE ID = 1\",\n\n case catch odbc:sql_query(Ref, UpdateQuery, TimeOut) of\n\t{'EXIT', timeout} ->\n\t Pid ! timout_occurred;\n\t{updated, 1} ->\n\t ct:fail(database_locker_failed)\n end,\n\n receive \n\tcontinue ->\n\t ok\n end,\n\n %% Make sure we receive the correct result and not the answer\n %% to the previous query.\n {selected, Fields, [{\"baz\"}]} = \n\todbc:sql_query(Ref, \"SELECT DATA FROM \" ++ Table ++ \" WHERE ID = 2\"),\n [\"DATA\"] = odbc_test_lib:to_upper(Fields),\n\n %% Do not check {updated, 1} as some drivers will return 0\n %% even though the update is done, which is checked by the test\n %% case when the altered message is recived.\n {updated, _} = odbc:sql_query(Ref, UpdateQuery, TimeOut),\n\n ok = odbc:commit(Ref, commit),\n\n Pid ! altered,\n\n ok = odbc:disconnect(Ref).\n%%-------------------------------------------------------------------------\nmany_timeouts() ->\n [{doc, \"Tests that many consecutive timeouts lead to that the connection \"\n \"is shutdown.\"}].\nmany_timeouts(Config) when is_list(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n\n Table = proplists:get_value(tableName, Config),\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\" ++ TransStr),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n ok = odbc:commit(Ref, commit),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n\n _Pid = spawn_link(?MODULE, update_table_many_timeouts, \n\t\t [Table, 5000, self()]),\n\n receive \n\tmany_timeouts_occurred ->\n\t ok\n end,\n\n ok = odbc:commit(Ref, commit),\n ok = odbc:disconnect(Ref).\n\n\nupdate_table_many_timeouts(Table, TimeOut, Pid) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n UpdateQuery = \"UPDATE \" ++ Table ++ \" SET DATA = 'foobar' WHERE ID = 1\",\n\n ok = loop_many_timouts(Ref, UpdateQuery, TimeOut),\n\n Pid ! many_timeouts_occurred, \n\n ok = odbc:disconnect(Ref).\n\n\nloop_many_timouts(Ref, UpdateQuery, TimeOut) ->\n case catch odbc:sql_query(Ref, UpdateQuery, TimeOut) of\n\t{'EXIT',timeout} ->\n\t loop_many_timouts(Ref, UpdateQuery, TimeOut);\n\t{updated, 1} ->\n\t ct:fail(database_locker_failed);\n\t{error, connection_closed} ->\n\t ok\n end.\n%%-------------------------------------------------------------------------\ntimeout_reset() ->\n [{doc, \"Check that the number of consecutive timouts is reset to 0 when \"\n \"a successful call to the database is made.\"}].\ntimeout_reset(Config) when is_list(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n Table = proplists:get_value(tableName, Config),\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\" ++ TransStr),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n ok = odbc:commit(Ref, commit),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(2,'baz')\"),\n\n\n Pid = spawn_link(?MODULE, update_table_timeout_reset, \n\t\t [Table, 5000, self()]),\n\n receive \n\tmany_timeouts_occurred ->\n\t ok\n end,\n\n ok = odbc:commit(Ref, commit),\n Pid ! continue,\n\n receive \n\taltered ->\n\t ok\n end,\n\n {selected, Fields, [{\"foobar\"}]} = \n\todbc:sql_query(Ref, \"SELECT DATA FROM \" ++ Table ++ \" WHERE ID = 1\"),\n [\"DATA\"] = odbc_test_lib:to_upper(Fields),\n\n ok = odbc:commit(Ref, commit),\n ok = odbc:disconnect(Ref).\n\nupdate_table_timeout_reset(Table, TimeOut, Pid) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n UpdateQuery = \"UPDATE \" ++ Table ++ \" SET DATA = 'foobar' WHERE ID = 1\",\n\n ok = loop_timout_reset(Ref, UpdateQuery, TimeOut, \n\t\t\t ?MAX_SEQ_TIMEOUTS-1),\n\n Pid ! many_timeouts_occurred,\n\n receive \n\tcontinue ->\n\t ok\n end,\n\n {selected, Fields, [{\"baz\"}]} =\n\todbc:sql_query(Ref, \"SELECT DATA FROM \" ++ Table ++ \" WHERE ID = 2\"),\n [\"DATA\"] = odbc_test_lib:to_upper(Fields),\n\n %% Do not check {updated, 1} as some drivers will return 0\n %% even though the update is done, which is checked by the test\n %% case when the altered message is recived.\n {updated, _} = odbc:sql_query(Ref, UpdateQuery, TimeOut),\n\n ok = odbc:commit(Ref, commit),\n\n Pid ! altered,\n\n ok = odbc:disconnect(Ref).\n\nloop_timout_reset(_, _, _, 0) ->\n ok;\n\nloop_timout_reset(Ref, UpdateQuery, TimeOut, NumTimeouts) ->\n case catch odbc:sql_query(Ref, UpdateQuery, TimeOut) of\n\t{'EXIT',timeout} ->\n\t loop_timout_reset(Ref, UpdateQuery, \n\t\t\t TimeOut, NumTimeouts - 1);\n\t{updated, 1} ->\n\t ct:fail(database_locker_failed);\n\t{error, connection_closed} ->\n\t ct:fail(connection_closed_premature)\n end.\n\n%%-------------------------------------------------------------------------\n\ndisconnect_on_timeout() ->\n [{doc,\"Check that disconnect after a time out works properly\"}].\ndisconnect_on_timeout(Config) when is_list(Config) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n Table = proplists:get_value(tableName, Config),\n TransStr = transaction_support_str(?RDBMS),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\" ++ TransStr),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n ok = odbc:commit(Ref, commit),\n\n {updated, 1} = \n\todbc:sql_query(Ref, \"UPDATE \" ++ Table ++\n\t\t \" SET DATA = 'foo' WHERE ID = 1\"),\n\n\n _Pid = spawn_link(?MODULE, update_table_disconnect_on_timeout,\n\t\t [Table, 5000, self()]),\n receive \n\tok ->\n\t ok = odbc:commit(Ref, commit);\n\tnok ->\n\t ct:fail(database_locker_failed)\n end.\n\nupdate_table_disconnect_on_timeout(Table, TimeOut, Pid) ->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{auto_commit, off}] ++ odbc_test_lib:platform_options()),\n UpdateQuery = \"UPDATE \" ++ Table ++ \" SET DATA = 'foobar' WHERE ID = 1\",\n\n case catch odbc:sql_query(Ref, UpdateQuery, TimeOut) of\n\t{'EXIT', timeout} ->\n\t ok = odbc:disconnect(Ref),\n\t Pid ! ok;\n\t{updated, 1} ->\n\t Pid ! nok\n end.\n\n%%-------------------------------------------------------------------------\nconnection_closed() ->\n [{doc, \"Checks that you get an appropriate error message if you try to\"\n \" use a connection that has been closed\"}].\nconnection_closed(Config) when is_list(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n\n Table = proplists:get_value(tableName, Config), \n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA char(10), PRIMARY KEY(ID))\"),\n\n ok = odbc:disconnect(Ref),\n\n {error, connection_closed} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n {error, connection_closed} = \n\todbc:select_count(Ref, \"SELECT * FROM \" ++ Table),\n {error, connection_closed} = odbc:first(Ref),\n {error, connection_closed} = odbc:last(Ref),\n {error, connection_closed} = odbc:next(Ref),\n {error, connection_closed} = odbc:prev(Ref),\n {error, connection_closed} = odbc:select(Ref, next, 3),\n {error, connection_closed} = odbc:commit(Ref, commit).\n\n%%-------------------------------------------------------------------------\ndisable_scrollable_cursors() ->\n [{doc,\"Test disabling of scrollable cursors.\"}].\ndisable_scrollable_cursors(Config) when is_list(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{scrollable_cursors, off}]),\n\n Table = proplists:get_value(tableName, Config),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\"),\n\n {updated, _} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n {ok, _} = odbc:select_count(Ref, \"SELECT ID FROM \" ++ Table),\n\n NextResult = ?RDBMS:selected_ID(1, next),\n\n ct:pal(\"Expected: ~p~n\", [NextResult]),\n\n Result = odbc:next(Ref),\n ct:pal(\"Got: ~p~n\", [Result]),\n NextResult = Result,\n\n {error, scrollable_cursors_disabled} = odbc:first(Ref),\n {error, scrollable_cursors_disabled} = odbc:last(Ref),\n {error, scrollable_cursors_disabled} = odbc:prev(Ref),\n {error, scrollable_cursors_disabled} = \n\todbc:select(Ref, {relative, 2}, 5),\n {error, scrollable_cursors_disabled} =\n\todbc:select(Ref, {absolute, 2}, 5),\n\n {selected, _ColNames,[]} = odbc:select(Ref, next, 1).\n\n%%-------------------------------------------------------------------------\nreturn_rows_as_lists()->\n [{doc,\"Test the option that a row may be returned as a list instead \" \n \"of a tuple. Too be somewhat backward compatible.\"}].\nreturn_rows_as_lists(Config) when is_list(Config) ->\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t [{tuple_row, off}] ++ odbc_test_lib:platform_options()),\n\n Table = proplists:get_value(tableName, Config),\n\n {updated, _} = \n\todbc:sql_query(Ref, \n\t\t \"CREATE TABLE \" ++ Table ++\n\t\t \" (ID integer, DATA varchar(10), PRIMARY KEY(ID))\"),\n\n {updated, _} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(1,'bar')\"),\n\n {updated, _} = \n\todbc:sql_query(Ref, \"INSERT INTO \" ++ Table ++ \" VALUES(2,'foo')\"),\n\n ListRows = ?RDBMS:selected_list_rows(),\n ListRows = \n\todbc:sql_query(Ref, \"SELECT * FROM \" ++ Table),\n\n {ok, _} = odbc:select_count(Ref, \"SELECT * FROM \" ++ Table),\n\n case proplists:get_value(scrollable_cursors, odbc_test_lib:platform_options()) of\n\toff ->\n\t Next = ?RDBMS:next_list_rows(),\n\t Next = odbc:next(Ref);\n\t_ ->\n\t First = ?RDBMS:first_list_rows(),\n\t Last = ?RDBMS:last_list_rows(),\n\t Prev = ?RDBMS:prev_list_rows(),\n\t Next = ?RDBMS:next_list_rows(),\n\n\t Last = odbc:last(Ref),\n\t Prev = odbc:prev(Ref),\n\t First = odbc:first(Ref),\n\t Next = odbc:next(Ref)\n end.\n\n%%-------------------------------------------------------------------------\n\napi_missuse()->\n [{doc,\"Test that behaviour of the control process if the api is abused\"}].\napi_missuse(Config) when is_list(Config)->\n\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n %% Serious programming fault, connetion will be shut down \n gen_server:call(Ref, {self(), foobar, 10}, infinity),\n ct:sleep(10),\n undefined = process_info(Ref, status),\n\n {ok, Ref2} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t odbc_test_lib:platform_options()),\n %% Serious programming fault, connetion will be shut down \n gen_server:cast(Ref2, {self(), foobar, 10}),\n ct:sleep(10),\n undefined = process_info(Ref2, status),\n\n {ok, Ref3} = odbc:connect(?RDBMS:connection_string(),\n\t\t\t odbc_test_lib:platform_options()),\n %% Could be an innocent misstake the connection lives. \n Ref3 ! foobar, \n ct:sleep(10),\n {status, _} = process_info(Ref3, status).\n\ntransaction_support_str(mysql) ->\n \"ENGINE = InnoDB\";\ntransaction_support_str(_) ->\n \"\".\n\n\n%%-------------------------------------------------------------------------\nextended_errors()->\n [{doc, \n \"Test the extended errors connection option: When off; the old behaviour of just an error \"\n \"string is returned on error. When on, the error string is replaced by a 3 element tuple \"\n \"that also exposes underlying ODBC provider error codes.\"}].\nextended_errors(Config) when is_list(Config)->\n Table = proplists:get_value(tableName, Config),\n {ok, Ref} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options()),\n {updated, _} = odbc:sql_query(Ref, \"create table \" ++ Table ++\" ( id integer, data varchar(10))\"),\n\n % Error case WITHOUT extended errors on...\n case odbc:sql_query(Ref, \"create table \" ++ Table ++\" ( id integer, data varchar(10))\") of\n {error, ErrorString} when is_list(ErrorString) -> ok\n end,\n\n % Now the test case with extended errors on - This should return a tuple, not a list\/string now.\n % The first element is a string that is the ODBC error string; the 2nd element is a native integer error\n % code passed from the underlying provider driver. The last is the familiar old error string.\n % We can't check the actual error code; as each different underlying provider will return\n % a different value - So we just check the return types at least.\n {ok, RefExtended} = odbc:connect(?RDBMS:connection_string(), odbc_test_lib:platform_options() ++ [{extended_errors, on}]),\n case odbc:sql_query(RefExtended, \"create table \" ++ Table ++\" ( id integer, data varchar(10))\") of\n {error, {ODBCCodeString, NativeCodeNum, ShortErrorString}} when is_list(ODBCCodeString), is_number(NativeCodeNum), is_list(ShortErrorString) -> ok\n end,\n\n ok = odbc:disconnect(Ref),\n ok = odbc:disconnect(RefExtended).\n\n\nis_odbcserver(Name) ->\n case re:run(Name, \"odbcserver\") of\n\t{match, _} ->\n\t true;\n\t_ ->\n\t false\n end.\n\n","avg_line_length":33.0476718404,"max_line_length":154,"alphanum_fraction":0.5936126673} +{"size":7673,"ext":"erl","lang":"Erlang","max_stars_count":7.0,"content":"%%%-------------------------------------------------------------------\n%%% @author Bartosz Walkowicz\n%%% @copyright (C) 2021 ACK CYFRONET AGH\n%%% This software is released under the MIT license\n%%% cited in 'LICENSE.txt'.\n%%% @end\n%%%-------------------------------------------------------------------\n%%% @doc\n%%% Module responsible for operating on task execution argument spec which is\n%%% 'atm_lambda_argument_spec' and 'atm_task_schema_argument_mapper' merged into\n%%% one record. It is done for performance reasons so as to not reference\n%%% several more documents (workflow schema and lambda doc) when executing\n%%% task for each item.\n%%% @end\n%%%-------------------------------------------------------------------\n-module(atm_task_execution_argument_spec).\n-author(\"Bartosz Walkowicz\").\n\n-behaviour(persistent_record).\n\n-include(\"modules\/automation\/atm_execution.hrl\").\n\n%% API\n-export([build\/2, get_name\/1, construct_arg\/2]).\n\n%% persistent_record callbacks\n-export([version\/0, db_encode\/2, db_decode\/2]).\n\n\n-record(atm_task_execution_argument_spec, {\n name :: automation:name(),\n value_builder :: atm_task_argument_value_builder:record(),\n data_spec :: atm_data_spec:record(),\n is_batch :: boolean()\n}).\n-type record() :: #atm_task_execution_argument_spec{}.\n\n-export_type([record\/0]).\n\n\n%%%===================================================================\n%%% API\n%%%===================================================================\n\n\n-spec build(\n atm_lambda_argument_spec:record(),\n undefined | atm_task_schema_argument_mapper:record()\n) ->\n record().\nbuild(#atm_lambda_argument_spec{\n name = Name,\n data_spec = AtmDataSpec,\n is_batch = IsBatch,\n default_value = DefaultValue\n}, undefined) ->\n #atm_task_execution_argument_spec{\n name = Name,\n value_builder = #atm_task_argument_value_builder{type = const, recipe = DefaultValue},\n data_spec = AtmDataSpec,\n is_batch = IsBatch\n };\n\nbuild(#atm_lambda_argument_spec{\n name = Name,\n data_spec = AtmDataSpec,\n is_batch = IsBatch\n}, #atm_task_schema_argument_mapper{value_builder = ValueBuilder}) ->\n #atm_task_execution_argument_spec{\n name = Name,\n value_builder = ValueBuilder,\n data_spec = AtmDataSpec,\n is_batch = IsBatch\n }.\n\n\n-spec get_name(record()) -> automation:name().\nget_name(#atm_task_execution_argument_spec{name = ArgName}) ->\n ArgName.\n\n\n-spec construct_arg(atm_job_ctx:record(), record()) ->\n json_utils:json_term() | no_return().\nconstruct_arg(AtmJobCtx, AtmTaskExecutionArgSpec = #atm_task_execution_argument_spec{\n value_builder = ArgValueBuilder\n}) ->\n ArgValue = build_value(AtmJobCtx, ArgValueBuilder),\n validate_value(AtmJobCtx, ArgValue, AtmTaskExecutionArgSpec),\n\n ArgValue.\n\n\n%%%===================================================================\n%%% persistent_record callbacks\n%%%===================================================================\n\n\n-spec version() -> persistent_record:record_version().\nversion() ->\n 1.\n\n\n-spec db_encode(record(), persistent_record:nested_record_encoder()) ->\n json_utils:json_term().\ndb_encode(#atm_task_execution_argument_spec{\n name = Name,\n value_builder = ValueBuilder,\n data_spec = AtmDataSpec,\n is_batch = IsBatch\n}, NestedRecordEncoder) ->\n #{\n <<\"name\">> => Name,\n <<\"valueBuilder\">> => NestedRecordEncoder(ValueBuilder, atm_task_argument_value_builder),\n <<\"dataSpec\">> => NestedRecordEncoder(AtmDataSpec, atm_data_spec),\n <<\"isBatch\">> => IsBatch\n }.\n\n\n-spec db_decode(json_utils:json_term(), persistent_record:nested_record_decoder()) ->\n record().\ndb_decode(#{\n <<\"name\">> := Name,\n <<\"valueBuilder\">> := ValueBuilderJson,\n <<\"dataSpec\">> := AtmDataSpecJson,\n <<\"isBatch\">> := IsBatch\n}, NestedRecordDecoder) ->\n #atm_task_execution_argument_spec{\n name = Name,\n value_builder = NestedRecordDecoder(ValueBuilderJson, atm_task_argument_value_builder),\n data_spec = NestedRecordDecoder(AtmDataSpecJson, atm_data_spec),\n is_batch = IsBatch\n }.\n\n\n%%%===================================================================\n%%% Internal functions\n%%%===================================================================\n\n\n%% @private\n-spec build_value(atm_job_ctx:record(), atm_task_argument_value_builder:record()) ->\n json_utils:json_term() | no_return().\nbuild_value(_AtmJobCtx, #atm_task_argument_value_builder{\n type = const,\n recipe = ConstValue\n}) ->\n ConstValue;\n\nbuild_value(AtmJobCtx, #atm_task_argument_value_builder{\n type = iterated_item,\n recipe = undefined\n}) ->\n atm_job_ctx:get_item(AtmJobCtx);\n\nbuild_value(AtmJobCtx, #atm_task_argument_value_builder{\n type = iterated_item,\n recipe = Query\n}) ->\n Item = atm_job_ctx:get_item(AtmJobCtx),\n\n % TODO VFS-7660 fix query in case of array indices\n case json_utils:query(Item, Query) of\n {ok, Value} -> Value;\n error -> throw(?ERROR_ATM_TASK_ARG_MAPPER_ITERATED_ITEM_QUERY_FAILED(Item, Query))\n end;\n\nbuild_value(AtmJobCtx, #atm_task_argument_value_builder{\n type = onedatafs_credentials\n}) ->\n #{\n <<\"host\">> => oneprovider:get_domain(),\n <<\"accessToken\">> => atm_job_ctx:get_access_token(AtmJobCtx)\n };\n\nbuild_value(AtmJobCtx, #atm_task_argument_value_builder{\n type = single_value_store_content,\n recipe = AtmSingleValueStoreSchemaId\n}) ->\n AtmSingleValueStoreId = atm_workflow_execution_ctx:get_workflow_store_id(\n AtmSingleValueStoreSchemaId,\n atm_job_ctx:get_workflow_execution_ctx(AtmJobCtx)\n ),\n {ok, AtmStore} = atm_store_api:get(AtmSingleValueStoreId),\n\n case atm_store_container:get_store_type(AtmStore#atm_store.container) of\n single_value ->\n ok;\n _ ->\n throw(?ERROR_ATM_STORE_TYPE_DISALLOWED(AtmSingleValueStoreSchemaId, [single_value]))\n end,\n\n AtmWorkflowExecutionAuth = atm_job_ctx:get_workflow_execution_auth(AtmJobCtx),\n BrowseOpts = #{offset => 0, limit => 1},\n\n case atm_store_api:browse_content(AtmWorkflowExecutionAuth, BrowseOpts, AtmStore) of\n {[], true} ->\n throw(?ERROR_ATM_STORE_EMPTY(AtmSingleValueStoreSchemaId));\n {[{_Index, {error, _} = Error}], true} ->\n throw(Error);\n {[{_Index, {ok, Item}}], true} ->\n Item\n end;\n\nbuild_value(_AtmJobCtx, #atm_task_argument_value_builder{\n type = ValueBuilderType\n}) ->\n % TODO VFS-7660 handle rest of atm_task_argument_value_builder:type()\n throw(?ERROR_ATM_TASK_ARG_MAPPER_UNSUPPORTED_VALUE_BUILDER(ValueBuilderType, [\n const, iterated_item, onedatafs_credentials, single_value_store_content\n ])).\n\n\n%% @private\n-spec validate_value(\n atm_job_ctx:record(),\n json_utils:json_term() | [json_utils:json_term()],\n record()\n) ->\n ok | no_return().\nvalidate_value(AtmJobCtx, ArgValue, #atm_task_execution_argument_spec{\n data_spec = AtmDataSpec,\n is_batch = false\n}) ->\n AtmWorkflowExecutionAuth = atm_job_ctx:get_workflow_execution_auth(AtmJobCtx),\n atm_value:validate(AtmWorkflowExecutionAuth, ArgValue, AtmDataSpec);\n\nvalidate_value(AtmJobCtx, ArgsBatch, #atm_task_execution_argument_spec{\n data_spec = AtmDataSpec,\n is_batch = true\n}) when is_list(ArgsBatch) ->\n AtmWorkflowExecutionAuth = atm_job_ctx:get_workflow_execution_auth(AtmJobCtx),\n\n lists:foreach(fun(ArgValue) ->\n atm_value:validate(AtmWorkflowExecutionAuth, ArgValue, AtmDataSpec)\n end, ArgsBatch);\n\nvalidate_value(_AtmWorkflowExecutionAuth, _ArgsBatch, _AtmTaskExecutionArgSpec) ->\n throw(?ERROR_BAD_DATA(<<\"value\">>, <<\"not a batch\">>)).\n","avg_line_length":32.1046025105,"max_line_length":97,"alphanum_fraction":0.6513749511} +{"size":6045,"ext":"erl","lang":"Erlang","max_stars_count":8238.0,"content":"%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 1996-2016. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n\n%%\n\n%%-behaviour(mnesia_backup).\n%0\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\n%% This module contains one implementation of callback functions\n%% used by Mnesia at backup and restore. The user may however\n%% write an own module the same interface as mnesia_backup and\n%% configure Mnesia so the alternate module performs the actual\n%% accesses to the backup media. This means that the user may put\n%% the backup on medias that Mnesia does not know about, possibly\n%% on hosts where Erlang is not running.\n%%\n%% The OpaqueData argument is never interpreted by other parts of\n%% Mnesia. It is the property of this module. Alternate implementations\n%% of this module may have different interpretations of OpaqueData.\n%% The OpaqueData argument given to open_write\/1 and open_read\/1\n%% are forwarded directly from the user.\n%%\n%% All functions must return {ok, NewOpaqueData} or {error, Reason}.\n%%\n%% The NewOpaqueData arguments returned by backup callback functions will\n%% be given as input when the next backup callback function is invoked.\n%% If any return value does not match {ok, _} the backup will be aborted.\n%%\n%% The NewOpaqueData arguments returned by restore callback functions will\n%% be given as input when the next restore callback function is invoked\n%% If any return value does not match {ok, _} the restore will be aborted.\n%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n-module(mnesia_backup).\n\n-include_lib(\"kernel\/include\/file.hrl\").\n\n-export([\n\t %% Write access\n open_write\/1,\n\t write\/2,\n\t commit_write\/1,\n\t abort_write\/1,\n\n\t %% Read access\n open_read\/1,\n\t read\/1,\n\t close_read\/1\n ]).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Backup callback interface\n-record(backup, {tmp_file, file, file_desc}).\n\n%% Opens backup media for write\n%%\n%% Returns {ok, OpaqueData} or {error, Reason}\nopen_write(OpaqueData) ->\n File = OpaqueData,\n Tmp = lists:concat([File,\".BUPTMP\"]),\n file:delete(Tmp),\n file:delete(File),\n case disk_log:open([{name, make_ref()},\n\t\t\t{file, Tmp},\n\t\t\t{repair, false},\n\t\t\t{linkto, self()}]) of\n\t{ok, Fd} ->\n\t {ok, #backup{tmp_file = Tmp, file = File, file_desc = Fd}};\n\t{error, Reason} ->\n\t {error, Reason}\n end.\n\n%% Writes BackupItems to the backup media\n%%\n%% Returns {ok, OpaqueData} or {error, Reason}\nwrite(OpaqueData, BackupItems) ->\n B = OpaqueData,\n case disk_log:log_terms(B#backup.file_desc, BackupItems) of\n ok ->\n {ok, B};\n {error, Reason} ->\n abort_write(B),\n {error, Reason}\n end.\n\n%% Closes the backup media after a successful backup\n%%\n%% Returns {ok, ReturnValueToUser} or {error, Reason}\ncommit_write(OpaqueData) ->\n B = OpaqueData,\n case disk_log:sync(B#backup.file_desc) of\n ok ->\n case disk_log:close(B#backup.file_desc) of\n ok ->\n\t\t case file:rename(B#backup.tmp_file, B#backup.file) of\n\t\t ok ->\n\t\t\t {ok, B#backup.file};\n\t\t {error, Reason} ->\n\t\t\t {error, Reason}\n\t\t end;\n {error, Reason} ->\n\t\t {error, Reason}\n end;\n {error, Reason} ->\n {error, Reason}\n end.\n\n%% Closes the backup media after an interrupted backup\n%%\n%% Returns {ok, ReturnValueToUser} or {error, Reason}\nabort_write(BackupRef) ->\n Res = disk_log:close(BackupRef#backup.file_desc),\n file:delete(BackupRef#backup.tmp_file),\n case Res of\n ok ->\n {ok, BackupRef#backup.file};\n {error, Reason} ->\n {error, Reason}\n end.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Restore callback interface\n\n-record(restore, {file, file_desc, cont}).\n\n%% Opens backup media for read\n%%\n%% Returns {ok, OpaqueData} or {error, Reason}\nopen_read(OpaqueData) ->\n File = OpaqueData,\n case file:read_file_info(File) of\n\t{error, Reason} ->\n\t {error, Reason};\n\t_FileInfo -> %% file exists\n\t case disk_log:open([{file, File},\n\t\t\t\t{name, make_ref()},\n\t\t\t\t{repair, false},\n\t\t\t\t{mode, read_only},\n\t\t\t\t{linkto, self()}]) of\n\t\t{ok, Fd} ->\n\t\t {ok, #restore{file = File, file_desc = Fd, cont = start}};\n\t\t{repaired, Fd, _, {badbytes, 0}} ->\n\t\t {ok, #restore{file = File, file_desc = Fd, cont = start}};\n\t\t{repaired, Fd, _, _} ->\n\t\t {ok, #restore{file = File, file_desc = Fd, cont = start}};\n\t\t{error, Reason} ->\n\t\t {error, Reason}\n\t end\n end.\n\n%% Reads BackupItems from the backup media\n%%\n%% Returns {ok, OpaqueData, BackupItems} or {error, Reason}\n%%\n%% BackupItems == [] is interpreted as eof\nread(OpaqueData) ->\n R = OpaqueData,\n Fd = R#restore.file_desc,\n case disk_log:chunk(Fd, R#restore.cont) of\n {error, Reason} ->\n {error, {\"Possibly truncated\", Reason}};\n eof ->\n {ok, R, []};\n {Cont, []} ->\n read(R#restore{cont = Cont});\n {Cont, BackupItems, _BadBytes} ->\n {ok, R#restore{cont = Cont}, BackupItems};\n {Cont, BackupItems} ->\n {ok, R#restore{cont = Cont}, BackupItems}\n end.\n\n%% Closes the backup media after restore\n%%\n%% Returns {ok, ReturnValueToUser} or {error, Reason}\nclose_read(OpaqueData) ->\n R = OpaqueData,\n case disk_log:close(R#restore.file_desc) of\n ok -> {ok, R#restore.file};\n {error, Reason} -> {error, Reason}\n end.\n%0\n\n","avg_line_length":29.7783251232,"max_line_length":75,"alphanum_fraction":0.6102564103} +{"size":1139,"ext":"erl","lang":"Erlang","max_stars_count":12.0,"content":"-module(ct_cardstore).\n\n-export([bank_card\/3]).\n\n%%\n\n-include_lib(\"cds_proto\/include\/cds_proto_storage_thrift.hrl\").\n\n-spec bank_card(binary(), {1..12, 2000..9999}, ct_helper:config()) ->\n #{\n token := binary(),\n bin => binary(),\n masked_pan => binary(),\n exp_date => {integer(), integer()},\n cardholder_name => binary()\n }.\nbank_card(PAN, ExpDate, C) ->\n CardData = #cds_PutCardData{\n pan = PAN\n },\n Client = ff_woody_client:new(maps:get('cds', ct_helper:cfg(services, C))),\n WoodyCtx = ct_helper:get_woody_ctx(C),\n Request = {{cds_proto_storage_thrift, 'Storage'}, 'PutCard', {CardData}},\n case woody_client:call(Request, Client, WoodyCtx) of\n {ok, #cds_PutCardResult{\n bank_card = #cds_BankCard{\n token = Token,\n bin = BIN,\n last_digits = Masked\n }\n }} ->\n #{\n token => Token,\n bin => BIN,\n masked_pan => Masked,\n exp_date => ExpDate,\n cardholder_name => <<\"ct_cardholder_name\">>\n }\n end.\n","avg_line_length":28.475,"max_line_length":78,"alphanum_fraction":0.5258999122} +{"size":3010,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"-module(gcm_api).\n-export([push\/3]).\n\n-define(BASEURL, \"https:\/\/android.googleapis.com\/gcm\/send\").\n\n-type header() :: {string(), string()}.\n-type headers() :: [header(),...].\n-type regids() :: [binary(),...].\n-type message() :: [tuple(),...].\n-type result() :: {number(), non_neg_integer(), non_neg_integer(), non_neg_integer(), [any()]}.\n\n-spec push(regids(),message(),string()) -> {'error',any()} | {'noreply','unknown'} | {'ok',result()}.\npush(RegIds, Message, Key) ->\n Request = jsx:encode([{<<\"registration_ids\">>, RegIds}|Message]),\n ApiKey = string:concat(\"key=\", Key),\n\n try httpc:request(post, {?BASEURL, [{\"Authorization\", ApiKey}], \"application\/json\", Request}, [], []) of\n {ok, {{_, 200, _}, _Headers, Body}} ->\n Json = jsx:decode(response_to_binary(Body)),\n error_logger:info_msg(\"Result was: ~p~n\", [Json]),\n {ok, result_from(Json)};\n {ok, {{_, 400, _}, _, _}} ->\n\t error_logger:error_msg(\"Error in request. Reason was: json_error~n\", []),\n {error, json_error};\n {ok, {{_, 401, _}, _, _}} ->\n\t error_logger:error_msg(\"Error in request. Reason was: authorization error~n\", []),\n {error, auth_error};\n {ok, {{_, Code, _}, Headers, _}} when Code >= 500 andalso Code =< 599 ->\n\t RetryTime = retry_after_from(Headers),\n\t error_logger:error_msg(\"Error in request. Reason was: retry. Will retry in: ~p~n\", [RetryTime]),\n {error, {retry, RetryTime}};\n {ok, {{_StatusLine, _, _}, _, _Body}} ->\n\t error_logger:error_msg(\"Error in request. Reason was: timeout~n\", []),\n {error, timeout};\n {error, Reason} ->\n\t error_logger:error_msg(\"Error in request. Reason was: ~p~n\", [Reason]),\n {error, Reason};\n OtherError ->\n\t error_logger:error_msg(\"Error in request. Reason was: ~p~n\", [OtherError]),\n {noreply, unknown}\n catch\n Exception ->\n\t error_logger:error_msg(\"Error in request. Exception ~p while calling URL: ~p~n\", [Exception, ?BASEURL]),\n {error, Exception}\n end.\n\n-spec response_to_binary(binary() | list()) -> binary().\nresponse_to_binary(Json) when is_binary(Json) ->\n Json;\n\nresponse_to_binary(Json) when is_list(Json) ->\n list_to_binary(Json).\n\n-spec result_from([{binary(),any()}]) -> result().\nresult_from(Json) ->\n {\n proplists:get_value(<<\"multicast_id\">>, Json),\n proplists:get_value(<<\"success\">>, Json),\n proplists:get_value(<<\"failure\">>, Json),\n proplists:get_value(<<\"canonical_ids\">>, Json),\n proplists:get_value(<<\"results\">>, Json)\n }.\n\n-spec retry_after_from(headers()) -> 'no_retry' | non_neg_integer().\nretry_after_from(Headers) ->\n case proplists:get_value(\"retry-after\", Headers) of\n\tundefined ->\n\t no_retry;\n\tRetryTime ->\n\t case string:to_integer(RetryTime) of\n\t\t{Time, _} when is_integer(Time) ->\n\t\t Time;\n\t\t{error, no_integer} ->\n\t\t Date = qdate:to_unixtime(RetryTime),\n\t\t Date - qdate:unixtime()\n\t end\n end.\n","avg_line_length":38.5897435897,"max_line_length":109,"alphanum_fraction":0.5993355482} +{"size":3782,"ext":"erl","lang":"Erlang","max_stars_count":922.0,"content":"%%-------------------------------------------------------------------\n%% @author\n%% ChicagoBoss Team and contributors, see AUTHORS file in root directory\n%% @end\n%% @copyright\n%% This file is part of ChicagoBoss project.\n%% See AUTHORS file in root directory\n%% for license information, see LICENSE file in root directory\n%% @end\n%% @doc\n%%-------------------------------------------------------------------\n\n-module(boss_load_test).\n-include_lib(\"proper\/include\/proper.hrl\").\n-include_lib(\"eunit\/include\/eunit.hrl\").\n\n\n\nload_view_inner_test() ->\n Inner = boss_load:load_views_inner(test, \".\", self()),\n ?assert(is_function(Inner, 2)),\n [DtlModule] = Inner(\"..\/test\/good.dtl\", []),\n ?assertEqual(test_test_good_dtl, DtlModule),\n Exports = DtlModule:module_info(exports),\n ?assertEqual([0,1,2], proplists:get_all_values(render, Exports)).\n\nload_view_inner_bad_test() ->\n Inner = boss_load:load_views_inner(test, \".\", self()),\n ?assert(is_function(Inner, 2)),\n ?assertEqual([[{\"..\/test\/bad.dtl\",[{{1,11},erlydtl_scanner,{illegal_char,125}}]}]],Inner(\"..\/test\/bad.dtl\", [])).\n\n\nload_view_inner_no_file_test() ->\n Inner = boss_load:load_views_inner(test, \".\", self()),\n ?assert(is_function(Inner, 2)),\n ?assertEqual([test], Inner(\"..\/test\/no_file.dtl\", [test])).\n\n\n\nmodule_is_loaded_test() ->\n ?assert(boss_load:module_is_loaded('boss_load')),\n ?assertNot(boss_load:module_is_loaded('boss_load1')),\n ?assert(proper:check_spec({boss_load, module_is_loaded, 1},\n\n [{to_file, user}])),\n ok.\n\n\nmake_computed_vsn_test() ->\n ?assertEqual(\"ok\", boss_load:make_computed_vsn(\"echo ok\")),\n ?assert(proper:quickcheck(prop_make_computed_vsn(),\n [{to_file, user}])),\n ok.\n\n\nprop_make_computed_vsn() ->\n ?FORALL(X,\n any(),\n X =:= boss_load:make_computed_vsn({unknown, X})).\n\n\nmake_all_modules_test() ->\n ?assertEqual([], boss_load:make_all_modules(test, \"\/tmp\", [])),\n ?assert(proper:quickcheck(prop_make_all_modules(),\n [{to_file, user}])),\n ?assert(proper:quickcheck(prop_make_all_modules_error(),\n [{to_file, user}])),\n\n ok.\n\n-type op_key() :: test_modules|lib_modules|websocket_modules|mail_modules|controller_modules|\n model_modules| view_lib_tags_modules|view_lib_helper_modules|view_modules.\n-type op_list_el():: {op_key(), [atom()]}.\nprop_make_all_modules()->\n ?FORALL(\n OpKeys,\n [op_list_el()],\n begin\n Application = test,\n OutDir = \"\/tmp\",\n Ops = [{Op, fun(IApp,IOutDir) ->\n IApp = Application,\n IOutDir = OutDir,\n {ok, Modules}\n end}|| {Op, Modules} <- OpKeys],\n\n Result = boss_load:make_all_modules(Application, OutDir, Ops),\n\n Result -- OpKeys =:= []\n end).\n\nprop_make_all_modules_error()->\n ?FORALL(\n OpKeys,\n [op_list_el()],\n begin\n Application = test,\n OutDir = \"\/tmp\",\n Ops = [{Op, fun(IApp,IOutDir) ->\n IApp = Application,\n IOutDir = OutDir,\n {error, \"test\"}\n end}|| {Op, _Modules} <- OpKeys],\n\n Result = boss_load:make_all_modules(Application, OutDir, Ops),\n [] =:= lists:concat([Value|| {_, Value} <-Result])\n\n end).\n\nmake_ops_list_test() ->\n OpsList = boss_load:make_ops_list(self()),\n ?assert(lists:all(fun({Op, Fun}) ->\n is_atom(Op) andalso is_function(Fun,2)\n end, OpsList)),\n ok.\n","avg_line_length":32.6034482759,"max_line_length":117,"alphanum_fraction":0.5452141724} +{"size":2114,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%--------------------------------------------------------------------\n%% Copyright (c) 2021-2022 EMQ Technologies Co., Ltd. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%--------------------------------------------------------------------\n\n%% Test database consistency with random transactions\n-module(mria_proper_suite).\n\n-compile(export_all).\n-compile(nowarn_export_all).\n\n-include_lib(\"snabbkaffe\/include\/ct_boilerplate.hrl\").\n-include(\"mria_proper_utils.hrl\").\n\n%%================================================================================\n%% Testcases\n%%================================================================================\n\nt_import_transactions(Config0) when is_list(Config0) ->\n Config = [{proper, #{max_size => 300,\n numtests => 100,\n timeout => 100000\n }} | Config0],\n ClusterConfig = [core, replicant],\n ?run_prop(Config, mria_proper_utils:prop(ClusterConfig, ?MODULE)).\n\n%%================================================================================\n%% Proper FSM definition\n%%================================================================================\n\n%% Initial model value at system start. Should be deterministic.\ninitial_state() ->\n #s{cores = [n1], replicants = [n2]}.\n\ncommand(State) -> mria_proper_utils:command(State).\nprecondition(State, Op) -> mria_proper_utils:precondition(State, Op).\npostcondition(State, Op, Res) -> mria_proper_utils:postcondition(State, Op, Res).\nnext_state(State, Res, Op) -> mria_proper_utils:next_state(State, Res, Op).\n","avg_line_length":42.28,"max_line_length":82,"alphanum_fraction":0.5487228004} +{"size":2917,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%-------------------------------------------------------------------\n%%% @author Alpha Umaru Shaw \n%%% @doc\n%%%\n%%% @end\n%%% Company: Skulup Ltd\n%%% Copyright: (C) 2020\n%%%-------------------------------------------------------------------\n-module(ew_assertions).\n-author(\"Alpha Umaru Shaw\").\n\n-include(\"erlwater.hrl\").\n\n%% API\n-export([assert\/3, is_boolean\/1, is_number\/1, is_integer\/1, is_string\/1, is_proplist\/1, is_positive_int\/1, is_non_negative_int\/1]).\n\n-define(BOOLEAN, \"boolean\").\n-define(NUMBER, \"number\").\n-define(INTEGER, \"integer\").\n-define(STRING, \"binary or string\").\n-define(POS_INTEGER, \"positive integer\").\n-define(NON_NEG_INTEGER, \"non-negative integer\").\n-define(PROPLIST, \"proplist\").\n\nassert(Expression, Arg, Error) ->\n if Expression ->\n Arg;\n true ->\n erlang:error(Error, [Arg])\n end.\n\nis_boolean({Key, Value} = Arg) ->\n assert_type(Key, Arg, Value, fun() -> erlang:is_boolean(Value) end, ?BOOLEAN);\n\nis_boolean(Value) ->\n ?MODULE:is_boolean({Value, Value}),\n Value.\n\nis_number({Key, Value} = Arg) ->\n assert_type(Key, Arg, Value, fun() -> erlang:is_number(Value) end, ?NUMBER);\n\nis_number(Value) ->\n ?MODULE:is_number({Value, Value}),\n Value.\n\n\nis_integer({Key, Value} = Arg) ->\n assert_type(Key, Arg, Value, fun() -> erlang:is_integer(Value) end, ?INTEGER);\n\nis_integer(Value) ->\n ?MODULE:is_integer({Value, Value}),\n Value.\n\nis_positive_int({Key, Value} = Arg) ->\n assert_type( Key, Arg, Value, fun() ->\n erlang:is_integer(Value) andalso Value > 0 end, ?POS_INTEGER);\n\nis_positive_int(Value) ->\n ?MODULE:is_positive_int({Value, Value}),\n Value.\n\nis_non_negative_int({Key, Value} = Arg) ->\n assert_type( Key, Arg, Value, fun() ->\n erlang:is_integer(Value) andalso Value >= 0 end, ?NON_NEG_INTEGER);\n\nis_non_negative_int(Value) ->\n ?MODULE:is_non_negative_int({Value, Value}),\n Value.\n\nis_string({Key, Value} = Arg) ->\n assert_type( Key, Arg, Value, fun() ->\n is_binary(Value) or io_lib:printable_list(Value) end, ?STRING);\n\nis_string(Value) ->\n ?MODULE:is_string({Value, Value}),\n Value.\n\nis_proplist({Key, Value} = Arg) ->\n assert_type(Key, Arg, Value,\n fun() -> is_a_prop_list(Value) end, ?PROPLIST);\n\nis_proplist(Value) ->\n ?MODULE:is_proplist({Value, Value}),\n Value.\n\n\nassert_type(Prop, Arg, Given, Checker, Type) ->\n case Checker() of\n true ->\n Arg;\n _ ->\n bad_value(Prop, Given, Type, Arg)\n end.\n\nis_a_prop_list([]) ->\n true;\nis_a_prop_list(Ls) when is_list(Ls) ->\n lists:all(\n fun({_, _}) ->\n true;\n (_) ->\n false\n end, Ls);\nis_a_prop_list(_) -> false.\n\nbad_value(Prop, Given, Msg, Args) ->\n Msg2 = lists:flatten(io_lib:format(\"value of property: `~p` must be ~s. Given: ~p\", [Prop, Msg, Given])),\n erlang:error({bad_value, Msg2}, [Args]).","avg_line_length":27.0092592593,"max_line_length":131,"alphanum_fraction":0.594103531} +{"size":4692,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%% @author Couchbase \n%% @copyright 2013-2019 Couchbase, Inc.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% @doc suprevisor for dcp_replicator's\n%%\n-module(dcp_sup).\n\n-behavior(supervisor).\n\n-include(\"ns_common.hrl\").\n\n-export([start_link\/1, init\/1]).\n\n-export([get_children\/1, manage_replicators\/2, nuke\/1]).\n-export([get_replication_features\/0]).\n\nstart_link(Bucket) ->\n supervisor:start_link({local, server_name(Bucket)}, ?MODULE, []).\n\n-spec server_name(bucket_name()) -> atom().\nserver_name(Bucket) ->\n list_to_atom(?MODULE_STRING \"-\" ++ Bucket).\n\ninit([]) ->\n {ok, {{one_for_one,\n misc:get_env_default(max_r, 3),\n misc:get_env_default(max_t, 10)},\n []}}.\n\nget_children(Bucket) ->\n [{Node, C, T, M} ||\n {{Node, _RepFeatures}, C, T, M}\n <- supervisor:which_children(server_name(Bucket)),\n is_pid(C)].\n\nbuild_child_spec(Bucket, {ProducerNode, RepFeatures} = ChildId) ->\n {ChildId,\n {dcp_replicator, start_link, [ProducerNode, Bucket, RepFeatures]},\n temporary, 60000, worker, [dcp_replicator]}.\n\nstart_replicator(Bucket, {ProducerNode, RepFeatures} = ChildId) ->\n ?log_debug(\"Starting DCP replication from ~p for bucket ~p (Features = ~p)\",\n [ProducerNode, Bucket, RepFeatures]),\n\n case supervisor:start_child(server_name(Bucket),\n build_child_spec(Bucket, ChildId)) of\n {ok, _} -> ok;\n {ok, _, _} -> ok\n end.\n\nkill_replicator(Bucket, {ProducerNode, RepFeatures} = ChildId) ->\n ?log_debug(\"Going to stop DCP replication from ~p for bucket ~p \"\n \"(Features = ~p)\", [ProducerNode, Bucket, RepFeatures]),\n _ = supervisor:terminate_child(server_name(Bucket), ChildId),\n ok.\n\n%% Replicators need to negotiate features while opening DCP connections\n%% in order to enable certain features and these features can be enabled\n%% only when the entire cluster is at a particular compat_version.\n%%\n%% We try to determine what features to enable and send this information as a\n%% canonicalized list which is encoded into the replicator names (child ID).\n%% Whenever features become eligible to be turned on or disabled, this list\n%% would differ in its content thereby signalling the supervisor to drop\n%% existing connections and recreate them with appropriate features enabled.\n%% This could mean that the ongoing rebalance can fail and we are ok with that\n%% as it can be restarted.\nget_replication_features() ->\n FeatureSet = [{xattr, cluster_compat_mode:is_cluster_50()},\n {snappy, memcached_config_mgr:is_snappy_enabled()},\n %% this function is called for membase buckets only\n %% so we can assume that if collections are enabled globally\n %% they cannot be disabled for particular bucket\n {collections, collections:enabled()},\n {del_times, cluster_compat_mode:is_cluster_55()}],\n misc:canonical_proplist(FeatureSet).\n\nmanage_replicators(Bucket, NeededNodes) ->\n CurrNodes = [ChildId || {ChildId, _C, _T, _M} <-\n supervisor:which_children(server_name(Bucket))],\n\n RepFeatures = get_replication_features(),\n ExpectedNodes = [{Node, RepFeatures} || Node <- NeededNodes],\n\n [kill_replicator(Bucket, CurrId) || CurrId <- CurrNodes -- ExpectedNodes],\n [start_replicator(Bucket, NewId) || NewId <- ExpectedNodes -- CurrNodes].\n\nnuke(Bucket) ->\n Children = try get_children(Bucket) of\n RawKids ->\n [{ProducerNode, Pid} || {ProducerNode, Pid, _, _} <- RawKids]\n catch exit:{noproc, _} ->\n []\n end,\n\n ?log_debug(\"Nuking DCP replicators for bucket ~p:~n~p\",\n [Bucket, Children]),\n misc:terminate_and_wait([Pid || {_, Pid} <- Children], {shutdown, nuke}),\n\n Connections = dcp_replicator:get_connections(Bucket),\n misc:parallel_map(\n fun (ConnName) ->\n dcp_proxy:nuke_connection(consumer, ConnName, node(), Bucket)\n end,\n Connections,\n infinity),\n Children =\/= [] andalso Connections =\/= [].\n","avg_line_length":39.1,"max_line_length":84,"alphanum_fraction":0.6575021313} +{"size":17968,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%\n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2005-2009. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%%\n%%\n\n%%%-------------------------------------------------------------------\n%%% File : tftp_lib.erl\n%%% Author : Hakan Mattsson \n%%% Description : Option parsing, decode, encode etc.\n%%%\n%%% Created : 18 May 2004 by Hakan Mattsson \n%%%-------------------------------------------------------------------\n\n-module(tftp_lib).\n\n%%-------------------------------------------------------------------\n%% Interface\n%%-------------------------------------------------------------------\n\n%% application internal functions\n-export([\n parse_config\/1,\n parse_config\/2,\n decode_msg\/1,\n encode_msg\/1,\n replace_val\/3,\n to_lower\/1,\n host_to_string\/1,\n\t add_default_callbacks\/1\n ]).\n\n%%-------------------------------------------------------------------\n%% Defines\n%%-------------------------------------------------------------------\n\n-include(\"tftp.hrl\").\n\n-define(LOWER(Char),\n if\n Char >= $A, Char =< $Z ->\n Char - ($A - $a);\n true ->\n Char\n end).\n\n%%-------------------------------------------------------------------\n%% Config\n%%-------------------------------------------------------------------\n\nparse_config(Options) ->\n parse_config(Options, #config{}).\n\nparse_config(Options, Config) ->\n do_parse_config(Options, Config).\n\ndo_parse_config([{Key, Val} | Tail], Config) when is_record(Config, config) ->\n case Key of\n debug ->\n if\n Val =:= 0; Val =:= none ->\n do_parse_config(Tail, Config#config{debug_level = none});\n Val =:= 1; Val =:= error ->\n do_parse_config(Tail, Config#config{debug_level = error});\n Val =:= 2; Val =:= warning ->\n do_parse_config(Tail, Config#config{debug_level = warning});\n Val =:= 3; Val =:= brief ->\n do_parse_config(Tail, Config#config{debug_level = brief});\n Val =:= 4; Val =:= normal ->\n do_parse_config(Tail, Config#config{debug_level = normal});\n Val =:= 5; Val =:= verbose ->\n do_parse_config(Tail, Config#config{debug_level = verbose});\n Val =:= 6; Val =:= all ->\n do_parse_config(Tail, Config#config{debug_level = all});\n true ->\n exit({badarg, {Key, Val}})\n end;\n host ->\n if\n is_list(Val) ->\n do_parse_config(Tail, Config#config{udp_host = Val});\n is_tuple(Val), size(Val) =:= 4 ->\n do_parse_config(Tail, Config#config{udp_host = Val});\n is_tuple(Val), size(Val) =:= 8 ->\n do_parse_config(Tail, Config#config{udp_host = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n port ->\n if\n is_integer(Val), Val >= 0 ->\n Config2 = Config#config{udp_port = Val, udp_options = Config#config.udp_options},\n do_parse_config(Tail, Config2);\n true ->\n exit({badarg, {Key, Val}})\n end;\n port_policy ->\n case Val of\n random ->\n do_parse_config(Tail, Config#config{port_policy = Val});\n 0 ->\n do_parse_config(Tail, Config#config{port_policy = random});\n MinMax when is_integer(MinMax), MinMax > 0 ->\n do_parse_config(Tail, Config#config{port_policy = {range, MinMax, MinMax}});\n {range, Min, Max} when Max >= Min, \n is_integer(Min), Min > 0,\n is_integer(Max), Max > 0 ->\n do_parse_config(Tail, Config#config{port_policy = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n udp when is_list(Val) ->\n Fun = \n fun({K, V}, List) when K \/= active -> \n replace_val(K, V, List);\n (V, List) when V \/= list, V \/= binary ->\n List ++ [V];\n (V, _List) ->\n exit({badarg, {udp, [V]}})\n end,\n UdpOptions = lists:foldl(Fun, Config#config.udp_options, Val),\n do_parse_config(Tail, Config#config{udp_options = UdpOptions});\n use_tsize ->\n case Val of\n true ->\n do_parse_config(Tail, Config#config{use_tsize = Val});\n false ->\n do_parse_config(Tail, Config#config{use_tsize = Val});\n _ ->\n exit({badarg, {Key, Val}})\n end;\n max_tsize ->\n if\n Val =:= infinity ->\n do_parse_config(Tail, Config#config{max_tsize = Val});\n is_integer(Val), Val >= 0 ->\n do_parse_config(Tail, Config#config{max_tsize = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n max_conn ->\n if\n Val =:= infinity ->\n do_parse_config(Tail, Config#config{max_conn = Val});\n is_integer(Val), Val > 0 ->\n do_parse_config(Tail, Config#config{max_conn = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n _ when is_list(Key), is_list(Val) ->\n Key2 = to_lower(Key),\n Val2 = to_lower(Val),\n TftpOptions = replace_val(Key2, Val2, Config#config.user_options),\n do_parse_config(Tail, Config#config{user_options = TftpOptions});\n reject ->\n case Val of\n read ->\n Rejected = [Val | Config#config.rejected],\n do_parse_config(Tail, Config#config{rejected = Rejected});\n write ->\n Rejected = [Val | Config#config.rejected],\n do_parse_config(Tail, Config#config{rejected = Rejected});\n _ when is_list(Val) ->\n Rejected = [Val | Config#config.rejected],\n do_parse_config(Tail, Config#config{rejected = Rejected});\n _ ->\n exit({badarg, {Key, Val}})\n end;\n callback ->\n case Val of\n {RegExp, Mod, State} when is_list(RegExp), is_atom(Mod) ->\n case inets_regexp:parse(RegExp) of\n {ok, Internal} ->\n Callback = #callback{regexp = RegExp,\n internal = Internal,\n module = Mod,\n state = State},\n Callbacks = Config#config.callbacks ++ [Callback],\n do_parse_config(Tail, Config#config{callbacks = Callbacks});\n {error, Reason} ->\n exit({badarg, {Key, Val}, Reason})\n end;\n _ ->\n exit({badarg, {Key, Val}})\n end;\n logger ->\n if\n is_atom(Val) ->\n do_parse_config(Tail, Config#config{logger = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n max_retries ->\n if\n is_integer(Val), Val > 0 ->\n do_parse_config(Tail, Config#config{max_retries = Val});\n true ->\n exit({badarg, {Key, Val}})\n end;\n _ ->\n exit({badarg, {Key, Val}})\n end;\ndo_parse_config([], #config{udp_host = Host,\n udp_options = UdpOptions,\n user_options = UserOptions,\n callbacks = Callbacks} = Config) ->\n IsInet6 = lists:member(inet6, UdpOptions),\n IsInet = lists:member(inet, UdpOptions),\n Host2 = \n if\n (IsInet and not IsInet6); (not IsInet and not IsInet6) -> \n case inet:getaddr(Host, inet) of\n {ok, Addr} ->\n Addr;\n {error, Reason} ->\n exit({badarg, {host, Reason}})\n end;\n (IsInet6 and not IsInet) ->\n case inet:getaddr(Host, inet6) of\n {ok, Addr} ->\n Addr;\n {error, Reason} ->\n exit({badarg, {host, Reason}})\n end;\n true ->\n %% Conflicting options\n exit({badarg, {udp, [inet]}})\n end,\n UdpOptions2 = lists:reverse(UdpOptions),\n TftpOptions = lists:reverse(UserOptions),\n Callbacks2 = add_default_callbacks(Callbacks),\n Config#config{udp_host = Host2,\n udp_options = UdpOptions2,\n user_options = TftpOptions,\n callbacks = Callbacks2};\ndo_parse_config(Options, Config) when is_record(Config, config) ->\n exit({badarg, Options}).\n\nadd_default_callbacks(Callbacks) ->\n RegExp = \"\",\n {ok, Internal} = inets_regexp:parse(RegExp),\n File = #callback{regexp = RegExp,\n\t\t internal = Internal,\n\t\t module = tftp_file,\n\t\t state = []},\n Bin = #callback{regexp = RegExp,\n\t\t internal = Internal,\n\t\t module = tftp_binary,\n\t\t state = []},\n Callbacks ++ [File, Bin].\n\nhost_to_string(Host) ->\n case Host of\n String when is_list(String) ->\n String;\n {A1, A2, A3, A4} -> % inet\n lists:concat([A1, \".\", A2, \".\", A3, \".\",A4]);\n {A1, A2, A3, A4, A5, A6, A7, A8} -> % inet6\n lists:concat([\n int16_to_hex(A1), \"::\",\n int16_to_hex(A2), \"::\",\n int16_to_hex(A3), \"::\",\n int16_to_hex(A4), \"::\",\n int16_to_hex(A5), \"::\",\n int16_to_hex(A6), \"::\",\n int16_to_hex(A7), \"::\",\n int16_to_hex(A8)\n ])\n end.\n\nint16_to_hex(0) ->\n [$0];\nint16_to_hex(I) ->\n N1 = ((I bsr 8) band 16#ff),\n N2 = (I band 16#ff),\n [code_character(N1 div 16), code_character(N1 rem 16),\n code_character(N2 div 16), code_character(N2 rem 16)].\n\ncode_character(N) when N < 10 ->\n $0 + N;\ncode_character(N) ->\n $A + (N - 10).\n\n%%-------------------------------------------------------------------\n%% Decode\n%%-------------------------------------------------------------------\n\ndecode_msg(Bin) when is_binary(Bin) ->\n case Bin of\n <> ->\n case decode_strings(Tail, [keep_case, lower_case]) of\n [Filename, Mode | Strings] ->\n Options = decode_options(Strings),\n #tftp_msg_req{access = read,\n filename = Filename,\n mode = to_lower(Mode),\n options = Options};\n [_Filename | _Strings] ->\n exit(#tftp_msg_error{code = undef,\n text = \"Missing mode\"});\n _ ->\n exit(#tftp_msg_error{code = undef,\n text = \"Missing filename\"})\n end;\n <> ->\n case decode_strings(Tail, [keep_case, lower_case]) of\n [Filename, Mode | Strings] ->\n Options = decode_options(Strings),\n #tftp_msg_req{access = write,\n filename = Filename,\n mode = to_lower(Mode),\n options = Options};\n [_Filename | _Strings] ->\n exit(#tftp_msg_error{code = undef,\n text = \"Missing mode\"});\n _ ->\n exit(#tftp_msg_error{code = undef,\n text = \"Missing filename\"})\n end;\n <> ->\n #tftp_msg_data{block_no = SeqNo, data = Data};\n <> ->\n #tftp_msg_ack{block_no = SeqNo};\n <> ->\n case decode_strings(Tail, [keep_case]) of\n [ErrorText] ->\n ErrorCode2 = decode_error_code(ErrorCode),\n #tftp_msg_error{code = ErrorCode2,\n text = ErrorText};\n _ ->\n exit(#tftp_msg_error{code = undef,\n text = \"Trailing garbage\"})\n end;\n <> ->\n Strings = decode_strings(Tail, [lower_case]),\n Options = decode_options(Strings),\n #tftp_msg_oack{options = Options};\n _ ->\n exit(#tftp_msg_error{code = undef,\n text = \"Invalid syntax\"})\n end.\n\ndecode_strings(Bin, Cases) when is_binary(Bin), is_list(Cases) ->\n do_decode_strings(Bin, Cases, []).\n\ndo_decode_strings(<<>>, _Cases, Strings) ->\n lists:reverse(Strings);\ndo_decode_strings(Bin, [Case | Cases], Strings) ->\n {String, Tail} = decode_string(Bin, Case, []),\n if\n Cases =:= [] ->\n do_decode_strings(Tail, [Case], [String | Strings]);\n true ->\n do_decode_strings(Tail, Cases, [String | Strings])\n end.\n\ndecode_string(<>, Case, String) ->\n if\n Char =:= 0 ->\n {lists:reverse(String), Tail};\n Case =:= keep_case ->\n decode_string(Tail, Case, [Char | String]);\n Case =:= lower_case ->\n Char2 = ?LOWER(Char),\n decode_string(Tail, Case, [Char2 | String])\n end;\ndecode_string(<<>>, _Case, _String) ->\n exit(#tftp_msg_error{code = undef, text = \"Trailing null missing\"}).\n\ndecode_options([Key, Value | Strings]) ->\n [{to_lower(Key), Value} | decode_options(Strings)];\ndecode_options([]) ->\n [].\n\ndecode_error_code(Int) ->\n case Int of\n ?TFTP_ERROR_UNDEF -> undef;\n ?TFTP_ERROR_ENOENT -> enoent;\n ?TFTP_ERROR_EACCES -> eacces;\n ?TFTP_ERROR_ENOSPC -> enospc;\n ?TFTP_ERROR_BADOP -> badop;\n ?TFTP_ERROR_BADBLK -> badblk;\n ?TFTP_ERROR_EEXIST -> eexist;\n ?TFTP_ERROR_BADUSER -> baduser;\n ?TFTP_ERROR_BADOPT -> badopt;\n Int when is_integer(Int), Int >= 0, Int =< 65535 -> Int;\n _ -> exit(#tftp_msg_error{code = undef, text = \"Error code outside range.\"})\n end.\n\n%%-------------------------------------------------------------------\n%% Encode\n%%-------------------------------------------------------------------\n\nencode_msg(#tftp_msg_req{access = Access,\n filename = Filename,\n mode = Mode, \n options = Options}) ->\n OpCode = case Access of\n read -> ?TFTP_OPCODE_RRQ;\n write -> ?TFTP_OPCODE_WRQ\n end,\n [\n <>,\n Filename, \n 0, \n Mode, \n 0,\n [[Key, 0, Val, 0] || {Key, Val} <- Options]\n ];\nencode_msg(#tftp_msg_data{block_no = BlockNo, data = Data}) when BlockNo =< 65535 ->\n [\n <>,\n Data\n ];\nencode_msg(#tftp_msg_ack{block_no = BlockNo}) when BlockNo =< 65535 ->\n <>;\nencode_msg(#tftp_msg_error{code = Code, text = Text}) ->\n IntCode = encode_error_code(Code),\n [\n <>, \n Text,\n 0\n ];\nencode_msg(#tftp_msg_oack{options = Options}) ->\n [\n <>,\n [[Key, 0, Val, 0] || {Key, Val} <- Options]\n ].\n\nencode_error_code(Code) ->\n case Code of\n undef -> ?TFTP_ERROR_UNDEF;\n enoent -> ?TFTP_ERROR_ENOENT;\n eacces -> ?TFTP_ERROR_EACCES;\n enospc -> ?TFTP_ERROR_ENOSPC;\n badop -> ?TFTP_ERROR_BADOP;\n badblk -> ?TFTP_ERROR_BADBLK;\n eexist -> ?TFTP_ERROR_EEXIST;\n baduser -> ?TFTP_ERROR_BADUSER;\n badopt -> ?TFTP_ERROR_BADOPT;\n Int when is_integer(Int), Int >= 0, Int =< 65535 -> Int\n end.\n\n%%-------------------------------------------------------------------\n%% Miscellaneous\n%%-------------------------------------------------------------------\n\nreplace_val(Key, Val, List) ->\n case lists:keysearch(Key, 1, List) of\n false ->\n List ++ [{Key, Val}];\n {value, {_, OldVal}} when OldVal =:= Val ->\n List;\n {value, {_, _}} ->\n lists:keyreplace(Key, 1, List, {Key, Val})\n end.\n\nto_lower(Chars) ->\n [?LOWER(Char) || Char <- Chars].\n","avg_line_length":37.8273684211,"max_line_length":101,"alphanum_fraction":0.4565338379} +{"size":2229,"ext":"erl","lang":"Erlang","max_stars_count":8238.0,"content":"%% \n%% %CopyrightBegin%\n%% \n%% Copyright Ericsson AB 2004-2019. All Rights Reserved.\n%% \n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%% \n%% %CopyrightEnd%\n%% \n\n-module(snmpm_network_interface).\n\n-callback start_link(Server, NoteStore) ->\n {ok, Pid} | {error, Reason} when\n Server :: pid(),\n NoteStore :: pid(),\n Pid :: pid(),\n Reason :: term().\n\n-callback stop(Pid) ->\n snmp:void() when\n Pid :: pid().\n\n-callback send_pdu(Pid, Pdu, Vsn, MsgData, Domain, Addr, ExtraInfo) ->\n snmp:void() when\n Pid :: pid(),\n Pdu :: snmp:pdu(),\n Vsn :: 'version-1' | 'version-2' | 'version-3',\n MsgData :: term(),\n Domain :: snmp:tdomain(),\n Addr :: {inet:ip_address(), inet:port_number()},\n ExtraInfo :: term().\n\n-callback inform_response(Pid, Ref, Addr, Port) ->\n snmp:void() when\n Pid :: pid(),\n Ref :: term(),\n Addr :: inet:ip_address(),\n Port :: inet:port_number().\n\n-callback note_store(Pid, NoteStore) ->\n snmp:void() when\n Pid :: pid(),\n NoteStore :: pid().\n\n-callback info(Pid) ->\n Info when\n Pid :: pid(),\n Info :: [{Key, Value}],\n Key :: term(),\n Value :: term().\n\n-callback verbosity(Pid, Verbosity) ->\n snmp:void() when\n Pid :: pid(),\n Verbosity :: snmp:verbosity().\n\n-callback get_log_type(Pid) ->\n {ok, LogType} | {error, Reason} when\n Pid :: pid(),\n LogType :: snmp:atl_type(),\n Reason :: term().\n\n-callback set_log_type(Pid, NewType) ->\n {ok, OldType} | {error, Reason} when\n Pid :: pid(),\n NewType :: snmp:atl_type(),\n OldType :: snmp:atl_type(),\n Reason :: term().\n\n","avg_line_length":27.5185185185,"max_line_length":75,"alphanum_fraction":0.5800807537} +{"size":2696,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%% -*- erlang-indent-level: 2 -*-\n%%\n%% %CopyrightBegin%\n%%\n%% Copyright Ericsson AB 2016. All Rights Reserved.\n%%\n%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%% you may not use this file except in compliance with the License.\n%% You may obtain a copy of the License at\n%%\n%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%\n%% Unless required by applicable law or agreed to in writing, software\n%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%% See the License for the specific language governing permissions and\n%% limitations under the License.\n%%\n%% %CopyrightEnd%\n%%\n%%----------------------------------------------------------------------\n%% File : hipe_icode_call_elim.erl\n%% Authors : Daniel S. McCain ,\n%% Magnus L\u00e5ng \n%% Created : 14 Apr 2014 by Magnus L\u00e5ng \n%% Purpose : Eliminate calls to BIFs that are side-effect free only when\n%% executed on some argument types.\n%%----------------------------------------------------------------------\n-module(hipe_icode_call_elim).\n-export([cfg\/1]).\n\n-include(\"hipe_icode.hrl\").\n-include(\"..\/flow\/cfg.hrl\").\n\n-spec cfg(cfg()) -> cfg().\n\ncfg(IcodeSSA) ->\n lists:foldl(fun (Lbl, CFG1) ->\n\t\t BB1 = hipe_icode_cfg:bb(CFG1, Lbl),\n\t\t Code1 = hipe_bb:code(BB1),\n\t\t Code2 = lists:map(fun elim_insn\/1, Code1),\n\t\t BB2 = hipe_bb:code_update(BB1, Code2),\n\t\t hipe_icode_cfg:bb_add(CFG1, Lbl, BB2)\n\t end, IcodeSSA, hipe_icode_cfg:labels(IcodeSSA)).\n\n-spec elim_insn(icode_instr()) -> icode_instr().\nelim_insn(Insn=#icode_call{'fun'={_,_,_}=MFA, args=Args, type=remote,\n\t\t\t dstlist=[Dst=#icode_variable{\n\t\t\t\t\t annotation={type_anno, RetType, _}}],\n\t\t\t continuation=[], fail_label=[]}) ->\n Opaques = 'universe',\n case erl_types:t_is_singleton(RetType, Opaques) of\n true ->\n ArgTypes = [case Arg of\n\t\t #icode_variable{annotation={type_anno, Type, _}} -> Type;\n\t\t #icode_const{} ->\n\t\t erl_types:t_from_term(hipe_icode:const_value(Arg))\n\t\t end || Arg <- Args],\n case can_be_eliminated(MFA, ArgTypes) of\n\ttrue ->\n\t Const = hipe_icode:mk_const(\n\t\t erl_types:t_singleton_to_term(RetType, Opaques)),\n\t #icode_move{dst=Dst, src=Const};\n\tfalse -> Insn\n end;\n false -> Insn\n end;\nelim_insn(Insn) -> Insn.\n\n\n%% A function can be eliminated for some argument types if it has no side\n%% effects when run on arguments of those types.\n\n-spec can_be_eliminated(mfa(), [erl_types:erl_type()]) -> boolean().\n\ncan_be_eliminated({maps, is_key, 2}, [_K, M]) ->\n erl_types:t_is_map(M);\ncan_be_eliminated(_, _) ->\n false.\n","avg_line_length":33.7,"max_line_length":75,"alphanum_fraction":0.6424332344} +{"size":1989,"ext":"erl","lang":"Erlang","max_stars_count":2.0,"content":"%%\n%% libigl.erl --\n%%\n%% This module interfaces some functions in libigl.\n%%\n%% Copyright (c) 2019 Dan Gudmundsson\n%%\n%% See the file \"license.terms\" for information on usage and redistribution\n%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.\n\n-module(libigl).\n\n-export([lscm\/4]).\n-export([harmonic\/4]).\n-export([slim\/5]).\n-on_load(init\/0).\n-define(nif_stub,nif_stub_error(?LINE)).\n\n-type triangles() :: nonempty_list().\n-type point2d() :: {float(), float()}.\n\n-type energy_type() :: 'arap' | 'log_arap' | 'symmetric_dirichlet' |\n 'conformal' | 'exp_conformal' | 'exp_symmetric_dirichlet'.\n\n%% Least sqaure conformal maps\n%% At least bind two BorderVs with UV-positions in BorderPos\n-spec lscm(Vs::[e3d_vec:point()],Fs::triangles(),[BVs::integer()], BPos::[point2d()]) ->\n [point2d()].\nlscm(_Vs,_Fs,_BorderVs,_BorderPos) ->\n ?nif_stub.\n\n\n%% Harmonic mapping\n%% All BorderVs must be present and have an initial mapping in BorderPos\n-spec harmonic(Vs::[e3d_vec:point()],Fs::triangles(),[BVs::integer()], BPos::[point2d()]) ->\n [point2d()].\nharmonic(_Vs,_Fs,_BorderVs,_BorderPos) ->\n ?nif_stub.\n\n\n%% Slim Scalable Locally Injective Mappings\n%% UVInitPos must contain an intial (non-flipped) UV-mapping of all verts\n%% Stops when change is less then eps\n-spec slim(VS::[e3d_vec:point()], Fs::triangles(),\n UVInitPos::[point2d()], energy_type(), Eps::float()) -> [point2d()].\nslim(_Vs,_Fs, _InitUVs, _Type, _Eps) ->\n ?nif_stub.\n\n%%% Nif init\n\nnif_stub_error(Line) ->\n erlang:nif_error({nif_not_loaded,module,?MODULE,line,Line}).\n\ninit() ->\n case get(wings_not_running) of\n\tundefined ->\n Name = \"libigl\",\n\t Dir = case code:priv_dir(wings) of\n {error, _} -> filename:join(wings_util:lib_dir(wings),\"priv\");\n Priv -> Priv\n end,\n Nif = filename:join(Dir, Name),\n erlang:load_nif(Nif, 0);\n\t_ ->\n\t false\n end.\n\n","avg_line_length":29.25,"max_line_length":92,"alphanum_fraction":0.6254399196} +{"size":9713,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"-module(beam_opcodes).\n%% Warning: Do not edit this file.\n%% Auto-generated by 'beam_makeops'.\n\n-export([format_number\/0]).\n-export([opcode\/2,opname\/1]).\n\n-spec format_number() -> 0.\nformat_number() -> 0.\n\n-spec opcode(atom(), 0..8) -> 1..158.\nopcode(label, 1) -> 1;\nopcode(func_info, 3) -> 2;\nopcode(int_code_end, 0) -> 3;\nopcode(call, 2) -> 4;\nopcode(call_last, 3) -> 5;\nopcode(call_only, 2) -> 6;\nopcode(call_ext, 2) -> 7;\nopcode(call_ext_last, 3) -> 8;\nopcode(bif0, 2) -> 9;\nopcode(bif1, 4) -> 10;\nopcode(bif2, 5) -> 11;\nopcode(allocate, 2) -> 12;\nopcode(allocate_heap, 3) -> 13;\nopcode(allocate_zero, 2) -> 14;\nopcode(allocate_heap_zero, 3) -> 15;\nopcode(test_heap, 2) -> 16;\nopcode(init, 1) -> 17;\nopcode(deallocate, 1) -> 18;\nopcode(return, 0) -> 19;\nopcode(send, 0) -> 20;\nopcode(remove_message, 0) -> 21;\nopcode(timeout, 0) -> 22;\nopcode(loop_rec, 2) -> 23;\nopcode(loop_rec_end, 1) -> 24;\nopcode(wait, 1) -> 25;\nopcode(wait_timeout, 2) -> 26;\n%%opcode(m_plus, 4) -> 27;\n%%opcode(m_minus, 4) -> 28;\n%%opcode(m_times, 4) -> 29;\n%%opcode(m_div, 4) -> 30;\n%%opcode(int_div, 4) -> 31;\n%%opcode(int_rem, 4) -> 32;\n%%opcode(int_band, 4) -> 33;\n%%opcode(int_bor, 4) -> 34;\n%%opcode(int_bxor, 4) -> 35;\n%%opcode(int_bsl, 4) -> 36;\n%%opcode(int_bsr, 4) -> 37;\n%%opcode(int_bnot, 3) -> 38;\nopcode(is_lt, 3) -> 39;\nopcode(is_ge, 3) -> 40;\nopcode(is_eq, 3) -> 41;\nopcode(is_ne, 3) -> 42;\nopcode(is_eq_exact, 3) -> 43;\nopcode(is_ne_exact, 3) -> 44;\nopcode(is_integer, 2) -> 45;\nopcode(is_float, 2) -> 46;\nopcode(is_number, 2) -> 47;\nopcode(is_atom, 2) -> 48;\nopcode(is_pid, 2) -> 49;\nopcode(is_reference, 2) -> 50;\nopcode(is_port, 2) -> 51;\nopcode(is_nil, 2) -> 52;\nopcode(is_binary, 2) -> 53;\n%%opcode(is_constant, 2) -> 54;\nopcode(is_list, 2) -> 55;\nopcode(is_nonempty_list, 2) -> 56;\nopcode(is_tuple, 2) -> 57;\nopcode(test_arity, 3) -> 58;\nopcode(select_val, 3) -> 59;\nopcode(select_tuple_arity, 3) -> 60;\nopcode(jump, 1) -> 61;\nopcode('catch', 2) -> 62;\nopcode(catch_end, 1) -> 63;\nopcode(move, 2) -> 64;\nopcode(get_list, 3) -> 65;\nopcode(get_tuple_element, 3) -> 66;\nopcode(set_tuple_element, 3) -> 67;\n%%opcode(put_string, 3) -> 68;\nopcode(put_list, 3) -> 69;\nopcode(put_tuple, 2) -> 70;\nopcode(put, 1) -> 71;\nopcode(badmatch, 1) -> 72;\nopcode(if_end, 0) -> 73;\nopcode(case_end, 1) -> 74;\nopcode(call_fun, 1) -> 75;\n%%opcode(make_fun, 3) -> 76;\nopcode(is_function, 2) -> 77;\nopcode(call_ext_only, 2) -> 78;\n%%opcode(bs_start_match, 2) -> 79;\n%%opcode(bs_get_integer, 5) -> 80;\n%%opcode(bs_get_float, 5) -> 81;\n%%opcode(bs_get_binary, 5) -> 82;\n%%opcode(bs_skip_bits, 4) -> 83;\n%%opcode(bs_test_tail, 2) -> 84;\n%%opcode(bs_save, 1) -> 85;\n%%opcode(bs_restore, 1) -> 86;\n%%opcode(bs_init, 2) -> 87;\n%%opcode(bs_final, 2) -> 88;\nopcode(bs_put_integer, 5) -> 89;\nopcode(bs_put_binary, 5) -> 90;\nopcode(bs_put_float, 5) -> 91;\nopcode(bs_put_string, 2) -> 92;\n%%opcode(bs_need_buf, 1) -> 93;\nopcode(fclearerror, 0) -> 94;\nopcode(fcheckerror, 1) -> 95;\nopcode(fmove, 2) -> 96;\nopcode(fconv, 2) -> 97;\nopcode(fadd, 4) -> 98;\nopcode(fsub, 4) -> 99;\nopcode(fmul, 4) -> 100;\nopcode(fdiv, 4) -> 101;\nopcode(fnegate, 3) -> 102;\nopcode(make_fun2, 1) -> 103;\nopcode('try', 2) -> 104;\nopcode(try_end, 1) -> 105;\nopcode(try_case, 1) -> 106;\nopcode(try_case_end, 1) -> 107;\nopcode(raise, 2) -> 108;\nopcode(bs_init2, 6) -> 109;\n%%opcode(bs_bits_to_bytes, 3) -> 110;\nopcode(bs_add, 5) -> 111;\nopcode(apply, 1) -> 112;\nopcode(apply_last, 2) -> 113;\nopcode(is_boolean, 2) -> 114;\nopcode(is_function2, 3) -> 115;\nopcode(bs_start_match2, 5) -> 116;\nopcode(bs_get_integer2, 7) -> 117;\nopcode(bs_get_float2, 7) -> 118;\nopcode(bs_get_binary2, 7) -> 119;\nopcode(bs_skip_bits2, 5) -> 120;\nopcode(bs_test_tail2, 3) -> 121;\nopcode(bs_save2, 2) -> 122;\nopcode(bs_restore2, 2) -> 123;\nopcode(gc_bif1, 5) -> 124;\nopcode(gc_bif2, 6) -> 125;\n%%opcode(bs_final2, 2) -> 126;\n%%opcode(bs_bits_to_bytes2, 2) -> 127;\n%%opcode(put_literal, 2) -> 128;\nopcode(is_bitstr, 2) -> 129;\nopcode(bs_context_to_binary, 1) -> 130;\nopcode(bs_test_unit, 3) -> 131;\nopcode(bs_match_string, 4) -> 132;\nopcode(bs_init_writable, 0) -> 133;\nopcode(bs_append, 8) -> 134;\nopcode(bs_private_append, 6) -> 135;\nopcode(trim, 2) -> 136;\nopcode(bs_init_bits, 6) -> 137;\nopcode(bs_get_utf8, 5) -> 138;\nopcode(bs_skip_utf8, 4) -> 139;\nopcode(bs_get_utf16, 5) -> 140;\nopcode(bs_skip_utf16, 4) -> 141;\nopcode(bs_get_utf32, 5) -> 142;\nopcode(bs_skip_utf32, 4) -> 143;\nopcode(bs_utf8_size, 3) -> 144;\nopcode(bs_put_utf8, 3) -> 145;\nopcode(bs_utf16_size, 3) -> 146;\nopcode(bs_put_utf16, 3) -> 147;\nopcode(bs_put_utf32, 3) -> 148;\nopcode(on_load, 0) -> 149;\nopcode(recv_mark, 1) -> 150;\nopcode(recv_set, 1) -> 151;\nopcode(gc_bif3, 7) -> 152;\nopcode(line, 1) -> 153;\nopcode(put_map_assoc, 5) -> 154;\nopcode(put_map_exact, 5) -> 155;\nopcode(is_map, 2) -> 156;\nopcode(has_map_fields, 3) -> 157;\nopcode(get_map_elements, 3) -> 158;\nopcode(Name, Arity) -> erlang:error(badarg, [Name,Arity]).\n\n-spec opname(1..158) -> {atom(),0..8}.\nopname(1) -> {label,1};\nopname(2) -> {func_info,3};\nopname(3) -> {int_code_end,0};\nopname(4) -> {call,2};\nopname(5) -> {call_last,3};\nopname(6) -> {call_only,2};\nopname(7) -> {call_ext,2};\nopname(8) -> {call_ext_last,3};\nopname(9) -> {bif0,2};\nopname(10) -> {bif1,4};\nopname(11) -> {bif2,5};\nopname(12) -> {allocate,2};\nopname(13) -> {allocate_heap,3};\nopname(14) -> {allocate_zero,2};\nopname(15) -> {allocate_heap_zero,3};\nopname(16) -> {test_heap,2};\nopname(17) -> {init,1};\nopname(18) -> {deallocate,1};\nopname(19) -> {return,0};\nopname(20) -> {send,0};\nopname(21) -> {remove_message,0};\nopname(22) -> {timeout,0};\nopname(23) -> {loop_rec,2};\nopname(24) -> {loop_rec_end,1};\nopname(25) -> {wait,1};\nopname(26) -> {wait_timeout,2};\nopname(27) -> {m_plus,4};\nopname(28) -> {m_minus,4};\nopname(29) -> {m_times,4};\nopname(30) -> {m_div,4};\nopname(31) -> {int_div,4};\nopname(32) -> {int_rem,4};\nopname(33) -> {int_band,4};\nopname(34) -> {int_bor,4};\nopname(35) -> {int_bxor,4};\nopname(36) -> {int_bsl,4};\nopname(37) -> {int_bsr,4};\nopname(38) -> {int_bnot,3};\nopname(39) -> {is_lt,3};\nopname(40) -> {is_ge,3};\nopname(41) -> {is_eq,3};\nopname(42) -> {is_ne,3};\nopname(43) -> {is_eq_exact,3};\nopname(44) -> {is_ne_exact,3};\nopname(45) -> {is_integer,2};\nopname(46) -> {is_float,2};\nopname(47) -> {is_number,2};\nopname(48) -> {is_atom,2};\nopname(49) -> {is_pid,2};\nopname(50) -> {is_reference,2};\nopname(51) -> {is_port,2};\nopname(52) -> {is_nil,2};\nopname(53) -> {is_binary,2};\nopname(54) -> {is_constant,2};\nopname(55) -> {is_list,2};\nopname(56) -> {is_nonempty_list,2};\nopname(57) -> {is_tuple,2};\nopname(58) -> {test_arity,3};\nopname(59) -> {select_val,3};\nopname(60) -> {select_tuple_arity,3};\nopname(61) -> {jump,1};\nopname(62) -> {'catch',2};\nopname(63) -> {catch_end,1};\nopname(64) -> {move,2};\nopname(65) -> {get_list,3};\nopname(66) -> {get_tuple_element,3};\nopname(67) -> {set_tuple_element,3};\nopname(68) -> {put_string,3};\nopname(69) -> {put_list,3};\nopname(70) -> {put_tuple,2};\nopname(71) -> {put,1};\nopname(72) -> {badmatch,1};\nopname(73) -> {if_end,0};\nopname(74) -> {case_end,1};\nopname(75) -> {call_fun,1};\nopname(76) -> {make_fun,3};\nopname(77) -> {is_function,2};\nopname(78) -> {call_ext_only,2};\nopname(79) -> {bs_start_match,2};\nopname(80) -> {bs_get_integer,5};\nopname(81) -> {bs_get_float,5};\nopname(82) -> {bs_get_binary,5};\nopname(83) -> {bs_skip_bits,4};\nopname(84) -> {bs_test_tail,2};\nopname(85) -> {bs_save,1};\nopname(86) -> {bs_restore,1};\nopname(87) -> {bs_init,2};\nopname(88) -> {bs_final,2};\nopname(89) -> {bs_put_integer,5};\nopname(90) -> {bs_put_binary,5};\nopname(91) -> {bs_put_float,5};\nopname(92) -> {bs_put_string,2};\nopname(93) -> {bs_need_buf,1};\nopname(94) -> {fclearerror,0};\nopname(95) -> {fcheckerror,1};\nopname(96) -> {fmove,2};\nopname(97) -> {fconv,2};\nopname(98) -> {fadd,4};\nopname(99) -> {fsub,4};\nopname(100) -> {fmul,4};\nopname(101) -> {fdiv,4};\nopname(102) -> {fnegate,3};\nopname(103) -> {make_fun2,1};\nopname(104) -> {'try',2};\nopname(105) -> {try_end,1};\nopname(106) -> {try_case,1};\nopname(107) -> {try_case_end,1};\nopname(108) -> {raise,2};\nopname(109) -> {bs_init2,6};\nopname(110) -> {bs_bits_to_bytes,3};\nopname(111) -> {bs_add,5};\nopname(112) -> {apply,1};\nopname(113) -> {apply_last,2};\nopname(114) -> {is_boolean,2};\nopname(115) -> {is_function2,3};\nopname(116) -> {bs_start_match2,5};\nopname(117) -> {bs_get_integer2,7};\nopname(118) -> {bs_get_float2,7};\nopname(119) -> {bs_get_binary2,7};\nopname(120) -> {bs_skip_bits2,5};\nopname(121) -> {bs_test_tail2,3};\nopname(122) -> {bs_save2,2};\nopname(123) -> {bs_restore2,2};\nopname(124) -> {gc_bif1,5};\nopname(125) -> {gc_bif2,6};\nopname(126) -> {bs_final2,2};\nopname(127) -> {bs_bits_to_bytes2,2};\nopname(128) -> {put_literal,2};\nopname(129) -> {is_bitstr,2};\nopname(130) -> {bs_context_to_binary,1};\nopname(131) -> {bs_test_unit,3};\nopname(132) -> {bs_match_string,4};\nopname(133) -> {bs_init_writable,0};\nopname(134) -> {bs_append,8};\nopname(135) -> {bs_private_append,6};\nopname(136) -> {trim,2};\nopname(137) -> {bs_init_bits,6};\nopname(138) -> {bs_get_utf8,5};\nopname(139) -> {bs_skip_utf8,4};\nopname(140) -> {bs_get_utf16,5};\nopname(141) -> {bs_skip_utf16,4};\nopname(142) -> {bs_get_utf32,5};\nopname(143) -> {bs_skip_utf32,4};\nopname(144) -> {bs_utf8_size,3};\nopname(145) -> {bs_put_utf8,3};\nopname(146) -> {bs_utf16_size,3};\nopname(147) -> {bs_put_utf16,3};\nopname(148) -> {bs_put_utf32,3};\nopname(149) -> {on_load,0};\nopname(150) -> {recv_mark,1};\nopname(151) -> {recv_set,1};\nopname(152) -> {gc_bif3,7};\nopname(153) -> {line,1};\nopname(154) -> {put_map_assoc,5};\nopname(155) -> {put_map_exact,5};\nopname(156) -> {is_map,2};\nopname(157) -> {has_map_fields,3};\nopname(158) -> {get_map_elements,3};\nopname(Number) -> erlang:error(badarg, [Number]).\n","avg_line_length":29.2560240964,"max_line_length":58,"alphanum_fraction":0.6371872748} +{"size":3444,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%----------------------------------------------------------------------\n%%% File : fxml_stream.erl\n%%% Author : Alexey Shchepin \n%%% Purpose : Parse XML streams\n%%% Created : 17 Nov 2002 by Alexey Shchepin \n%%%\n%%%\n%%% Copyright (C) 2002-2021 ProcessOne, SARL. All Rights Reserved.\n%%%\n%%% Licensed under the Apache License, Version 2.0 (the \"License\");\n%%% you may not use this file except in compliance with the License.\n%%% You may obtain a copy of the License at\n%%%\n%%% http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n%%%\n%%% Unless required by applicable law or agreed to in writing, software\n%%% distributed under the License is distributed on an \"AS IS\" BASIS,\n%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%%% See the License for the specific language governing permissions and\n%%% limitations under the License.\n%%%\n%%%----------------------------------------------------------------------\n\n-module(fxml_stream).\n\n-author('alexey@process-one.net').\n\n-compile(no_native).\n\n-export([new\/1, new\/2, new\/3, parse\/2, close\/1, reset\/1,\n\t change_callback_pid\/2, parse_element\/1]).\n\n-export([load_nif\/0, load_nif\/1]).\n\n-include(\"fxml.hrl\").\n\n-record(xml_stream_state,\n\t{callback_pid = self() :: pid(),\n port :: port(),\n stack = [] :: stack(),\n size = 0 :: non_neg_integer(),\n maxsize = infinity :: non_neg_integer() | infinity}).\n\n-type xml_stream_el() :: {xmlstreamraw, binary()} |\n {xmlstreamcdata, binary()} |\n {xmlstreamelement, xmlel()} |\n {xmlstreamend, binary()} |\n {xmlstreamstart, binary(), [attr()]} |\n {xmlstreamerror, binary()}.\n\n-type xml_stream_state() :: #xml_stream_state{}.\n-type stack() :: [xmlel()].\n\n-export_type([xml_stream_state\/0, xml_stream_el\/0]).\n\nload_nif() ->\n SOPath = p1_nif_utils:get_so_path(?MODULE, [fast_xml], \"fxml_stream\"),\n load_nif(SOPath).\n\nload_nif(SOPath) ->\n case erlang:load_nif(SOPath, 0) of\n\tok ->\n\t ok;\n {error, {Reason, Txt}} ->\n error_logger:error_msg(\"failed to load NIF ~s: ~s\",\n [SOPath, Txt]),\n {error, Reason}\n end.\n\n-spec new(pid()) -> xml_stream_state().\n\nnew(CallbackPid) ->\n new(CallbackPid, infinity).\n\n-spec new(pid(), non_neg_integer() | infinity) -> xml_stream_state().\n\nnew(_CallbackPid, _MaxSize) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec new(pid(), non_neg_integer() | infinity, list()) -> xml_stream_state().\n\nnew(_CallbackPid, _MaxSize, _Options) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec reset(xml_stream_state()) -> xml_stream_state().\n\nreset(_State) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec change_callback_pid(xml_stream_state(), pid()) -> xml_stream_state().\n\nchange_callback_pid(_State, _CallbackPid) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec parse(xml_stream_state(), binary()) -> xml_stream_state().\n\nparse(_State, _Data) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec close(xml_stream_state()) -> true.\n\nclose(_State) ->\n erlang:nif_error(nif_not_loaded).\n\n-spec parse_element(binary()) -> xmlel() |\n {error, atom()} |\n {error, {integer(), binary()}}.\n\nparse_element(_Str) ->\n erlang:nif_error(nif_not_loaded).\n","avg_line_length":31.027027027,"max_line_length":77,"alphanum_fraction":0.5943670151} +{"size":2080,"ext":"erl","lang":"Erlang","max_stars_count":1.0,"content":"%%\n%% This is the root supervisor for the suptest application. It starts 3 different\n%% supervisors that exhibit 3 different kinds of restart strategies and, in the\n%% case of best_sup, demostrate how state can be recovered across restarts\n%% (after crashes).\n%%\n\n-module(suptest_sup).\n\n-behaviour(supervisor).\n\n%% API\n-export([start_link\/0, start_child\/2, start_child\/1]).\n\n%% Supervisor callbacks\n-export([init\/1]).\n\n%% Helper macro for declaring children of supervisor\n-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).\n\n%% ===================================================================\n%% API functions\n%% ===================================================================\n\nstart_link() ->\n lager:emergency(\"******************* suptest_sup: START_LINK~n\", []),\n supervisor:start_link({local, ?MODULE}, ?MODULE, []).\n\nstart_child(Key, Value) ->\n lager:emergency(\"******************* suptest_sup: start_child(~p,~p)~n\", [Key, Value]),\n\tsupervisor:start_child(?MODULE, [Key, Value]).\n\nstart_child(Spec) ->\n lager:emergency(\"******************* suptest_sup: start_child(~p)~n\", [Spec]),\n\tsupervisor:start_child(?MODULE, Spec). \n \n%% ===================================================================\n%% Supervisor callbacks\n%% ===================================================================\n\ninit([]) ->\n%% HelloWorldServer = ?CHILD(suptest_hello_world, worker),\n lager:emergency(\"******************* suptest_sup: INIT~n\", []),\n\t\n\tNonStdSupervisor = {non_std_sup, {non_std_sup, start_link, []},\n\t\t\t\t\t\tpermanent, 5000, supervisor, [non_std_sup]},\n%% \tCrashSupervisor = {crash_sup, {crash_sup, start_link, []},\n%% \t\t\t\t\t\tpermanent, 5000, supervisor, [crash_sup]},\n%% \tBetterSupervisor = {better_sup, {better_sup, start_link, []},\n%% \t\t\t\t\t\tpermanent, 5000, supervisor, [better_sup]},\n%% \tBestSupervisor = {best_sup, {best_sup, start_link, []},\n%% \t\t\t\t\t\tpermanent, 5000, supervisor, [best_sup]},\n {ok, { {rest_for_one, 1, 1}, [NonStdSupervisor] } }. %, CrashSupervisor, BetterSupervisor, \n\t\t\t\t\t\t\t\t %BestSupervisor] } }.\n\n","avg_line_length":37.1428571429,"max_line_length":95,"alphanum_fraction":0.5610576923} +{"size":1018,"ext":"erl","lang":"Erlang","max_stars_count":null,"content":"%%%-------------------------------------------------------------------\n%% @doc shorturl top level supervisor.\n%% @end\n%%%-------------------------------------------------------------------\n\n-module(shorturl_sup).\n\n-behaviour(supervisor).\n\n%% API\n-export([start_link\/0]).\n\n%% Supervisor callbacks\n-export([init\/1]).\n\n-define(SERVER, ?MODULE).\n\n%%====================================================================\n%% API functions\n%%====================================================================\n\nstart_link() ->\n supervisor:start_link({local, ?SERVER}, ?MODULE, []).\n\n%%====================================================================\n%% Supervisor callbacks\n%%====================================================================\n\n%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}\ninit([]) ->\n {ok, { {one_for_all, 0, 1}, []} }.\n\n%%====================================================================\n%% Internal functions\n%%====================================================================\n","avg_line_length":28.2777777778,"max_line_length":70,"alphanum_fraction":0.2878192534}