### Run MySQL Docker Container and Setup Database
Source: https://www.boost.org/doc/libs/latest/libs/mysql/doc/html/mysql/examples.html
This snippet shows how to run a MySQL Docker container and load the necessary example database. It includes commands for starting the container and importing the SQL setup script.
```bash
# Remove the "-v /var/run/mysqld:/var/run/mysqld" part if you don't need UNIX sockets
> docker run --name some-mysql -p 3306:3306 -v /var/run/mysqld:/var/run/mysqld -d -e MYSQL_ROOT_PASSWORD= -e MYSQL_ALLOW_EMPTY_PASSWORD=1 -d mysql
# All the required data can be loaded by running example/db_setup.sql.
# If you're using the above container, the root user has a blank password
> mysql -u root < example/db_setup.sql
```
--------------------------------
### Main Function Setup
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/http/server/async/http_server_async.cpp
Parses command-line arguments, initializes the io_context, and starts the listener.
```cpp
int main(int argc, char* argv[])
{
// Check command line arguments.
if (argc != 5)
{
std::cerr <<
"Usage: http-server-async
\n" <<
"Example:\n" <<
" http-server-async 0.0.0.0 8080 . 1\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const doc_root = std::make_shared(argv[3]);
auto const threads = std::max(1, std::atoi(argv[4]));
// The io_context is required for all I/O
net::io_context ioc{threads};
// Create and launch a listening port
std::make_shared(
ioc,
tcp::endpoint{address, port},
doc_root)->run();
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
return EXIT_SUCCESS;
}
```
--------------------------------
### Main Function for Mutual Exclusion Example
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp20/channels/mutual_exclusion_1.cpp
Sets up the Boost.Asio io_context, resolves the listen endpoint, and starts the acceptor. It also spawns the listener coroutine and runs the io_context. Handles potential exceptions during setup.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: mutual_exclusion_1";
std::cerr << " \n";
return 1;
}
io_context ctx;
auto listen_endpoint =
*tcp::resolver(ctx).resolve(argv[1], argv[2],
tcp::resolver::passive).begin();
tcp::acceptor acceptor(ctx, listen_endpoint);
co_spawn(ctx, listen(acceptor), detached);
ctx.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
```
--------------------------------
### Example Directory Change
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
An example of changing the current directory to a Boost installation path. Adjust the path according to your Boost installation.
```bash
cd `C:\Program Files\boost\``boost_1_82_0`
```
--------------------------------
### Boost.Asio Async Accept Example
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/reference/basic_socket_acceptor/async_accept/overload1.html
An example demonstrating how to use `async_accept` to initiate an asynchronous connection acceptance. It includes a completion handler and the acceptor setup.
```cpp
void accept_handler(const boost::system::error_code& error)
{
if (!error)
{
// Accept succeeded.
}
}
...
boost::asio::ip::tcp::acceptor acceptor(my_context);
...
boost::asio::ip::tcp::socket socket(my_context);
acceptor.async_accept(socket, accept_handler);
```
--------------------------------
### SSL Server Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp11/ssl/server.cpp
Initializes the Boost.Asio SSL server, configures the SSL context, and starts accepting connections.
```cpp
#include
#include
#include
#include
#include
using boost::asio::ip::tcp;
class server
{
public:
server(boost::asio::io_context& io_context, unsigned short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
context_(boost::asio::ssl::context::sslv23)
{
context_.set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::single_dh_use);
context_.set_password_callback(std::bind(&server::get_password, this));
context_.use_certificate_chain_file("server.pem");
context_.use_private_key_file("server.pem", boost::asio::ssl::context::pem);
context_.use_tmp_dh_file("dh4096.pem");
do_accept();
}
private:
std::string get_password() const
{
return "test";
}
void do_accept()
{
acceptor_.async_accept(
[this](const boost::system::error_code& error, tcp::socket socket)
{
if (!error)
{
std::make_shared(
boost::asio::ssl::stream(
std::move(socket), context_))->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
boost::asio::ssl::context context_;
};
```
--------------------------------
### Configuration File Example
Source: https://www.boost.org/doc/libs/latest/libs/wave/doc/wave_driver.html
This snippet shows an example of a Wave configuration file, demonstrating how to enable features like variadics, timer support, emulate specific GCC versions, and add include search paths.
```bash
#
# enable variadics et.al. in C++ mode
#
--variadics
#
# enable timer support
#
--timer
#
# emulate gcc V3.3.2
#
-D__GNUC__=3
-D__GNUC_MINOR__=3
-D__GNUC_PATCHLEVEL__=2
-D__GNUG__
#
# add Boost to the system include search paths
#
-S/usr/local/boost
```
--------------------------------
### Main Program Setup for MySQL Connection Pool
Source: https://www.boost.org/doc/libs/latest/libs/mysql/doc/html/mysql/tutorial_connection_pool.html
Initializes the io_context, configures MySQL connection pool parameters, and starts the pool. This snippet is the core setup for the server application.
```cpp
// Create an I/O context, required by all I/O objects
asio::io_context ctx;
// pool_params contains configuration for the pool.
// You must specify enough information to establish a connection,
// including the server address and credentials.
// You can configure a lot of other things, like pool limits
mysql::pool_params params;
params.server_address.emplace_host_and_port(server_hostname);
params.username = username;
params.password = password;
params.database = "boost_mysql_examples";
// Construct the pool.
// ctx will be used to create the connections and other I/O objects
mysql::connection_pool pool(ctx, std::move(params));
// You need to call async_run on the pool before doing anything useful with it.
// async_run creates connections and keeps them healthy. It must be called
// only once per pool.
// The detached completion token means that we don't want to be notified when
// the operation ends. It's similar to a no-op callback.
pool.async_run(asio::detached);
```
--------------------------------
### Running the Example Program
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
Command to run the compiled Boost example program, redirecting input from 'jayne.txt'.
```bash
_path_/_to_/example < _path_/_to_/jayne.txt
```
--------------------------------
### Install Boost.Build
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
Steps to build and install Boost.Build from its source directory.
```bash
b2 install --prefix=_PREFIX_
```
--------------------------------
### Main Function Setup
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/http/server/sync-ssl/http_server_sync_ssl.cpp
Initializes the server, parses command-line arguments for address, port, and document root, and sets up the io_context and SSL context. Includes basic argument validation.
```cpp
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 4)
{
std::cerr <<
"Usage: http-server-sync-ssl \n" <<
"Example:\n" <<
" http-server-sync-ssl 0.0.0.0 8080 .\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const doc_root = std::make_shared(argv[3]);
// The io_context is required for all I/O
net::io_context ioc{1};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
```
--------------------------------
### Recommended Setup for Database Selection
Source: https://www.boost.org/doc/libs/latest/libs/redis/doc/html/redis/reference/boost/redis/config/database_index.html
This snippet demonstrates the recommended approach to select a database index using the `setup` field. Set `use_setup` to true and push a 'SELECT' command with the desired database index.
```cpp
cfg.use_setup = true;
cfg.setup.push("SELECT", 4); // select database index 4
```
--------------------------------
### HTTP GET Request Example
Source: https://www.boost.org/doc/libs/latest/doc/antora/url/urls/components.html
An example of a complete HTTP/1.1 GET request. The URL's scheme is implied by the context of the request.
```http
GET /index.htm HTTP/1.1
Host: www.example.com
Accept: text/html
User-Agent: Beast
```
--------------------------------
### Install Boost.Build
Source: https://www.boost.org/doc/libs/latest/more/getting_started/unix-variants.html
Steps to build and install Boost.Build from source. Ensure the installation prefix and its bin directory are added to your PATH.
```bash
cd tools/build/
bash bootstrap.sh
b2 install --prefix=_PREFIX_
export PATH=_PREFIX_/bin:$PATH
```
--------------------------------
### Main Server Entry Point
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp11/ssl/server.cpp
Sets up the Boost.Asio io_context and starts the SSL server, handling command-line arguments for the port.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: server \n";
return 1;
}
boost::asio::io_context io_context;
using namespace std;
server s(io_context, atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
```
--------------------------------
### Compile and Run Boost.Filesystem Tutorial Example (Windows)
Source: https://www.boost.org/doc/libs/latest/libs/filesystem/doc/tutorial.html
Commands to navigate to the example directory, compile the tutorial programs using b2, and run the tut1 example on Microsoft Windows.
```batch
>cd _**boost-root**_\libs\filesystem\example
>b2.exe tutorial
Compiling example programs...
>tut1
Usage: tut1 path
```
--------------------------------
### start
Source: https://www.boost.org/doc/libs/latest/boost/container/vector.hpp
Gets or sets the starting pointer of the allocated memory.
```APIDOC
## start
### Description
Gets or sets the starting pointer of the allocated memory.
### Method
`pointer` (getter) or `void` (setter)
### Parameters
- **p** (const pointer &) - The pointer to set (for the setter).
```
--------------------------------
### Compile and Run Boost.Filesystem Tutorial Example (Linux)
Source: https://www.boost.org/doc/libs/latest/libs/filesystem/doc/tutorial.html
Commands to navigate to the example directory, compile the tutorial programs using b2, and run the tut1 example on Ubuntu Linux.
```bash
$ cd _**boost-root**_/libs/filesystem/example
$ b2 tutorial
Compiling example programs...
$ ./tut1
Usage: tut1 path
```
--------------------------------
### DST Start Date Rule Examples
Source: https://www.boost.org/doc/libs/latest/boost/date_time/tz_db_base.hpp
Provides examples of the specially formatted strings used to define the start date rule for daylight saving time transitions.
```cpp
"-1;5;9"="Last Friday of September",
"2;1;3"="Second Monday of March"
```
--------------------------------
### Get the beginning of a local_time_period
Source: https://www.boost.org/doc/libs/latest/doc/html/date_time/local_time.html
Retrieves the starting local_date_time of the period. This is the inclusive start of the range.
```cpp
time_zone_ptr
zone(new posix_time_zone("MST-07"));
local_date_time
ldt((ptime(date(2005,Jan,1)),hours(0)), zone);
local_time_period ltp(ldt, hours(2));
ltp.begin(); // => 2005-Jan-01 00:00:00
```
--------------------------------
### Main Function Example Setup
Source: https://www.boost.org/doc/libs/latest/libs/fiber/examples/adapt_method_calls.cpp
Initializes the `AsyncAPI` with sample data in the `main` function to prepare for demonstrating asynchronous operations.
```cpp
/*****************************************************************************
* driving logic
*****************************************************************************/
int main(int argc, char *argv[]) {
// prime AsyncAPI with some data
AsyncAPI api("abcd");
```
--------------------------------
### Main Function Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/tutorial/tutdaytime4.html
Sets up the main function, including argument checking and initializing the io_context.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client " << std::endl;
return 1;
}
boost::asio::io_context io_context;
```
--------------------------------
### foldl_reject_incomplete Example Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/metaparse/reference.html
Defines helper parsers and metafunctions used in examples for foldl_reject_incomplete.
```cpp
using int_token = token;
using plus_token = token>;
using plus_int = last_of;
using sum_op = mpl::lambda>::type;
```
--------------------------------
### Get Period Start Character
Source: https://www.boost.org/doc/libs/latest/doc/html/doxygen/date_time_reference/classboost_1_1date__time_1_1iso__format__base_3_01wchar__t_01_4.html
Returns the ISO 8601 character indicating the start of a period.
```cpp
static wchar_t period_start_char();
```
--------------------------------
### Main Function and Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp20/channels/throttling_proxy.cpp
Parses command-line arguments for listen and target endpoints, sets up the io_context, resolver, and acceptor, and starts the listening coroutine. Includes basic error handling for incorrect usage and exceptions.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 5)
{
std::cerr << "Usage: throttling_proxy";
std::cerr << " ";
std::cerr << " \n";
return 1;
}
io_context ctx;
auto listen_endpoint =
*tcp::resolver(ctx).resolve(argv[1], argv[2],
tcp::resolver::passive).begin();
auto target_endpoint =
*tcp::resolver(ctx).resolve(argv[3], argv[4]).begin();
tcp::acceptor acceptor(ctx, listen_endpoint);
co_spawn(ctx, listen(acceptor, target_endpoint), detached);
ctx.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
```
--------------------------------
### Get Local DST Start Day
Source: https://www.boost.org/doc/libs/latest/boost/date_time/dst_rules.hpp
Retrieves the date of the DST start for a given year.
```C++
static date_type local_dst_start_day(year_type year)
{
return dst_traits::local_dst_start_day(year);
}
```
--------------------------------
### Main Function: HTTP Server Setup and Run
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/http/server/async-local/http_server_async_local.cpp
Entry point for the HTTP server. Parses command-line arguments, sets up the io_context, creates a listener, and starts the server threads.
```C++
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 4)
{
std::cerr <<
"Usage: http-server-async-local \n" <<
"Example:\n" <<
" http-server-async-local /tmp/http.sock . 1\n";
return EXIT_FAILURE;
}
auto const path = argv[1];
auto const doc_root = std::make_shared(argv[2]);
auto const threads = std::max(1, std::atoi(argv[3]));
// The io_context is required for all I/O
net::io_context ioc{threads};
// Remove previous binding
std::remove(path);
// Create and launch a listening port
std::make_shared(
ioc,
stream_protocol::endpoint{path},
doc_root)->run();
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
return EXIT_SUCCESS;
}
catch(std::exception const& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}
```
--------------------------------
### Main Function and IO Context Setup
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/websocket/server/awaitable/websocket_server_awaitable.cpp
Sets up the Boost.Asio IO context, parses command-line arguments for address, port, and thread count, and starts the server. It also manages a pool of threads to run the IO context.
```cpp
int
main(int argc, char* argv[])
{
// Check command line arguments.
if(argc != 4)
{
std::cerr
<< "Usage: websocket-server-awaitable \n"
<< "Example:\n"
<< " websocket-server-awaitable 0.0.0.0 8080 1\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const threads = std::max(1, std::atoi(argv[3]));
// The io_context is required for all I/O
net::io_context ioc(threads);
// Spawn a listening port
net::co_spawn(
ioc,
do_listen(net::ip::tcp::endpoint{ address, port }),
[](std::exception_ptr e)
{
if(e)
{
try
{
std::rethrow_exception(e);
}
catch(std::exception const& e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
}
});
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back([&ioc] { ioc.run(); });
ioc.run();
return EXIT_SUCCESS;
}
#else
int
main(int, char*[])
{
std::printf("awaitables require C++20\n");
return EXIT_FAILURE;
}
#endif
```
--------------------------------
### Get Start Index of index_range
Source: https://www.boost.org/doc/libs/latest/doc/html/MultiArray.html
Retrieve the start index of an index_range object. If the start index is not specified, it returns the provided default value idx.
```cpp
i.start()
```
```cpp
i.get_start(idx)
```
--------------------------------
### Main Function and Server Initialization
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp11/handler_tracking/async_tcp_echo_server.cpp
Sets up the Boost.Asio io_context, initializes the server with a specified port, and runs the event loop.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: async_tcp_echo_server \n";
return 1;
}
boost::asio::io_context io_context;
server s(io_context, std::atoi(argv[1]));
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
```
--------------------------------
### DST Start Date Rule Examples
Source: https://www.boost.org/doc/libs/latest/doc/html/doxygen/date_time_reference/classboost_1_1date__time_1_1tz__db__base.html
Provides examples of the specially formatted strings used to define Daylight Saving Time start dates. These rules specify the 'nth' weekday of a given month for the transition.
```text
"-1;5;9"="Last Friday of September"
"2;1;3"="Second Monday of March"
```
--------------------------------
### Get DST start day
Source: https://www.boost.org/doc/libs/latest/doc/html/doxygen/date_time_reference/structboost_1_1date__time_1_1acst__dst__trait.html
Retrieves the day of the week for the start of Daylight Saving Time for a given year.
```cpp
static day_of_week_type start_day(year_type);
```
--------------------------------
### Install Boost Binaries
Source: https://www.boost.org/doc/libs/latest/more/getting_started/unix-variants.html
Build and install the Boost libraries to the configured installation prefix. The binaries will be located in the `lib/` subdirectory.
```bash
$ ./b2 install
```
--------------------------------
### Hello, World! Example with Boost.Xpressive
Source: https://www.boost.org/doc/libs/latest/doc/html/xpressive/user_s_guide.html
Demonstrates basic usage of Boost.Xpressive for string matching and capturing groups. Requires including and using the boost::xpressive namespace.
```cpp
#include
#include
using namespace boost::xpressive;
int main()
{
std::string hello( "hello world!" );
sregex rex = sregex::compile( "(\w+) (\w+)!" );
smatch what;
if( regex_match( hello, what, rex ) )
{
std::cout << what[0] << '\n'; // whole match
std::cout << what[1] << '\n'; // first capture
std::cout << what[2] << '\n'; // second capture
}
return 0;
}
```
```text
hello world!
hello
world
```
--------------------------------
### Get Week Start Character
Source: https://www.boost.org/doc/libs/latest/doc/html/doxygen/date_time_reference/classboost_1_1date__time_1_1iso__format__base_3_01wchar__t_01_4.html
Returns the character used in mixed strings to identify the start of a week number.
```cpp
static wchar_t week_start_char();
```
--------------------------------
### Lazy Generator Example Setup
Source: https://www.boost.org/doc/libs/latest/libs/spirit/doc/html/spirit/karma/reference/auxiliary/lazy.html
Includes and using declarations required for Boost.Spirit Karma lazy generator examples.
```c++
#include
#include
#include
#include
#include
#include
#include
#include
namespace karma = boost::spirit::karma;
using boost::spirit::karma::_1;
using boost::spirit::ascii::string;
using boost::phoenix::val;
```
--------------------------------
### Main Function for Server Setup
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/websocket/server/stackless-ssl/websocket_server_stackless_ssl.cpp
The main function initializes the server, sets up the IO context, SSL context, and loads the server certificate. It then creates a listener to accept connections and starts the IO context on multiple threads.
```cpp
int main(int argc, char* argv[])
{
// Check command line arguments.
if (argc != 4)
{
std::cerr <<
"Usage: websocket-server-async-ssl \n" <<
"Example:\n" <<
" websocket-server-async-ssl 0.0.0.0 8080 1\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const threads = std::max(1, std::atoi(argv[3]));
// The io_context is required for all I/O
net::io_context ioc{threads};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
// This holds the self-signed certificate used by the server
load_server_certificate(ctx);
// Create and launch a listening port
std::make_shared(ioc, ctx, tcp::endpoint{address, port})->run();
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
return EXIT_SUCCESS;
}
```
--------------------------------
### Get Time Start Character
Source: https://www.boost.org/doc/libs/latest/doc/html/doxygen/date_time_reference/classboost_1_1date__time_1_1iso__format__base_3_01wchar__t_01_4.html
Returns the character used to denote the start of the time portion in mixed date-time strings.
```cpp
static wchar_t time_start_char();
```
--------------------------------
### Example Jayne.txt Content
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
This is the content for the 'jayne.txt' file used in the example.
```text
To: George Shmidlap
From: Rita Marlowe
Subject: Will Success Spoil Rock Hunter?
---
See subject.
```
--------------------------------
### Main Function for Server Setup and Execution
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/http/server/stackless-ssl/http_server_stackless_ssl.cpp
Sets up the Boost.Asio I/O context, SSL context, and listener. Parses command-line arguments for address, port, document root, and thread count. Launches the server and manages worker threads.
```cpp
int main(int argc, char* argv[])
{
// Check command line arguments.
if (argc != 5)
{
std::cerr <<
"Usage: http-server-stackless-ssl \n" <<
"Example:\n" <<
" http-server-stackless-ssl 0.0.0.0 8080 . 1\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const doc_root = std::make_shared(argv[3]);
auto const threads = std::max(1, std::atoi(argv[4]));
// The io_context is required for all I/O
net::io_context ioc{threads};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
// This holds the self-signed certificate used by the server
load_server_certificate(ctx);
// Create and launch a listening port
std::make_shared(
ioc,
ctx,
tcp::endpoint{address, port},
doc_root)->run();
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
return EXIT_SUCCESS;
}
```
--------------------------------
### Getting the remote endpoint with error handling
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/reference/basic_stream_socket/remote_endpoint/overload2.html
Example demonstrating how to get the remote endpoint of a TCP socket and check for errors.
```cpp
boost::asio::ip::tcp::socket socket(my_context);
...
bboost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec);
if (ec)
{
// An error occurred.
}
```
--------------------------------
### Example Placeholder Usage
Source: https://www.boost.org/doc/libs/latest/more/getting_started.html
This example demonstrates the use of italicized text in examples as a descriptive placeholder for user-provided information.
```bash
$ echo "My name is _your name_"
```
--------------------------------
### File System Initialization and Command Table Setup
Source: https://www.boost.org/doc/libs/latest/libs/multi_index/example/composite_keys.cpp
Initializes the file system with sample data and populates the command table with available commands. This sets up the environment for the command-line interface simulation.
```C++
/* table of commands, a map from command names to class command pointers */
typedef std::map command_table;
static command_table cmt;
int main()
{
/* fill the file system with some data */
file_system::iterator it0,it1;
fs.insert(file_entry("usr.cfg",240,false,0));
fs.insert(file_entry("memo.txt",2430,false,0));
it0=fs.insert(file_entry("dev",0,true,0)).first;
fs.insert(file_entry("tty0",128,false,&*it0));
fs.insert(file_entry("tty1",128,false,&*it0));
it0=fs.insert(file_entry("usr",0,true,0)).first;
it1=fs.insert(file_entry("bin",0,true,&*it0)).first;
fs.insert(file_entry("bjam",172032,false,&*it1));
it0=fs.insert(file_entry("home",0,true,0)).first;
it1=fs.insert(file_entry("andy",0,true,&*it0)).first;
fs.insert(file_entry("logo.jpg",5345,false,&*it1)).first;
fs.insert(file_entry("foo.cpp",890,false,&*it1)).first;
fs.insert(file_entry("foo.hpp",93,false,&*it1)).first;
fs.insert(file_entry("foo.html",750,false,&*it1)).first;
fs.insert(file_entry("a.obj",12302,false,&*it1)).first;
fs.insert(file_entry(".bash_history",8780,false,&*it1)).first;
it1=fs.insert(file_entry("rachel",0,true,&*it0)).first;
fs.insert(file_entry("test.py",650,false,&*it1)).first;
fs.insert(file_entry("todo.txt",241,false,&*it1)).first;
fs.insert(file_entry(".bash_history",9510,false,&*it1)).first;
/* fill the command table */
cmt["cd"] =&cd;
cmt["ls"] =&ls;
cmt["mkdir"]=&mkdir;
/* main looop */
for(;;){
/* print out the current directory and the prompt symbol */
if(current_dir)std::cout<name;
std::cout=">";
/* get an input line from the user: if empty, exit the program */
std::string com;
std::getline(std::cin,com);
command_tokenizer tok(com,boost::char_separator(" \t\n"));
if(tok.begin()==tok.end())break; /* null command, exit */
/* select the corresponding command and execute it */
command_table::iterator it=cmt.find(*tok.begin());
if(it==cmt.end()){
std::cout<<"invalid command"<second->execute(boost::next(tok.begin()),tok.end());
}
return 0;
}
```
--------------------------------
### Results Report Start Notification
Source: https://www.boost.org/doc/libs/latest/libs/test/doc/html/doxygen/a01004.html
Called at the beginning of a results report. Implement to perform any setup required before reporting starts.
```cpp
virtual void results_report_start(std::ostream & ostr) = 0;
```
--------------------------------
### iota Example
Source: https://www.boost.org/doc/libs/latest/boost/compute/algorithm/iota.hpp
This example demonstrates how to use the `iota` algorithm to fill a vector with sequential values starting from 0. The `iota` function is called with iterators defining the range and the starting value. The result is a vector containing 0, 1, 2, and so on.
```cpp
// Fill vector 'vec' with values 0, 1, 2, ...
boost::compute::iota(vec.begin(), vec.end(), (cl_int)0, queue);
```
--------------------------------
### Example Session: With Options and Positional Arguments
Source: https://www.boost.org/doc/libs/latest/doc/html/program_options/tutorial.html
Illustrates a complex command line with various options, including short and long forms for include paths, and positional arguments for input files.
```bash
$ **bin/gcc/debug/options_description --optimization 4 -I foo -I another/path --include-path third/include/path a.cpp b.cpp**
Include paths are: foo another/path third/include/path
Input files are: a.cpp b.cpp
Optimization level is 4
```
--------------------------------
### Example b2 Invocation on Windows
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
An example of a command-line session to build Boost libraries on Windows, specifying build directory, build type, and toolset.
```bash
C:\WINDOWS> cd `C:\Program Files\boost\`boost_1_82_0`
`C:\Program Files\boost\`boost_1_82_0`> b2 **^**
More? **--build-dir=**"C:\Documents and Settings\dave\build-boost" **^**
More? **--build-type=complete** **msvc** stage
```
--------------------------------
### date_time_duration::start
Source: https://www.boost.org/doc/libs/latest/libs/locale/doc/html/date__time_8hpp_source.html
Gets the starting point of the date_time_duration.
```APIDOC
## start
### Description
Gets the starting point of the date_time_duration.
### Signature
```cpp
const date_time & start() const
```
### Returns
A const reference to the starting `date_time` object.
```
--------------------------------
### Client Main Function and Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp11/porthopper/client.cpp
Sets up the Boost.Asio io_context, resolves the server host and port, and establishes a TCP control connection. It also creates a UDP socket for receiving data.
```cpp
#include
#include
#include
#include
#include
#include
#include
#include
#include "protocol.hpp"
using boost::asio::ip::tcp;
using boost::asio::ip::udp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: client \n";
return 1;
}
using namespace std;
std::string host_name = argv[1];
std::string port = argv[2];
boost::asio::io_context io_context;
tcp::resolver resolver(io_context);
tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin();
tcp::socket control_socket(io_context);
control_socket.connect(remote_endpoint);
udp::socket data_socket(io_context, udp::endpoint(udp::v4(), 0));
udp::endpoint data_endpoint = data_socket.local_endpoint();
control_request start = control_request::start(data_endpoint.port());
boost::asio::write(control_socket, start.to_buffers());
unsigned long last_frame_number = 0;
for (;;)
{
for (int i = 0; i < 50; ++i)
{
frame f;
data_socket.receive(f.to_buffers(), 0);
if (f.number() > last_frame_number)
{
last_frame_number = f.number();
std::cout << "\n" << f.payload();
}
}
std::cout << " Starting renegotiation";
udp::socket new_data_socket(io_context, udp::endpoint(udp::v4(), 0));
udp::endpoint new_data_endpoint = new_data_socket.local_endpoint();
control_request change =
control_request::change(data_endpoint.port(), new_data_endpoint.port());
boost::system::error_code control_result;
boost::asio::async_write(control_socket, change.to_buffers(),
[&](boost::system::error_code ec, std::size_t /*length*/)
{
control_result = ec;
});
frame f1;
boost::system::error_code new_data_socket_result;
new_data_socket.async_receive(f1.to_buffers(),
[&](boost::system::error_code ec, std::size_t /*length*/)
{
new_data_socket_result = ec;
if (!ec)
{
data_socket.close();
}
});
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
```
--------------------------------
### deque_tie Usage Example
Source: https://www.boost.org/doc/libs/latest/libs/fusion/doc/html/fusion/container/generation/metafunctions/deque_tie.html
An example demonstrating how to use result_of::deque_tie to get the type of a deque containing references to an int and a double.
```cpp
result_of::deque_tie::type
```
--------------------------------
### Boost.Asio connect example
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/reference/connect/overload4.html
Example demonstrating how to use Boost.Asio's 'connect' function to establish a socket connection to a sequence of endpoints and handle potential errors.
```cpp
tcp::resolver r(my_context);
tcp::resolver::query q("host", "service");
tcp::resolver::results_type e = r.resolve(q);
tcp::socket s(my_context);
boost::system::error_code ec;
boost::asio::connect(s, e.begin(), e.end(), ec);
if (ec)
{
// An error occurred.
}
```
--------------------------------
### Example Build Action Message
Source: https://www.boost.org/doc/libs/latest/more/getting_started/windows.html
This is an example of a build action message that may appear during the Boost build process.
```text
_toolset-name_.c++ _long_/_path_/_to_/_file_/_being_/_built_
```
--------------------------------
### Get Device Info Example (Auto Type)
Source: https://www.boost.org/doc/libs/latest/libs/compute/doc/html/doxygen/header_reference/classboost_1_1compute_1_1device.html
Example of how to retrieve device information where the return type is automatically deduced by the template.
```cpp
device.get_info();
```
--------------------------------
### Configure Client and Publish Message
Source: https://www.boost.org/doc/libs/latest/libs/mqtt5/doc/html/mqtt5/intro.html
Illustrates configuring an MQTT 5 client, connecting to a broker, and publishing a "Hello World!" message with QoS 0. Ensure you replace placeholders like '', '', '', '', and '' with your actual values.
```cpp
#include
#include
#include
#include
#include
#include
int main() {
boost::asio::io_context ioc;
boost::mqtt5::mqtt_client c(ioc);
c.brokers("", 1883)
.credentials("", "", "")
.async_run(boost::asio::detached);
c.async_publish(
"", "Hello world!",
boost::mqtt5::retain_e::no, boost::mqtt5::publish_props {},
[&c](boost::mqtt5::error_code ec) {
std::cout << ec.message() << std::endl;
c.async_disconnect(boost::asio::detached); // disconnect and close the Client
}
);
ioc.run();
}
```
--------------------------------
### Placeholder in Command Line Example
Source: https://www.boost.org/doc/libs/latest/more/getting_started/index.html
Illustrates the use of italicized text in command-line examples as a placeholder for user-provided information.
```bash
**$** echo "My name is _your name_"
```
--------------------------------
### Build Action Message Example
Source: https://www.boost.org/doc/libs/latest/more/getting_started/unix-variants.html
An example of a build action message that might appear during the Boost build process.
```shell
_toolset-name_.c++ _long_/_path_/_to_/_file_/_being_/_built_
```
--------------------------------
### Main Function and Client Initialization
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp11/http/client/async_client.cpp
Sets up the Boost.Asio io_context and initializes the asynchronous HTTP client. Handles command-line arguments for server and path.
```cpp
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cout << "Usage: async_client \n";
std::cout << "Example:\n";
std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n";
return 1;
}
boost::asio::io_context io_context;
client c(io_context, argv[1], argv[2]);
io_context.run();
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
```
--------------------------------
### Getting the local endpoint of a TCP acceptor
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/reference/basic_socket_acceptor/local_endpoint/overload1.html
Example demonstrating how to get the local endpoint of a boost::asio::ip::tcp::acceptor.
```cpp
boost::asio::ip::tcp::acceptor acceptor(my_context);
...
boost::asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint();
```
--------------------------------
### Main Function Setup and Execution
Source: https://www.boost.org/doc/libs/latest/doc/html/boost_asio/example/cpp17/coroutines_ts/range_based_for.cpp
Sets up the Boost.Asio io_context, signal handling for graceful shutdown, a TCP acceptor on port 55555, and spawns the listener coroutine. It then runs the io_context to process events.
```cpp
int main()
{
try
{
boost::asio::io_context io_context(1);
boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto){ io_context.stop(); });
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
co_spawn(io_context, listener(std::move(acceptor)), detached);
io_context.run();
}
catch (std::exception& e)
{
std::printf("Exception: %s\n", e.what());
}
}
```
--------------------------------
### Get the first character of a decode_view
Source: https://www.boost.org/doc/libs/latest/doc/antora/url/reference/boost/urls/decode_view/front.html
This example shows how to get the first character of a decoded URL string view using `front()`.
```cpp
assert( decode_view( "Program%20Files" ).front() == 'P' );
```
--------------------------------
### Main Server Loop and Initialization
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/websocket/server/sync-ssl/websocket_server_sync_ssl.cpp
This is the main function that sets up the server. It parses command-line arguments for address and port, initializes the io_context and SSL context, loads the server certificate, and then enters an infinite loop to accept incoming connections and launch new sessions in separate threads.
```cpp
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 3)
{
std::cerr <<
"Usage: websocket-server-sync-ssl \n" <<
"Example:\n" <<
" websocket-server-sync-ssl 0.0.0.0 8080\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
// The io_context is required for all I/O
net::io_context ioc{1};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
// This holds the self-signed certificate used by the server
load_server_certificate(ctx);
// The acceptor receives incoming connections
tcp::acceptor acceptor{ioc, {address, port}};
for(;;)
{
// This will receive the new connection
tcp::socket socket{ioc};
// Block until we get a connection
acceptor.accept(socket);
// Launch the session, transferring ownership of the socket
std::thread(
&do_session,
std::move(socket),
std::ref(ctx)).detach();
}
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
```
--------------------------------
### Foldr Example Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/metaparse/reference.html
Provides a minimal setup for using the foldr combinator, defining an integer token and a sum operation metafunction.
```c++
using int_token = token;
using sum_op = mpl::lambda>::type;
```
--------------------------------
### Boost Hash Map Example
Source: https://www.boost.org/doc/libs/latest/libs/uuid/doc/html/uuid.html
Example demonstrating the use of UUIDs as keys in a boost::unordered_flat_map.
```cpp
boost::unordered_flat_map hash_map;
```
--------------------------------
### Main Server Entry Point
Source: https://www.boost.org/doc/libs/latest/libs/beast/example/advanced/server-flex/advanced_server_flex.cpp
Parses command-line arguments for address, port, document root, and thread count. Initializes the io_context, SSL context, loads the server certificate, and starts the listener. Sets up signal handling for graceful shutdown.
```cpp
int main(int argc, char* argv[])
{
// Check command line arguments.
if (argc != 5)
{
std::cerr <<
"Usage: advanced-server-flex \n" <<
"Example:\n" <<
" advanced-server-flex 0.0.0.0 8080 . 1\n";
return EXIT_FAILURE;
}
auto const address = net::ip::make_address(argv[1]);
auto const port = static_cast(std::atoi(argv[2]));
auto const doc_root = std::make_shared(argv[3]);
auto const threads = std::max(1, std::atoi(argv[4]));
// The io_context is required for all I/O
net::io_context ioc{threads};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
// This holds the self-signed certificate used by the server
load_server_certificate(ctx);
// Create and launch a listening port
std::make_shared(
ioc,
ctx,
tcp::endpoint{address, port},
doc_root)->run();
// Capture SIGINT and SIGTERM to perform a clean shutdown
net::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait(
[&](beast::error_code const&, int)
{
// Stop the `io_context`. This will cause `run()`
// to return immediately, eventually destroying the
// `io_context` and all of the sockets in it.
ioc.stop();
});
// Run the I/O service on the requested number of threads
std::vector v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
// (If we get here, it means we got a SIGINT or SIGTERM)
// Block until all the threads exit
for(auto& t : v)
t.join();
return EXIT_SUCCESS;
}
```
--------------------------------
### Get Device Info Example (CL_DEVICE_MAX_COMPUTE_UNITS)
Source: https://www.boost.org/doc/libs/latest/libs/compute/doc/html/doxygen/header_reference/classboost_1_1compute_1_1device.html
Example of how to retrieve the maximum number of compute units for a device using `get_info` with a specific type.
```cpp
device.get_info(CL_DEVICE_MAX_COMPUTE_UNITS);
```
--------------------------------
### In-place Construction Framework Example
Source: https://www.boost.org/doc/libs/latest/libs/utility/doc/html/utility/utilities/in_place_factory.html
A simplified example demonstrating the core idea of the In-place Factory framework, where a container uses a factory to construct an object directly in its storage.
```cpp
struct C
{
template
C ( InPlaceFactory const& aFactory )
:
contained_ ( uninitialized_storage() )
{
aFactory.template apply(contained_);
}
~C()
{
contained_ -> X::~X();
delete[] contained_ ;
}
char* uninitialized_storage() { return new char[sizeof(X)] ; }
char* contained_ ;
};
void foo()
{
C c( in_place(123,"hello") ) ;
}
```
--------------------------------
### foldl_reject_incomplete_start_with_parser Example Setup
Source: https://www.boost.org/doc/libs/latest/doc/html/metaparse/reference.html
Sets up example parsers and operations for demonstrating foldl_reject_incomplete_start_with_parser, including integer tokens, plus tokens, and a sum operation.
```c++
using int_token = token;
using plus_token = token>;
using plus_int = last_of;
using sum_op = mpl::lambda>::type;
```