text:
@extends('layouts.base')

@section('body')

    landscape->size_1280x720 }}" class="intro introhalf">

{{ titleCase($slug) }} Representatives

117th United States Congress - U.S. House of Representatives

                                Home

                            <meta itemprop="position" content="1" />

                                U.S. House

                            <meta itemprop="position" content="2" />

                                {{ titleCase($slug) }} Representatives

                            <meta itemprop="position" content="3" />

{{ titleCase($slug) }} Representatives

There are 435 Representatives, who sit in congressional districts which are allocated to each of the 50 U.S states. This is a list of the current {{ titleCase($slug) }} Representatives's of the United States House of Representatives (117th United States Congress).

                @foreach ($representatives as $key => $representative)
                    @if (count($representatives) === 1)
                      @include('partials.representatives', [
                        'representatives' => $representatives,
                        'classes' => 'col-md-6 col-sm-6 col-md-offset-3',
                        'offset' => '',
                        'key' => $key
                      ])
                    @elseif(count($representatives) === 2)
                      @include('partials.representatives', [
                        'representatives' => $representatives,
                        'classes' => 'col-md-4 col-sm-6',
                        'offset' => 'col-md-offset-2',
                        'key' => $key
                      ])
                    @elseif(count($representatives) === 3)
                      @include('partials.representatives', [
                        'representatives' => $representatives,
                        'classes' => 'col-md-2 col-sm-6',
                        'offset' => 'col-md-offset-3',
                        'key' => $key
                      ])
                    @elseif(count($representatives) === 4)
                      @include('partials.representatives', [
                        'representatives' => $representatives,
                        'classes' => 'col-md-2 col-sm-6',
                        'offset' => 'col-md-offset-2',
                        'key' => $key
                      ])
                    @elseif(count($representatives) >= 5)
                      @include('partials.representatives', [
                        'representatives' => $representatives,
                        'classes' => 'col-md-2 col-sm-6',
                        'offset' => 'col-md-offset-1',
                        'key' => $key
                      ])
                    @endif
                @endforeach

U.S. House of Representatives

Select a State to access Government & Demographic data on the 117th United States House of Representatives. Contact Information includes Phone Number, Mailing Address, Official Website, Twitter & Facebook Accounts.

- Civil Services Team

                    @include('partials.map', ['base' => '/us-house'])

    @include('partials.house-lists')

@endsection


text:
package api

import (
    "apiGO/config"
    "apiGO/filter"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "net/rpc"
)

// Performs a call to the RPC server using the appropriate data extracted from the HTTP request,
// which is stored in the specific API variable
func PerformClientCall(handlerName string, rw http.ResponseWriter, req *http.Request, route *config.Route) {
    client, err := rpc.DialHTTP(config.Protocol, config.RpcServerAddress)
    defer closeClient(client)

    if err != nil {
        GiveApiMessage(http.StatusInternalServerError, err.Error(), rw)
        return
    }

    vars := createApiVars(route, req, rw)

    if vars == nil {
        return
    }

    resp := &ApiResponse{}

    err = client.Call(handlerName, vars, resp)

    // Log requests and an eventual error messages
    log.Println(req.Method, route.Pattern, resp.StatusCode, resp.ErrorMessage)

    // Treat RPC call error separately
    if err != nil {
        GiveApiMessage(resp.StatusCode, err.Error(), rw)
        return
    }

    // If a content type is specified, write it to the response header
    if len(resp.ContentType) > 0 {
        rw.Header().Add("Content-type", resp.ContentType)
    }

    // Give appripriate http response depending on the status of the processed request
    if resp.ErrorMessage != "" {
        GiveApiMessage(resp.StatusCode, resp.ErrorMessage, rw)
    } else {
        GiveApiResponse(resp.StatusCode, resp.Message, rw)
    }
}

// Close an opened RPC client
func closeClient(client *rpc.Client) {
    err := client.Close()
    if err != nil {
        log.Panic("Error in closing client connection: ", err.Error())
    }
}

// Create the specialized API variable filled with data that is
// extracted from the HTTP request made to the server
func createApiVars(route *config.Route, req *http.Request, rw http.ResponseWriter) *ApiVar {
    err, statusCode := filter.CheckMethodAndParseContent(req)
    if err != nil {
        GiveApiMessage(statusCode, err.Error(), rw)
        return nil
    }

    body, err := convertBodyToReadableFormat(req.Body)
    if err != nil {
        GiveApiMessage(http.StatusBadRequest, err.Error(), rw)
        return nil
    }

    vars := &ApiVar{
        Route:                *route,
        RequestMethod:        req.Method,
        RequestHeader:        req.Header,
        RequestForm:          req.Form,
        RequestContentLength: req.ContentLength,
        RequestBody:          body,
        BasicAuth:            parseBasicAuthData(req),
    }

    return vars
}

// Converts the http request body from an io.ReadCloser to an array
// of bytes, which can then be serialized and deserialized
func convertBodyToReadableFormat(data io.ReadCloser) ([]byte, error) {
    body, err := ioutil.ReadAll(data)

    return body, err
}

// Prepare the Basic Authentication details into a data transport type
func parseBasicAuthData(req *http.Request) BasicAuthentication {
    username, password, ok := req.BasicAuth()

    basicAuth := BasicAuthentication{
        OK:       ok,
        Username: username,
        Password: password,
    }

    return basicAuth
}

redpajama_set_name: RedPajamaGithub


text:
_This document is part of the more general
[Chromium C++ style guide](https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/c++.md).
It summarizes the supported state of new and updated language and library
features in recent C++ standards and the [Abseil](https://abseil.io/about/)
library. This guide applies to both Chromium and its subprojects, though
subprojects can choose to be more restrictive if necessary for toolchain
support._

The C++ language has in recent years received an updated standard every three
years (C++11, C++14, etc.). For various reasons, Chromium does not immediately
allow new features on the publication of such a standard. Instead, once
Chromium supports the toolchain to a certain extent (e.g., build support is
ready), a standard is declared "_initially supported_", with new
language/library features banned pending discussion but not yet allowed.

You can propose changing the status of a feature by sending an email to
[cxx@chromium.org](https://groups.google.com/a/chromium.org/forum/#!forum/cxx).
Include a short blurb on what the feature is and why you think it should or
should not be allowed, along with links to any relevant previous discussion. If
the list arrives at some consensus, send a codereview to change this file
accordingly, linking to your discussion thread.

If an item remains on the TBD list two years after initial support is added,
style arbiters should explicitly move it to an appropriate allowlist or
blocklist, allowing it if there are no obvious reasons to ban.

The current status of existing standards and Abseil features is:

*   **C++11:** _Default allowed; see banned features below_
*   **C++14:** _Default allowed; see banned features below_
*   **C++17:** Initially supported December 23, 2021; see allowed/banned/TBD
    features below
*   **C++20:** _Not yet supported in Chromium_
*   **C++23:** _Not yet standardized_
*   **Abseil:** _Default allowed; see banned/TBD
    features below_
    *   absl::Cleanup: Initially supported February 4, 2021
    *   absl::AnyInvocable: Initially supported June 20, 2022
    *   Log library: Initially supported Aug 31, 2022

[TOC]

## C++11 Banned Language Features {#core-blocklist-11}

The following C++11 language features are not allowed in the Chromium codebase.

### Inline Namespaces [banned]

```c++
inline namespace foo { ... }
```

**Description:** Allows better versioning of namespaces.

**Documentation:**
[Inline namespaces](https://en.cppreference.com/w/cpp/language/namespace#Inline_namespaces)

**Notes:**
*** promo
Banned in the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#Namespaces).
Unclear how it will work with components.
***

### long long Type [banned]

```c++
long long var = value;
```

**Description:** An integer of at least 64 bits.

**Documentation:**
[Fundamental types](https://en.cppreference.com/w/cpp/language/types)

**Notes:**
*** promo
Use a stdint.h type if you need a 64-bit number.
[Discussion thread](https://groups.google.com/a/chromium.org/forum/#!topic/chromium-dev/RxugZ-pIDxk)
***

### User-Defined Literals [banned]

```c++
type var = literal_value_type;
```

**Description:** Allows user-defined literal expressions.

**Documentation:**
[User-defined literals](https://en.cppreference.com/w/cpp/language/user_literal)

**Notes:**
*** promo
Banned in the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading).
***

### thread_local Storage Class [banned]

```c++
thread_local int foo = 1;
```

**Description:** Puts variables into thread local storage.

**Documentation:**
[Storage duration](https://en.cppreference.com/w/cpp/language/storage_duration)

**Notes:**
*** promo
Some surprising effects on Mac
([discussion](https://groups.google.com/a/chromium.org/forum/#!topic/chromium-dev/2msN8k3Xzgs),
[fork](https://groups.google.com/a/chromium.org/forum/#!topic/cxx/h7O5BdtWCZw)).
Use `base::SequenceLocalStorageSlot` for sequence support, and
`base::ThreadLocal`/`base::ThreadLocalStorage` otherwise.
***

## C++11 Banned Library Features {#library-blocklist-11}

The following C++11 library features are not allowed in the Chromium codebase.

### Bind Operations [banned]

```c++
std::bind(function, args, ...)
```

**Description:** Declares a function object bound to certain arguments

**Documentation:**
[std::bind](https://en.cppreference.com/w/cpp/utility/functional/bind)

**Notes:**
*** promo
Use `base::Bind` instead. Compared to `std::bind`, `base::Bind` helps prevent
lifetime issues by preventing binding of capturing lambdas and by forcing
callers to declare raw pointers as `Unretained`.
[Discussion thread](https://groups.google.com/a/chromium.org/forum/#!topic/cxx/SoEj7oIDNuA)
***

### C Floating-Point Environment [banned]

```c++
#include <cfenv>
#include <fenv.h>
```

**Description:** Provides floating point status flags and control modes for
C-compatible code

**Documentation:**
[Standard library header "cfenv"](https://en.cppreference.com/w/cpp/header/cfenv)

**Notes:**
*** promo
Banned by the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#C++11)
due to concerns about compiler support.
***

### Date and time utilities [banned]

```c++
#include <chrono>
```

**Description:** A standard date and time library

**Documentation:**
[Date and time utilities](https://en.cppreference.com/w/cpp/chrono)

**Notes:**
*** promo
Overlaps with `Time` APIs in `base/`. Keep using the `base/` classes.
***

### Exceptions [banned]

```c++
#include <exception>
```

**Description:** Enhancements to exception throwing and handling

**Documentation:**
[Standard library header "exception"](https://en.cppreference.com/w/cpp/header/exception)

**Notes:**
*** promo
Exceptions are banned by the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#Exceptions)
and disabled in Chromium compiles. However, the `noexcept` specifier is
explicitly allowed.
[Discussion thread](https://groups.google.com/a/chromium.org/forum/#!topic/chromium-dev/8i4tMqNpHhg)
***

### Function Objects [banned]

```c++
std::function
```

**Description:** Wraps a standard polymorphic function

**Documentation:**
[std::function](https://en.cppreference.com/w/cpp/utility/functional/function)

**Notes:**
*** promo
Use `base::{Once,Repeating}Callback` instead. Compared to `std::function`,
`base::{Once,Repeating}Callback` directly supports Chromium's refcounting
classes and weak pointers and deals with additional thread safety concerns.
[Discussion thread](https://groups.google.com/a/chromium.org/forum/#!topic/cxx/SoEj7oIDNuA)
***

### Random Number Engines [banned]

*** aside
The random number engines defined in `<random>` (see separate item for random
number distributions), e.g.: `linear_congruential_engine`,
`mersenne_twister_engine`, `minstd_rand0`, `mt19937`, `ranlinux48`,
`random_device`
***

**Description:** Random number generation algorithms and utilities.

**Documentation:**
[Pseudo-random number generation](https://en.cppreference.com/w/cpp/numeric/random)

**Notes:**
*** promo
Do not use any random number engines from `<random>`. Instead, use
`base::RandomBitGenerator`.
[Discussion thread](https://groups.google.com/a/chromium.org/forum/#!topic/cxx/16Xmw05C-Y0)
***

### Ratio Template Class [banned]

```c++
std::ratio<numerator, denominator>
```

**Description:** Provides compile-time rational numbers

**Documentation:**
[std::ratio](https://en.cppreference.com/w/cpp/numeric/ratio/ratio)

**Notes:**
*** promo
Banned by the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#C++11)
due to concerns that this is tied to a more template-heavy interface style.
***

### Regular Expressions [banned]

```c++
#include <regex>
```

**Description:** A standard regular expressions library

**Documentation:**
[Regular expressions library](https://en.cppreference.com/w/cpp/regex)

**Notes:**
*** promo
Overlaps with many regular expression libraries in Chromium. When in doubt, use
`re2`.
***

### Shared Pointers [banned]

```c++
std::shared_ptr
```

**Description:** Allows shared ownership of a pointer through reference counts

**Documentation:**
[std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr)

**Notes:**
*** promo
Needs a lot more evaluation for Chromium, and there isn't enough of a push for
this feature.

*   [Google Style Guide](https://google.github.io/styleguide/cppguide.html#Ownership_and_Smart_Pointers).
*   [Discussion Thread](https://groups.google.com/a/chromium.org/forum/#!topic/cxx/aT2wsBLKvzI)
***

### String-Number Conversion Functions [banned]

```c++
std::stoi()
std::stol()
std::stoul()
std::stoll
std::stoull()
std::stof()
std::stod()
std::stold()
std::to_string()
```

**Description:** Converts strings to/from numbers

**Documentation:**
*   [std::stoi, std::stol, std::stoll](https://en.cppreference.com/w/cpp/string/basic_string/stol),
*   [std::stoul, std::stoull](https://en.cppreference.com/w/cpp/string/basic_string/stoul),
*   [std::stof, std::stod, std::stold](https://en.cppreference.com/w/cpp/string/basic_string/stof),
*   [std::to_string](https://en.cppreference.com/w/cpp/string/basic_string/to_string)

**Notes:**
*** promo
The string-to-number conversions rely on exceptions to communicate failure,
while the number-to-string conversions have performance concerns and depend on
the locale. Use the routines in `base/strings/string_number_conversions.h`
instead.
***

### Thread Library [banned]

*** aside
`<thread>` and related headers, including `<future>`, `<mutex>`,
`<condition_variable>`
***

**Description:** Provides a standard multithreading library using `std::thread`
and associates

**Documentation:**
[Thread support library](https://en.cppreference.com/w/cpp/thread)

**Notes:**
*** promo
Overlaps with many classes in `base/`. Keep using the `base/` classes for now.
`base::Thread` is tightly coupled to `MessageLoop` which would make it hard to
replace. We should investigate using standard mutexes, or unique_lock, etc. to
replace our locking/synchronization classes.
***

### Weak Pointers [banned]

```c++
std::weak_ptr
```

**Description:** Allows a weak reference to a `std::shared_ptr`

**Documentation:**
[std::weak_ptr](https://en.cppreference.com/w/cpp/memory/weak_ptr)

**Notes:**
*** promo
Banned because `std::shared_ptr` is banned.  Use `base::WeakPtr` instead.
***

## C++14 Banned Library Features {#library-blocklist-14}

The following C++14 library features are not allowed in the Chromium codebase.

### std::chrono literals [banned]

```c++
using namespace std::chrono_literals;
auto timeout = 30s;
```

**Description:** Allows `std::chrono` types to be more easily constructed.

**Documentation:**
[std::literals::chrono_literals::operator""s](https://en.cppreference.com/w/cpp/chrono/operator%22%22s)

**Notes:**
*** promo
Banned because `<chrono>` is banned.
***

## C++17 Allowed Language Features {#core-allowlist-17}

The following C++17 language features are allowed in the Chromium codebase.

### Nested namespaces [allowed]

```c++
namespace A::B::C { ...
```

**Description:** Using the namespace resolution operator to create nested
namespace definitions.

**Documentation:**
[Namespaces](https://en.cppreference.com/w/cpp/language/namespace)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/gLdR3apDSmg/)
***

### Template argument deduction for class templates [allowed]

```c++
template <typename T>
struct MyContainer {
  MyContainer(T val) : val{val} {}
  // ...
};
MyContainer c1(1);  // Type deduced to be `int`.
```

**Description:** Automatic template argument deduction much like how it's done
for functions, but now including class constructors.

**Documentation:**
[Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)

**Notes:**
*** promo
Usage is governed by the
[Google Style Guide](https://google.github.io/styleguide/cppguide.html#CTAD).
***

### Fold expressions [allowed]

```c++
template <typename... Args>
auto sum(Args... args) {
  return (... + args);
}
```

**Description:** A fold expression performs a fold of a template parameter pack
over a binary operator.

**Documentation:**
[Fold expression](https://en.cppreference.com/w/cpp/language/fold)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/4DTm3idXz0w/m/g_JjOh0wAgAJ)
***

### Selection statements with initializer [allowed]

```c++
if (int a = Func(); a < 3) { ...
switch (int a = Func(); a) { ...
```

**Description:** New versions of the if and switch statements which simplify
common code patterns and help users keep scopes tight.

**Documentation:**
[if statement](https://en.cppreference.com/w/cpp/language/if),
[switch statement](https://en.cppreference.com/w/cpp/language/switch)

**Notes:**
*** promo
[@cxx discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/4GP43nftePE)
***

### fallthrough attribute [allowed]

```c++
case 1:
  DoSomething();
  [[fallthrough]];
case 2:
  break;
```

**Description:**
The `[[fallthrough]]` attribute can be used in switch statements to indicate
when intentionally falling through to the next case.

**Documentation:**
[C++ attribute: fallthrough](https://en.cppreference.com/w/cpp/language/attributes/fallthrough)

**Notes:**
*** promo
See [discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/JrvyFd243QI).

See [migration task](https://bugs.chromium.org/p/chromium/issues/detail?id=1283907).
***

### constexpr if [allowed]

```c++
if constexpr (cond) { ...
```

**Description:** Write code that is instantiated depending on a compile-time
condition.

**Documentation:**
[if statement](https://en.cppreference.com/w/cpp/language/if)

**Notes:**
*** promo
See [discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/op2ePZnjP0w).
***

### nodiscard attribute [allowed]

```c++
struct [[nodiscard]] ErrorOrValue;
[[nodiscard]] bool DoSomething();
```

**Description:**
The `[[nodiscard]]` attribute can be used to indicate that

  - the return value of a function should not be ignored
  - values of annotated classes/structs/enums returned from functions should not
    be ignored

**Documentation:**
[C++ attribute: nodiscard](https://en.cppreference.com/w/cpp/language/attributes/nodiscard)

**Notes:**
*** promo
This replaces the previous `WARN_UNUSED_RESULT` macro, which was a wrapper
around the compiler-specific `__attribute__((warn_unused_result))`.

[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/nH7Ar8pZ1Dw/m/c90vGChvAAAJ)
***

### maybe_unused attribute [allowed]

```c++
struct [[maybe_unused]] MyUnusedThing;
[[maybe_unused]] int x;
```

**Description:**
The `[[maybe_unused]]` attribute can be used to indicate that individual
variables, functions, or fields of a class/struct/enum can be left unused.

**Documentation:**
[C++ attribute: maybe_unused](https://en.cppreference.com/w/cpp/language/attributes/maybe_unused)

**Notes:**
*** promo
See [discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/jPLfU5eRg8M/).
***

### Structured bindings [allowed]

```c++
const auto [x, y] = FuncReturningStdPair();
```

**Description:** Allows writing `auto [x, y, z] = expr;` where the type of
`expr` is a tuple-like object, whose elements are bound to the variables `x`,
`y`, and `z` (which this construct declares). Tuple-like objects include
`std::tuple`, `std::pair`, `std::array`, and aggregate structures.

**Documentation:**
[Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding)
[Explanation of structured binding types](https://jguegant.github.io/blogs/tech/structured-bindings.html)

**Notes:**
*** promo
In C++17, structured bindings don't work with lambda captures.
[C++20 will allow capturing structured bindings by value](https://wg21.link/p1091r3).

This feature forces omitting type names. Its use should follow
[the guidance around `auto` in Google C++ Style guide](https://google.github.io/styleguide/cppguide.html#Type_deduction).

See [discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/ExfSorNLNf4).
***

### Inline variables [allowed]

```c++
struct S {
  static constexpr int kZero = 0;  // constexpr implies inline here.
};

inline constexpr int kOne = 1;  // Explicit inline needed here.
```

**Description:** The `inline` specifier can be applied to variables as well as
to functions. A variable declared inline has the same semantics as a function
declared inline. It can also be used to declare and define a static member
variable, such that it does not need to be initialized in the source file.

**Documentation:**
[inline specifier](https://en.cppreference.com/w/cpp/language/inline)

**Notes:**
*** promo
Inline variables in anonymous namespaces in header files will still get one copy
per translation unit, so they must be outside of an anonymous namespace to be
effective.

Mutable inline variables and taking the address of inline variables are banned
since these will break the component build.

See [discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/hmyGFD80ocE/m/O4AXC93vAQAJ).
***

## C++17 Allowed Library Features {#library-allowlist-17}

The following C++17 language features are allowed in the Chromium codebase.

### Allocation functions with explicit alignment [allowed]

```c++
class alignas(32) Vec3d {
  double x, y, z;
};
auto p_vec = new Vec3d[10];  // 32-byte aligned in C++17, maybe not previously
```

**Description:** Performs heap allocation of objects whose alignment
requirements exceed `__STDCPP_DEFAULT_NEW_ALIGNMENT__`.

**Documentation:**
[operator new](https://en.cppreference.com/w/cpp/memory/new/operator_new)

**Notes:**
*** promo
None
***

### Type trait variable templates [allowed]

```c++
bool b = std::is_same_v<int, std::int32_t>;
```

**Description:** Syntactic sugar to provide convenient access to `::value`
members by simply adding `_v`.

**Documentation:**
[Type support](https://en.cppreference.com/w/cpp/types)

**Notes:**
*** promo
[Discussion thread](Non://groups.google.com/a/chromium.org/g/cxx/c/KEa-0AOGRNY/m/IV_S3_pvAAAJ)
***

### std::map::try_emplace [allowed]

```c++
std::map<std::string, std::string> m;
m.try_emplace("c", 10, 'c');
m.try_emplace("c", "Won't be inserted");
```

**Description:** Like `emplace`, but does not move from rvalue arguments if the
insertion does not happen.

**Documentation:**
[std::map::try_emplace](https://en.cppreference.com/w/cpp/container/map/try_emplace),

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/Uv2tUfIwUfQ/m/ffMxCk9uAAAJ)
***

### std::map::insert_or_assign [allowed]

```c++
std::map<std::string, std::string> m;
m.insert_or_assign("c", "cherry");
m.insert_or_assign("c", "clementine");
```

**Description:** Like `operator[]`, but returns more information and does not
require default-constructibility of the mapped type.

**Documentation:**
[std::map::insert_or_assign](https://en.cppreference.com/w/cpp/container/map/insert_or_assign)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/Uv2tUfIwUfQ/m/ffMxCk9uAAAJ)
***

### std::apply [allowed]

```c++
static_assert(std::apply(std::plus<>(), std::make_tuple(1, 2)) == 3);
```

**Description:** Invokes a `Callable` object with a tuple of arguments.

**Documentation:**
[std::apply](https://en.cppreference.com/w/cpp/utility/apply)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/cNZm_g39fyM)
***

### std::as_const [allowed]

```c++
auto&& const_ref = std::as_const(mutable_obj);
```

**Description:** Forms reference to const T.

**Documentation:**
[std::as_const](https://en.cppreference.com/w/cpp/utility/as_const)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/5Uo4iJK6Mf4)
***

### Non-member std::size/std::empty/std::data [allowed]

```c++
char buffer[260];
memcpy(std::data(buffer), source_str.data(), std::size(buffer));

if (!std::empty(container)) { ... }
```

**Description:** Non-member versions of what are often member functions on STL
containers. Primarily useful when:
- using `std::size()` as a replacement for the old `arraysize()` macro.
- writing code that needs to generically operate across things like
  `std::vector` and `std::list` (which provide `size()`, `empty()`, and `data()
  member functions), `std::array` and `std::initialize_list` (which only provide
  a subset of the aforementioned member functions), and regular arrays (which
  have no member functions at all).

**Documentation:**
[std::size](https://en.cppreference.com/w/cpp/iterator/size),
[std::empty](https://en.cppreference.com/w/cpp/iterator/empty),
[std::data](https://en.cppreference.com/w/cpp/iterator/data)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/58qlA3zk5ZI/m/7kKok65xAAAJ)

Prefer range-based for loops over `std::size()`: range-based for loops work even
for regular arrays.
***

### std::is_invocable [allowed]

```c++
std::is_invocable_v<Fn, 1, "Hello">
```

**Description:** Checks whether a function may be invoked with the given
argument types.  The `_r` variant also evaluates whether the result is
convertible to a given type.

**Documentation:**
[std::is_invocable](https://en.cppreference.com/w/cpp/types/is_invocable)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/YhlF_sTDSc0/m/QMzf42BtAAAJ)
***

### std::conjunction/std::disjunction/std::negation [allowed]

```c++
template<typename T, typename... Ts>
std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...>>
func(T, Ts...) { ...
```

**Description:** Performs logical operations on type traits.

**Documentation:**
[std::conjunction](https://en.cppreference.com/w/cpp/types/conjunction),
[std::disjunction](https://en.cppreference.com/w/cpp/types/disjunction),
[std::negation](https://en.cppreference.com/w/cpp/types/negation)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/YhlF_sTDSc0/m/QMzf42BtAAAJ)
***

### std::hardware_{constructive|destructive}_interference_size [allowed]

```c++
struct SharedData {
  ReadOnlyFrequentlyUsed data;
  alignas(std::hardware_destructive_interference_size) std::atomic<size_t> counter;
};
```

**Description:** The `std::hardware_destructive_interference_size` constant is
useful to avoid false sharing (destructive interference) between variables that
would otherwise occupy the same cacheline. In contrast,
`std::hardware_constructive_interference_size` is helpful to promote true
sharing (constructive interference), e.g. to support better locality for
non-contended data.

**Documentation:**
[std::hardware_destructive_interference_size](https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size),
[std::hardware_constructive_interference_size](https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/cwktrFxxUY4/m/sP-J-s61AQAJ)
***

## C++17 Banned Library Features {#library-blocklist-17}

The following C++17 library features are not allowed in the Chromium codebase.

### std::any [banned]

```c++
std::any x = 5;
```

**Description:** A type-safe container for single values of any type.

**Documentation:**
[std::any](https://en.cppreference.com/w/cpp/utility/any)

**Notes:**
*** promo
[Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/KEa-0AOGRNY/m/IV_S3_pvAAAJ)

Banned since workaround for lack of RTTI isn't compatible with the component
build ([Bug](https://crbug.com/1096380)). Also see `absl::any`.
***

### std::filesystem [banned]

```c++
#include <filesystem>
```

**Description:** A standard way to manipulate files, directories, and paths in a
filesystem.

**Documentation:**
[Filesystem library](https://en.cppreference.com/w/cpp/filesystem)

**Notes:**
*** promo
Banned by the [Google Style Guide](https://google.github.io/styleguide/cppguide.html#Other_Features).
***

### weak_from_this [banned]

```c++
auto weak_ptr = weak_from_this();
```

**Description:** Returns a `std::weak_ptr<T>` that tracks ownership of `*this`
by all existing `std::shared_ptr`s that refer to `*this`.

**Documentation:**
[std::enable_shared_from_this<T>::weak_from_this](https://en.cppreference.com/w/cpp/memory/enable_shared_from_this/weak_from_this)

**Notes:**
*** promo
Banned since `std::shared_ptr` and `std::weak_ptr` are banned.
***

### Transparent std::owner_less [banned]

```c++
std::map<std::weak_ptr<T>, U, std::owner_less<>>
```

**Description:** Function object providing mixed-type owner-based ordering of
shared and weak pointers, regardless of the type of the pointee.

**Documentation:**
[std::owner_less](https://en.cppreference.com/w/cpp/memory/owner_less)

**Notes:**
*** promo
Banned since `std::shared_ptr` and `std::weak_ptr` are banned.
***

### Array support for std::shared_ptr [banned]

```c++
std::shared_ptr<int[]> p(new int[10]{0,1,2,3,4,5,6,7,8,9});
std::cout << p[3];  // "3"
```

**Description:** Supports memory management of arrays via `std::shared_ptr`.

**Documentation:**
[std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr)

**Notes:**
*** promo
Banned since `std::shared_ptr` is banned.
***

### std::uncaught_exceptions [banned]

```c++
int count = std::uncaught_exceptions();
```

**Description:** Determines whether there are live exception objects.

**Documentation:**
[std::uncaught_exceptions](https://en.cppreference.com/w/cpp/error/uncaught_exception)

**Notes:**
*** promo
Banned because exceptions are banned.
***

### Rounding functions for duration and time_point [banned]

```c++
std::chrono::ceil<std::chrono::seconds>(dur);
std::chrono::ceil<std::chrono::seconds>(time_pt);
std::chrono::floor<std::chrono::seconds>(dur);
std::chrono::floor<std::chrono::seconds>(time_pt);
std::chrono::round<std::chrono::seconds>(dur);
std::chrono::round<std::chrono::seconds>(time_pt);
```

**Description:** Converts durations and time_points by rounding.

**Documentation:**
[std::chrono::duration](https://en.cppreference.com/w/cpp/chrono/duration),
[std::chrono::time_point](https://en.cppreference.com/w/cpp/chrono/time_point)

**Notes:**
*** promo
Banned since `std::chrono` is banned.
***

### std::variant [banned]

```c++
std::variant<int, double> v = 12;
```

**Description:** The class template `std::variant` represents a type-safe
`union`. An instance of `std::variant` at any given time holds a value of one of
its alternative types (it's also possible for it to be valueless).

**Documentation:**
[std::variant](https://en.cppreference.com/w/cpp/utility/variant)

**Notes:**
*** promo
Banned for now because it does not provide safety guarantees in the case of
misuse. The Chromium C++ team is investigating the possibility of hardening the
C++ library so that the standard version can be used. In the meanwhile, use
`absl::variant` instead.
***

### std::optional [banned]

```c++
std::optional<std::string> s;
```

**Description:** The class template `std::optional` manages an optional
contained value, i.e. a value that may or may not be present. A common use case
for optional is the return value of a function that may fail.

**Documentation:**
[std::optional](https://en.cppreference.com/w/cpp/utility/optional)

**Notes:**
*** promo
Banned for now because it does not provide safety guarantees in the case of
misuse. The Chromium C++ team is investigating the possibility of hardening the
C++ library so that the standard version can be used. In the meanwhile, use
`absl::optional` instead.
***

### std::in_place/in_place_type/in_place_index/in_place_t/in_place_type_t/in_place_index_t [banned]

```c++
std::optional<std::complex<double>> opt{std::in_place, 0, 1};
std::variant<int, float> v{std::in_place_type<int>, 1.4};
```

**Description:** The `std::in_place` are disambiguation tags for
`std::optional`, `std::variant`, and `std::any` to indicate that the object
should be constructed in-place.

**Documentation:**
[std::in_place](https://en.cppreference.com/w/cpp/utility/in_place)

**Notes:**
*** promo
Banned for now because `std::optional`, `std::variant`, and `std::any` are all
banned for now. Because `absl::optional` and `absl::variant` are used instead,
and they require `absl::in_place`, use `absl::in_place` for non-Abseil Chromium
code. See the
[discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/ZspmuJPpv6s/m/wYYTCiRwAAAJ).
***

### std::clamp [banned]

```c++
int x = std::clamp(inp, 0, 100);
```

**Description:** Clamps a value between a minimum and a maximum.

**Documentation:**
[std::clamp](https://en.cppreference.com/w/cpp/algorithm/clamp)

**Notes:**
*** promo
Banned for now because it does not provide safety guarantees in the case of
misuse. The Chromium C++ team is investigating the possibility of hardening the
C++ library so that the standard version can be used. In the meanwhile, use
`base::clamp` instead.
***

## C++17 TBD Language Features {#core-review-17}

The following C++17 language features are not allowed in the Chromium codebase.
See the top of this page on how to propose moving a feature from this list into
the allowed or banned sections.

### Declaring non-type template parameters with auto [tbd]

```c++
template <auto... seq>
struct my_integer_sequence {
  // ...
};
auto seq = my_integer_sequence<0, 1, 2>();  // Type deduced to be `int`.
```

**Description:** Following the deduction rules of `auto`, while respecting the
non-type template parameter list of allowable types, template arguments can be
deduced from the types of its arguments.

**Documentation:**
[Template parameters](https://en.cppreference.com/w/cpp/language/template_parameters)

**Notes:**
*** promo
None
***

### constexpr lambda [tbd]

```c++
auto identity = [](int n) constexpr { return n; };
static_assert(identity(123) == 123);
```

**Description:** Compile-time lambdas using constexpr.

**Documentation:**
[Lambda expressions](https://en.cppreference.com/w/cpp/language/lambda)

**Notes:**
*** promo
None
***

### Lambda capture this by value [tbd]

```c++
const auto l = [*this] { return member_; }
```

**Description:** `*this` captures the current object by copy, while `this`
continues to capture by reference.

**Documentation:**
[Lambda capture](https://en.cppreference.com/w/cpp/language/lambda#Lambda_capture)

**Notes:**
*** promo
None
***

### UTF-8 character literals [tbd]

```c++
char x = u8'x';
```

**Description:** A character literal that begins with `u8` is a character
literal of type `char`. The value of a UTF-8 character literal is equal to its
ISO 10646 code point value.

**Documentation:**
[Character literal](https://en.cppreference.com/w/cpp/language/character_literal)

**Notes:**
*** promo
C++20 changes the type to `char8_t`, causing migration hazards for code using
this.
***

### using declaration for attributes [tbd]

```c++
[[using CC: opt(1), debug]]  // same as [[CC:opt(1), CC::debug]]
```

**Description:** Specifies a common namespace for a list of attributes.

**Documentation:**
[Attribute specifier sequence](https://en.cppreference.com/w/cpp/language/attributes)

**Notes:**
*** promo
See similar attribute macros in base/compiler_specific.h.
***

### __has_include [tbd]

```c++
#if __has_include(<optional>) ...
```

**Description:** Checks whether a file is available for inclusion, i.e. the file
exists.

**Documentation:**
[Source file inclusion](https://en.cppreference.com/w/cpp/preprocessor/include)

**Notes:**
*** promo
None
***

## C++17 TBD Library Features {#library-review-17}

The following C++17 library features are not allowed in the Chromium codebase.
See the top of this page on how to propose moving a feature from this list into
the allowed or banned sections.

### std::string_view [tbd]

```c++
std::string_view str = "foo";
```

**Description:** A non-owning reference to a string. Useful for providing an
abstraction on top of strings (e.g. for parsing).

**Documentation:**
[std::basic_string_view](https://en.cppreference.com/w/cpp/string/basic_string_view)

**Notes:**
*** promo
See also `absl::string_view` and `base::StringPiece`.
***

### std::invoke [tbd]

```c++
static_assert(std::invoke(std::plus<>(), 1, 2) == 3);
```

**Description:** Invokes a `Callable` object with parameters. An example of a
`Callable` object is `base::Callback` where an object can be called similarly to
a regular function.

**Documentation:**
[std::invoke](https://en.cppreference.com/w/cpp/utility/functional/invoke)

**Notes:**
*** promo
See also `base::invoke`.
***

### std::byte [tbd]

```c++
std::byte b = 0xFF;
int i = std::to_integer<int>(b);  // 0xFF
```

**Description:** A standard way of representing data as a byte. `std::byte` is
neither a character type nor an arithmetic type, and the only operator overloads
available are bitwise operations.

**Documentation:**
[std::byte](https://en.cppreference.com/w/cpp/types/byte)

**Notes:**
*** promo
None
***

### Splicing for maps and sets [tbd]

```c++
std::map<...>::extract
std::map<...>::merge
std::set<...>::extract
std::set<...>::merge
```

**Description:** Moving nodes and merging containers without the overhead of
expensive copies, moves, or heap allocations/deallocations.

**Documentation:**
[std::map::extract](https://en.cppreference.com/w/cpp/container/map/extract),
[std::map::merge](https://en.cppreference.com/w/cpp/container/map/merge)

**Notes:**
*** promo
None
***

### Parallel algorithms [tbd]

```c++
auto it = std::find(std::execution::par, std::begin(vec), std::end(vec), 2);
```

**Description:** Many of the STL algorithms, such as the `copy`, `find` and
`sort` methods, now support the parallel execution policies: `seq`, `par`, and
`par_unseq` which translate to "sequentially", "parallel" and
"parallel unsequenced".

**Documentation:**
[execution_policy_tag_t](https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t)

**Notes:**
*** promo
None
***

### std::make_from_tuple [tbd]

```c++
// Calls Foo(int, double):
auto foo = std::make_from_tuple<Foo>(std::make_tuple(1, 3.5));
```

**Description:** Constructs an object from a tuple of arguments.

**Documentation:**
[std::make_from_tuple](https://en.cppreference.com/w/cpp/utility/make_from_tuple)

**Notes:**
*** promo
See also `absl::make_from_tuple`.
***

### Searchers [tbd]

```c++
auto it = std::search(haystack.begin(), haystack.end(),
                      std::boyer_moore_searcher(needle.begin(), needle.end()));
```

**Description:** Alternate string searching algorithms.

**Documentation:**
[Searchers](https://en.cppreference.com/w/cpp/utility/functional#Searchers)

**Notes:**
*** promo
None
***

### std::not_fn [tbd]

```c++
auto nonwhite = std::find_if(str.begin(), str.end(), std::not_fn(IsWhitespace));
```

**Description:** Creates a forwarding call wrapper that returns the negation of
the callable object it holds.

**Documentation:**
[std::not_fn](https://en.cppreference.com/w/cpp/utility/functional/not_fn)

**Notes:**
*** promo
See also `base::not_fn`.
***

### Uninitialized memory algorithms [tbd]

```c++
std::destroy_at(ptr);
std::destroy(ptr, ptr + 8);
std::destroy_n(ptr, 8);
std::uninitialized_move(src.begin(), src.end(), dest.begin());
std::uninitialized_value_construct(std::begin(storage), std::end(storage));
```

**Description:** Replaces direct constructor and destructor calls when manually
managing memory.

**Documentation:**
[std::destroy_at](https://en.cppreference.com/w/cpp/memory/destroy_at),
[std::destroy](https://en.cppreference.com/w/cpp/memory/destroy),
[std::destroy_n](https://en.cppreference.com/w/cpp/memory/destroy_n),
[std::uninitialized_move](https://en.cppreference.com/w/cpp/memory/uninitialized_move),
[std::uninitialized_value_construct](https://en.cppreference.com/w/cpp/memory/uninitialized_value_construct)

**Notes:**
*** promo
None
***

### std::pmr::memory_resource and std::polymorphic_allocator [tbd]

```c++
#include <memory_resource>
```

**Description:** Manages memory allocations using runtime polymorphism.

**Documentation:**
[std::pmr::memory_resource](https://en.cppreference.com/w/cpp/memory/memory_resource),
[std::pmr::polymorphic_allocator](https://en.cppreference.com/w/cpp/memory/polymorphic_allocator),

**Notes:**
*** promo
May not be supported in libc++, according to the
[library features table](https://en.cppreference.com/w/cpp/17)
***

### std::aligned_alloc [tbd]

```c++
int* p2 = static_cast<int*>(std::aligned_alloc(1024, 1024));
```

**Description:** Allocates uninitialized storage with the specified alignment.

**Documentation:**
[std::aligned_alloc](https://en.cppreference.com/w/cpp/memory/c/aligned_alloc)

**Notes:**
*** promo
None
***

### std::is_swappable [tbd]

```c++
std::is_swappable<T>
std::is_swappable_with_v<T, U>
```

**Description:** Checks whether classes may be swapped.

**Documentation:**
[std::is_swappable](https://en.cppreference.com/w/cpp/types/is_swappable)

**Notes:**
*** promo
None
***

### std::is_aggregate [tbd]

```c++
if constexpr(std::is_aggregate_v<T>) { ...
```

**Description:** Checks wither the given type is an aggregate type.

**Documentation:**
[std::is_aggregate](https://en.cppreference.com/w/cpp/types/is_aggregate)

**Notes:**
*** promo
None
***

### std::has_unique_object_representations [tbd]

```c++
std::has_unique_object_representations_v<foo>
```

**Description:** Checks wither the given type is trivially copyable and any two
objects with the same value have the same object representation.

**Documentation:**
[std::has_unique_object_representations](https://en.cppreference.com/w/cpp/types/has_unique_object_representations)

**Notes:**
*** promo
None
***

### std::reduce [tbd]

```c++
std::reduce(std::execution::par, v.cbegin(), v.cend());
```

**Description:** Like `std::accumulate` except the elements of the range may be
grouped and rearranged in arbitrary order.

**Documentation:**
[std::reduce](https://en.cppreference.com/w/cpp/algorithm/reduce)

**Notes:**
*** promo
Makes the most sense in conjunction with `std::execution::par`.
***

### std::inclusive_scan [tbd]

```c++
std::inclusive_scan(data.begin(), data.end(), output.begin());
```

**Description:** Like `std::accumulate` but writes the result at each step into
the output range.

**Documentation:**
[std::inclusive_scan](https://en.cppreference.com/w/cpp/algorithm/inclusive_scan)

**Notes:**
*** promo
None
***

### std::exclusive_scan [tbd]

```c++
std::exclusive_scan(data.begin(), data.end(), output.begin());
```

**Description:** Like `std::inclusive_scan` but omits the current element from
the written output at each step; that is, results are "one value behind" those
of `std::inclusive_scan`.

**Documentation:**
[std::exclusive_scan](https://en.cppreference.com/w/cpp/algorithm/exclusive_scan)

**Notes:**
*** promo
None
***

### std::gcd [tbd]

```c++
static_assert(std::gcd(12, 18) == 6);
```

**Description:** Computes the greatest common divisor of its arguments.

**Documentation:**
[std::gcd](https://en.cppreference.com/w/cpp/numeric/gcd)

**Notes:**
*** promo
None
***

### std::lcm [tbd]

```c++
static_assert(std::lcm(12, 18) == 36);
```

**Description:** Computes the least common multiple of its arguments.

**Documentation:**
[std::lcm](https://en.cppreference.com/w/cpp/numeric/lcm)

**Notes:**
*** promo
None
***

### Mathematical special functions [tbd]

```c++
std::assoc_laguerre()
std::assoc_legendre()
std::beta()
std::comp_ellint_1()
std::comp_ellint_2()
std::comp_ellint_3()
std::cyl_bessel_i()
std::cyl_bessel_j()
std::cyl_bessel_k()
std::cyl_neumann()
std::ellint_1()
std::ellint_2()
std::ellint_3()
std::expint()
std::hermite()
std::legendre()
std::laguerre()
std::riemann_zeta()
std::sph_bessel()
std::sph_legendre()
std::sph_neumann()
```

**Description:** A variety of mathematical functions.

**Documentation:**
[Mathematical special functions](https://en.cppreference.com/w/cpp/numeric/special_functions)

**Notes:**
*** promo
May not be supported in libc++, according to the
[library features table](https://en.cppreference.com/w/cpp/17)
***

### 3D std::hypot [tbd]

```c++
double dist = std::hypot(1.0, 2.5, 3.7);
```

**Description:** Computes the distance from the origin in 3D space.

**Documentation:**
[std::hypot](https://en.cppreference.com/w/cpp/numeric/math/hypot)

**Notes:**
*** promo
None
***

### std::launder [tbd]

```c++
struct Y { int z; };
alignas(Y) std::byte s[sizeof(Y)];
Y* q = new(&s) Y{2};
const int h = std::launder(reinterpret_cast<Y*>(&s))->z;
```

**Description:** When used to wrap a pointer, makes it valid to access the
resulting object in cases it otherwise wouldn't have been, in a very limited set
of circumstances.

**Documentation:**
[std::launder](https://en.cppreference.com/w/cpp/utility/launder)

**Notes:**
*** promo
None
***

### std::to_chars/std::from_chars [tbd]

```c++
std::to_chars(str.data(), str.data() + str.size(), 42);
std::from_chars(str.data(), str.data() + str.size(), result);
```

**Description:** Locale-independent, non-allocating, non-throwing functions to
convert values to/from character strings, designed for use in high-throughput
contexts.

**Documentation:**
[std::to_chars](https://en.cppreference.com/w/cpp/utility/to_chars),
[std::from_chars](https://en.cppreference.com/w/cpp/utility/from_chars)

**Notes:**
*** promo
None
***

### std::atomic<T>::is_always_lock_free [tbd]

```c++
template <typename T>
struct is_lock_free_impl
: std::integral_constant<bool, std::atomic<T>::is_always_lock_free> {};
```

**Description:** True when the given atomic type is always lock-free.

**Documentation:**
[std::atomic<T>::is_always_lock_free](https://en.cppreference.com/w/cpp/atomic/atomic/is_always_lock_free)

**Notes:**
*** promo
None
***

### std::scoped_lock [tbd]

```c++
std::scoped_lock lock(e1.m, e2.m);
```

**Description:** Provides an RAII-style mechanism for owning one or more mutexes
for the duration of a scoped block.

**Documentation:**
[std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock)

**Notes:**
*** promo
See also `base::AutoLock`.
***

### std::timespec_get [tbd]

```c++
std::timespec ts;
std::timespec_get(&ts, TIME_UTC);
```

**Description:** Gets the current calendar time in the given time base.

**Documentation:**
[std::timespec_get](https://en.cppreference.com/w/cpp/chrono/c/timespec_get)

**Notes:**
*** promo
None
***

## Abseil Banned Library Features {#absl-blocklist}

The following Abseil library features are not allowed in the Chromium codebase.

### Any [banned]

```c++
absl::any a = int{5};
EXPECT_THAT(absl::any_cast<int>(&a), Pointee(5));
EXPECT_EQ(absl::any_cast<size_t>(&a), nullptr);
```

**Description:** Early adaptation of C++17 `std::any`.

**Documentation:** [std::any](https://en.cppreference.com/w/cpp/utility/any)

**Notes:**
*** promo
Banned since workaround for lack of RTTI isn't compatible with the component
build ([Bug](https://crbug.com/1096380)). Also see `std::any`.
***

### bind_front [banned]

```c++
absl::bind_front
```

**Description:** Binds the first N arguments of an invocable object and stores them by value.

**Documentation:**
*   [bind_front.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/functional/bind_front.h)
*   [Avoid std::bind](https://abseil.io/tips/108)

**Notes:**
*** promo
Banned due to overlap with `base::Bind`. Use `base::Bind` instead.
***

### Command line flags [banned]

```c++
ABSL_FLAG(bool, logs, false, "print logs to stderr");
app --logs=true;
```

**Description:** Allows programmatic access to flag values passed on the
command-line to binaries.

**Documentation:** [Flags Library](https://abseil.io/docs/cpp/guides/flags)

**Notes:**
*** promo
Banned since workaround for lack of RTTI isn't compatible with the component
build. ([Bug](https://crbug.com/1096380)) Use `base::CommandLine` instead.
***

### Container utilities [banned]

```c++
auto it = absl::c_find(container, value);
```

**Description:** Container-based versions of algorithmic functions within C++
standard library.

**Documentation:**
[container.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/algorithm/container.h)

**Notes:**
*** promo
Banned due to overlap with `base/ranges/algorithm.h`. Use the `base/ranges/`
facilities instead.
***

### FunctionRef [banned]

```c++
absl::FunctionRef
```

**Description:** Type for holding a non-owning reference to an object of any
invocable type.

**Documentation:**
[function_ref.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/functional/function_ref.h)

**Notes:**
*** promo
- `absl::FunctionRef` is banned due to allowing implicit conversions between
  function signatures in potentially surprising ways. For example, a callable
  with the signature `int()` will bind to `absl::FunctionRef<void()>`: the
  return value from the callable will be silently discarded.
- In Chromium, use `base::FunctionRef` instead.
- Unlike `base::OnceCallback` and `base::RepeatingCallback`, `base::FunctionRef`
  supports capturing lambdas.
- Useful when passing an invocable object to a function that synchronously calls
  the invocable object, e.g. `ForEachFrame(base::FunctionRef<void(Frame&)>)`.
  This can often result in clearer code than code that is templated to accept
  lambdas, e.g. with `template <typename Invocable> void
  ForEachFrame(Invocable invocable)`, it is much less obvious what arguments
  will be passed to `invocable`.
- For now, `base::OnceCallback` and `base::RepeatingCallback` intentionally
  disallow conversions to `base::FunctionRef`, under the theory that the
  callback should be a capturing lambda instead. Attempting to use this
  conversion will trigger a `static_assert` requesting additional feedback for
  use cases where this conversion would be valuable.
- *Important:* `base::FunctionRef` must not outlive the function call. Like
  `base::StringPiece`, `base::FunctionRef` is a *non-owning* reference. Using a
  `base::FunctionRef` as a return value or class field is dangerous and likely
  to result in lifetime bugs.
- [Discussion thread](https://groups.google.com/a/chromium.org/g/cxx/c/JVN4E4IIYA0/m/V0EVUVLiBwAJ)
***

### Random [banned]

```c++
absl::BitGen bitgen;
size_t index = absl::Uniform(bitgen, 0u, elems.size());
```

**Description:** Functions and utilities for generating pseudorandom data.

**Documentation:** [Random library](https://abseil.io/docs/cpp/guides/random)

**Notes:**
*** promo
Banned because most uses of random values in Chromium should be using a
cryptographically secure generator. Use `base/rand_util.h` instead.
***

### Span [banned]

```c++
absl::Span
```

**Description:** Early adaptation of C++20 `std::span`.

**Documentation:** [Using absl::Span](https://abseil.io/tips/93)

**Notes:**
*** promo
Banned due to being less std::-compliant than `base::span`. Keep using
`base::span`.
***

### StatusOr [banned]

```c++
absl::StatusOr<T>
```

**Description:** An object that is either a usable value, or an error Status
explaining why such a value is not present.

**Documentation:**
[statusor.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/status/statusor.h)

**Notes:**
*** promo
Banned due to overlap with `base::expected`. Use `base::expected` instead.
***

### String Formatting [banned]

```c++
absl::StrFormat
```

**Description:** A typesafe replacement for the family of printf() string
formatting routines.

**Documentation:**
[String Formatting](https://abseil.io/docs/cpp/guides/format)

**Notes:**
*** promo
Banned for now due to overlap with `base::StringPrintf()`. See
[migration bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1371963).
***

### string_view [banned]

```c++
absl::string_view
```

**Description:** Early adaptation of C++17 `std::string_view`.

**Documentation:** [absl::string_view](https://abseil.io/tips/1)

**Notes:**
*** promo
Banned due to only working with 8-bit characters. Keep using
`base::StringPiece` from `base/strings/`.
***

### Strings Library [banned]

```c++
absl::StrSplit
absl::StrJoin
absl::StrCat
absl::StrAppend
absl::Substitute
absl::StrContains
```

**Description:** Classes and utility functions for manipulating and comparing
strings.

**Documentation:**
[String Utilities](https://abseil.io/docs/cpp/guides/strings)

**Notes:**
*** promo
Banned for now due to overlap with `base/strings`. We
[should re-evalute](https://bugs.chromium.org/p/chromium/issues/detail?id=1371966)
when we've
[migrated](https://bugs.chromium.org/p/chromium/issues/detail?id=691162) from
`base::StringPiece` to `std::string_view`.
***

### Synchronization [banned]

```c++
absl::Mutex
```

**Description:** Primitives for managing tasks across different threads.

**Documentation:**
[Synchronization](https://abseil.io/docs/cpp/guides/synchronization)

**Notes:**
*** promo
Banned due to overlap with `base/synchronization/`. We would love
[more testing](https://bugs.chromium.org/p/chromium/issues/detail?id=1371969) on
whether there are compelling reasons to prefer base, absl, or std
synchronization primitives; for now, use `base/synchronization/`.
***

### Time library [banned]

```c++
absl::Duration
absl::Time
absl::TimeZone
absl::CivilDay
```

**Description:** Abstractions for holding time values, both in terms of
absolute time and civil time.

**Documentation:** [Time](https://abseil.io/docs/cpp/guides/time)

**Notes:**
*** promo
Banned due to overlap with `base/time/`. Use `base/time/` instead.
***

## Abseil TBD Features {#absl-review}

The following Abseil library features are not allowed in the Chromium codebase.
See the top of this page on how to propose moving a feature from this list into
the allowed or banned sections.

### AnyInvocable [tbd]

```c++
absl::AnyInvocable
```

**Description:** An equivalent of the C++23 std::move_only_function.

**Documentation:**
*   [any_invocable.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/functional/any_invocable.h)
*   [std::move_only_function](https://en.cppreference.com/w/cpp/utility/functional/move_only_function/move_only_function)

**Notes:**
*** promo
Overlaps with `base::RepeatingCallback`, `base::OnceCallback`.
***

### Cleanup [tbd]

```c++
FILE* sink_file = fopen(sink_path, "w");
auto sink_closer = absl::MakeCleanup([sink_file] { fclose(sink_file); });
```

**Description:** Implements the scope guard idiom, invoking the contained
callback's `operator()() &&` on scope exit.

**Documentation:**
[cleanup.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/cleanup/cleanup.h)

**Notes:**
*** promo
Similar to `defer` in Golang.
***

### Containers [tbd]

```c++
absl::flat_hash_map
absl::flat_hash_set
absl::node_hash_map
absl::node_hash_set
absl::btree_map
absl::btree_set
absl::btree_multimap
absl::btree_multiset
absl::InlinedVector
absl::FixedArray
```

**Description:** Alternatives to STL containers designed to be more efficient
in the general case.

**Documentation:**
*   [Containers](https://abseil.io/docs/cpp/guides/container)
*   [Hash](https://abseil.io/docs/cpp/guides/hash)

**Notes:**
*** promo
Supplements `base/containers/`.
***

### Log macros and related classes [tbd]

```c++
LOG(INFO) << message;
CHECK(condition);
absl::AddLogSink(&custom_sink_to_capture_absl_logs);
```

**Description:** Macros and related classes to perform debug loggings

**Documentation:**
[log.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/log.h)
[check.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/check.h)

**Notes:**
*** promo
Overlaps and uses same macros names as `base/logging.h`.
***


text:
"""
Reading data files from external sources

Stijn Van Hoey, stvhoey.vanhoey@ugent.be
"""

import os
import sys

import ftplib
import StringIO
import datetime

import pandas as pd

def load_VMM_zrx_timeserie(filename):
    """
    Read VMM zrx files and converts it into a pd.DataFrame

    Parameters
    ----------
    filename : str
        full path name to the file to read in

    Returns
    -------
    data : pd.DataFrame
        pd.DataFrame of the VMM data
    """
    zrxf = open(filename, 'r')

    #define header length (= number of lines with starting #)
    ctestall = zrxf
    headerlength = 0
    ctest = '#'
    while ctest == '#':
        ctest = ctestall.readline()[0]
        headerlength += 1
    print 'File ', filename.split("\\")[-1],\
            ' headerlength is: ', headerlength-1
    zrxf.close()

    #Read the data
    data = pd.read_table(filename, sep=' ',
                       skiprows=headerlength-1, index_col=0,
                       parse_dates=True,
                       header=None, usecols=(0, 1),
                       names=['Time', filename.split("\\")[-1][:-4]],
                       na_values='-777.0')
    return data

def _gettext(ftp, filename, outfile=None):
    """
    Help function for scraping text from the ftp-driver
    (for binary data, another format would be needed)

    """
    # fetch a text file
    if outfile is None:
        outfile = sys.stdout
    # use a lambda to add newlines to the lines read from the server
    ftp.retrlines("RETR " + filename, lambda s, w = outfile.write: w(s+"\n"))

def load_VMM_zrx_timeseries_from_ftp(server, login, password,
                                     path, dataname="_DATA"):
    """
    Read all VMM zrx files in a specific folder, concatenates them
    and converts it into a pd.DataFrame

    Parameters
    ----------
    server : str
        ftp server location, e.g. ftp.anteagroup.be
    login : str
        login name of the ftp drive
    password : str
        password of the user
    path : str
        path name to the folder with the interested .zrx files
    dataname : str
        suffix name used to flag the saved data

    Returns
    -------
    data : pd.DataFrame
        pd.DataFrame of the VMM data
    """
    ftp = ftplib.FTP(server)
    ftp.login(login, password)
    #discharge -> go to discharge folder
    ftp.cwd(path)
    #check the files in the folder
    files = ftp.nlst()

    # We're interested in the .zrx files, so let's get the information of
    # those in a dictionary, with the key the station code and the data a
    # pandas Dataframe first exclude in the files list the none-zrx files
    files = [zrxf for zrxf in files if '.zrx' in zrxf]

    data = []
    for zrxf in files:
        output = StringIO.StringIO()
        _gettext(ftp, zrxf, output)

        #define header length (= number of lines with starting #)
        ctestall = StringIO.StringIO(output.getvalue())
        headerlength = 0
        ctest = '#'
        while ctest == '#':
            ctest = ctestall.readline()[0]
            headerlength += 1
        print 'File ',zrxf,' headerlength is: ', headerlength-1

        temp = pd.read_table(StringIO.StringIO(output.getvalue()), sep=' ',
                           skiprows=headerlength-1, index_col=0,
                           parse_dates=True,
                           header=None, usecols=(0, 1),
                           names=['Time', zrxf[:-4]], na_values='-777.0')
        data.append(temp)
        output.close()
    ftp.close()

    ##CONCATENATE THE DIFFERENT DATAFRAMES IN ONE BIG:
    data2 = pd.concat(data, axis=1)

    ##SAVE THE DATA IN ONE PICKLE FOR NEXT TIME WORKING WITH THESE
    data2.to_csv(datetime.datetime.now().strftime("%Y%m%d") +
                    "VMM_" + dataname+".csv", float_format="%.3f",
                    na_rep="Nan")
    data2.to_pickle(datetime.datetime.now().strftime("%Y%m%d")
                    + "VMM_" + dataname)

def _minutes2hours(minutes):
    """convert minutes to hours and return als rest
    """
    return minutes/60, minutes%60

def load_CEH_timeserie(filename):
    """
    Read VMM zrx files and converts it into a pd.DataFrame

    Parameters
    ----------
    filename : str
        full path name to the file to read in

    Returns
    -------
    data : pd.DataFrame
        pd.DataFrame of the VMM data
    """
    parse = lambda y,m,d,h: datetime.datetime(int(y), int(m), int(d),
                                              _minutes2hours(int(h))[0],
                                              _minutes2hours(int(h))[1])
    ceh_data = pd.read_csv(filename, sep=',',
                       parse_dates={"Datetime":[1,2,3,4]},
                       date_parser=parse,
                       skipinitialspace=True)
    ceh_data = ceh_data.set_index("Datetime")

    return ceh_data


text:
CodeIgniter provides a `CI_Controller` that is meant to be used as the basis for all of your own controllers. It handles the behind-the-scenes work of assigning class vars and the Loader so that you can access them. Bonfire extends this concept and provides 4 additional Controllers that can be used as base classes throughout your project. This helps you to keep from repeating code any more than necessary by providing a central place for any site-wide code to sit. For example, it makes a user object available that can be accessed from any controller, library, or view to know details about the current user. You can use it to set a custom theme for all of your public pages. And much more.

Each controller is stored in its own file in the `application/libraries` folder and the file is named the same as the class name. This allows the provided autoloader to easily find your base classes.

The `MY_Controller` file is currently not used by Bonfire and is left alone so that you can use it for your own needs.

## The Controllers

Each controller type is meant to serve a specific purpose, but they are all easily adaptable to fit your needs. This files are meant to be customized for your application! Don't be afraid to edit them. That said, however, please be sure to back the files up during any upgrades of Bonfire.

### Base_Controller

All of the custom controllers extend from the `Base_Controller`.  This class extends the MX_Controller which gives you all of the power of WireDesign's [HMVC](https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home) available to all of your classes.  That allows for a different way of working, but also a very powerful one, and one that is not necessary to use.

This controller is the place that you want to setup anything that should happen for every page of your site, like:

* Setup environment-specific settings, like turning the profiler on for development and off for production and testing.
* Get the cache setup correctly.  This is currently setup to only use a file-based cache, but you can easily tell it to use APC if available, and fallback to the file system if not.
* This controller also sets up [System Events](system_events.html) that will get executed just before and just after the Base_Controller's constructor runs.

Some of the things that would normally be auto-loaded are handled here so that any AJAX controllers you may write don't need to process any of these other settings.

By default, Bonfire's Base_Controller provides the following features for any of your classes that extend it:

* `$previous_page` and `$requested_page` class vars that help you know where you came from. These are auto-populated for you.
* `$current_user` class var that, if logged in, will contain all of the information from the users table, as well as a link to the user's avatar. This same information is automatically made available to the view files that are rendered with the [Template](layouts_and_views) class.
* Loads the cache drivers. For development environments, we simply harness the 'dummy' driver which always returns FALSE. Production and test environments default to APC caching with a file-based backup, if that's not available.
* Gets the `activity model` loaded and ready.
* Loads the `application language` file.
* If the child class sets `$requires_authentication` to TRUE, will ensure that the user is logged in, set the `$current_user` variable, and ensure that the user's chosen language is set.

### Front_Controller

The `Front_Controller` is intended to be used as the base for any public-facing controllers.  As such, anything that needs to be done for the front-end can be done here.

Currently, it simply ensures that the Assets and Template libraries are available.  You could also set the active and default themes here, if you create a parent theme 'framework' to use with all of your sites that you extend with child themes.

### Authenticated_Controller

This controller forms the base for the Admin Controller.  It was broken into two parts in case you needed to create a front-end area that was only accessible to your users, but that was not part of the Admin area and didn't share the same themes, etc.  All changes you make here will affect your Admin Controller's, though, so use with care.  If you need to, reset the values in the Admin Controller.

This controller currently...

* Loads in all of the authentication library
* Restricts access to only logged in users
* Gets form_validation setup and working correctly with HMVC.

### Admin_Controller

The final controller sets things up even more for use within the Admin area of your site.  That is, the area that Bonfire has setup for you as a base of operations.  It currently...

* Sets the pagination settings for a consistent user experience.
* Gets the admin theme loaded and makes sure that some consistent CSS files are loaded so we don't have to worry about it later.

## Creating Controllers

Creating controllers in Bonfire is nearly identical to creating controllers in straight CodeIgniter. The only difference is the naming of some of the classes when you're dealing with the Administration side of Bonfire and [Contexts](contexts). It does provide some basic tools for you to use, though.

### Class Variables
The following class variables are available to you from any controller that extends from `Base_Controller` or one of it's child classes.

#### $current_user
 If a user is logged in, there basic information will be stored in the `$current_user` class variable. This is also made available within views as `$current_user`. If the user is not logged in, the value will be `NULL`.

#### $previous_page
Will store the uri of the previous page, if that page was a page within your application. This is set during the `post_controller` hook and will filter out any pages in the `$ignore_pages` class variable of the `App_hooks` file.

Hooks must be enabled for this variable to be populated.

#### $requested_page
The page that the web server thinks you were requesting. Set during the `pre_controller` hook, it will attempt to determine the page that the user was requesting, while filtering out the `$ignore_pages` uris so that we don't get things like images, etc.

This value is also saved to the $_SESSION if CodeIgniter's Session class has not been loaded.

Hooks must be enabled for this variable to be populated.

#### $require_authentication
If set to TRUE, the Base_Controller will load up the authentication class, ensure that the user is logged in via `$this->auth->restrict()` and handle setting up the current user for access in the controller.

If you are extending from Authenticated_Controller of Admin_Controller, this will have already been called.

#### $autoload
This array provides a simple means of loading various libraries, helpers and models automatically within your application.

	protected $autoload = array(
        'libraries' => array('settings/settings_lib'),
        'helpers'   => array(),
        'models'    => array()
    );

You will not, however, want to extend this directly since you will override parent class autoload needs. Instead, set the value in your class' constructor prior to calling the parent's constructor.

	public function __construct()
	{
		$this->autoload['helpers'][] = 'my_new_helper';

		parent::__construct();
	}


text:
<?php

namespace App\Ecofy\Modules\Auth\Controllers;

use Log;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Socialite;

use App\Ecofy\Support\AbstractAuthSocialController;
use App\Ecofy\Support\ObjectAccessor;
use App\Ecofy\Modules\Auth\Auth;
use App\Ecofy\Modules\Account\Account;
use App\Ecofy\Modules\Account\Profile;

// Ecofy service
use App\Ecofy\Modules\Auth\AuthServiceContract;

/**
 * For Socialite documentation
 * @see: https://github.com/laravel/socialite
 */
class AuthLinkedInController extends AbstractAuthSocialController
{
    public function __construct() {
		parent::__construct('linkedin', null);
	}

    public function buildAuthModel($authService, $oauthUser)
    {
        $authData['authSource'] = $this->driver;
        $authData['authId'] = $oauthUser->id;
        $authData['authCredentialsRaw'] = json_encode($oauthUser->user);
        $authData['status'] = 1;
        $authData['rememberToken'] = $oauthUser->token;
        $authData['security_password'] = null;
        $authData['security_activationCode'] = null;
        $authData['security_securityQuestion'] = null;
        $authData['security_securityAnswer'] = null;

        return $authService->newAuth($authData);
    }

    public function buildAccountModel($authService, $oauthUser)
    {
        $accountData['kind'] = 'basic';
        // $accountData['roles'] = null;
        $accountData['status'] = 'registered';
        $accountData['displayName'] = $oauthUser->name;
        $accountData['primaryEmail'] = $oauthUser->email;
        $accountData['imageUrl'] = $oauthUser->avatar;

        return $authService->getAccountService()->newAccount($accountData);
    }

    public function buildProfileModel($authService, $oauthUser)
    {
        $profileData['familyName'] = ObjectAccessor::get($oauthUser->user, 'lastName');
        $profileData['givenName'] = ObjectAccessor::get($oauthUser->user, 'firstName');
        $profileData['highlight'] = ObjectAccessor::get($oauthUser->user, 'headline', null);
        $profileData['gender'] = ObjectAccessor::get($oauthUser->user, 'gender', null);
        $profileData['language'] = ObjectAccessor::get($oauthUser->user, 'gender', null);

        $profileData['address_countryCode'] = ObjectAccessor::get($oauthUser->user, 'location.country.code');

        return $authService->getAccountService()->newProfile($profileData);
    }

}


text:
function SDPDiffer(mySDP, otherSDP) {
    this.mySDP = mySDP;
    this.otherSDP = otherSDP;
}

/**
 * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
 * @param otherSdp the other SDP to check ssrc with.
 */
SDPDiffer.prototype.getNewMedia = function() {

    // this could be useful in Array.prototype.
    function arrayEquals(array) {
        // if the other array is a falsy value, return
        if (!array)
            return false;

        // compare lengths - can save a lot of time
        if (this.length != array.length)
            return false;

        for (var i = 0, l=this.length; i < l; i++) {
            // Check if we have nested arrays
            if (this[i] instanceof Array && array[i] instanceof Array) {
                // recurse into the nested arrays
                if (!this[i].equals(array[i]))
                    return false;
            }
            else if (this[i] != array[i]) {
                // Warning - two different object instances will never be equal: {x:20} != {x:20}
                return false;
            }
        }
        return true;
    }

    var myMedias = this.mySDP.getMediaSsrcMap();
    var othersMedias = this.otherSDP.getMediaSsrcMap();
    var newMedia = {};
    Object.keys(othersMedias).forEach(function(othersMediaIdx) {
        var myMedia = myMedias[othersMediaIdx];
        var othersMedia = othersMedias[othersMediaIdx];
        if(!myMedia && othersMedia) {
            // Add whole channel
            newMedia[othersMediaIdx] = othersMedia;
            return;
        }
        // Look for new ssrcs accross the channel
        Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
            if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
                // Allocate channel if we've found ssrc that doesn't exist in our channel
                if(!newMedia[othersMediaIdx]){
                    newMedia[othersMediaIdx] = {
                        mediaindex: othersMedia.mediaindex,
                        mid: othersMedia.mid,
                        ssrcs: {},
                        ssrcGroups: []
                    };
                }
                newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
            }
        });

        // Look for new ssrc groups across the channels
        othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){

            // try to match the other ssrc-group with an ssrc-group of ours
            var matched = false;
            for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
                var mySsrcGroup = myMedia.ssrcGroups[i];
                if (otherSsrcGroup.semantics == mySsrcGroup.semantics
                    && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {

                    matched = true;
                    break;
                }
            }

            if (!matched) {
                // Allocate channel if we've found an ssrc-group that doesn't
                // exist in our channel

                if(!newMedia[othersMediaIdx]){
                    newMedia[othersMediaIdx] = {
                        mediaindex: othersMedia.mediaindex,
                        mid: othersMedia.mid,
                        ssrcs: {},
                        ssrcGroups: []
                    };
                }
                newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
            }
        });
    });
    return newMedia;
};

/**
 * Sends SSRC update IQ.
 * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
 * @param sid session identifier that will be put into the IQ.
 * @param initiator initiator identifier.
 * @param toJid destination Jid
 * @param isAdd indicates if this is remove or add operation.
 */
SDPDiffer.prototype.toJingle = function(modify) {
    var sdpMediaSsrcs = this.getNewMedia();
    var self = this;

    // FIXME: only announce video ssrcs since we mix audio and dont need
    //      the audio ssrcs therefore
    var modified = false;
    Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
        modified = true;
        var media = sdpMediaSsrcs[mediaindex];
        modify.c('content', {name: media.mid});

        modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
        // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
        // generate sources from lines
        Object.keys(media.ssrcs).forEach(function(ssrcNum) {
            var mediaSsrc = media.ssrcs[ssrcNum];
            modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
            modify.attrs({ssrc: mediaSsrc.ssrc});
            // iterate over ssrc lines
            mediaSsrc.lines.forEach(function (line) {
                var idx = line.indexOf(' ');
                var kv = line.substr(idx + 1);
                modify.c('parameter');
                if (kv.indexOf(':') == -1) {
                    modify.attrs({ name: kv });
                } else {
                    modify.attrs({ name: kv.split(':', 2)[0] });
                    modify.attrs({ value: kv.split(':', 2)[1] });
                }
                modify.up(); // end of parameter
            });
            modify.up(); // end of source
        });

        // generate source groups from lines
        media.ssrcGroups.forEach(function(ssrcGroup) {
            if (ssrcGroup.ssrcs.length != 0) {

                modify.c('ssrc-group', {
                    semantics: ssrcGroup.semantics,
                    xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
                });

                ssrcGroup.ssrcs.forEach(function (ssrc) {
                    modify.c('source', { ssrc: ssrc })
                        .up(); // end of source
                });
                modify.up(); // end of ssrc-group
            }
        });

        modify.up(); // end of description
        modify.up(); // end of content
    });

    return modified;
};

module.exports = SDPDiffer;


text:
  <alm-work-item-comment
    [comments]="comments | async"
    [loggedIn]="loggedIn"
    [loggedInUser]="loggedInUser"
    (create)="createComment($event)"
    (update)="updateComment($event)"
    (delete)="deleteComment($event)"
  >
  </alm-work-item-comment>


text:
import sbt._

package org.scommon.sbt.settings {
  trait CrossCompileSettings extends Settings {
    def defaultVersion: Option[String]
    def compilers: Traversable[CompilerSettings]
    lazy val default: CompilerSettings = {
      val fromDefaultVersion = defaultVersion map (ver => compilers.find(_.scalaVersion == ver).getOrElse(throw new IllegalStateException(s"Attempting to find the default Scala compiler version. The provided default version ($ver) was not in the list of valid versions: ${compilers.map(_.scalaVersion).mkString(", ")}")))
      fromDefaultVersion.getOrElse(compilers.headOption.getOrElse(throw new IllegalStateException(s"Please provide at least one compiler settings")))
    }
  }
}

//Unnamed package

import org.scommon.sbt.settings._

import scala.collection._
import org.scommon.sbt.settings._

object CrossCompileSettings {
  def byVersion(version: String, compilerSettings: CrossCompileSettings): CompilerSettings = {
    val compilers = compilerSettings.compilers
    val default = compilerSettings.default

    compilers.find(_.scalaVersion == version).getOrElse(throw new IllegalStateException(s"Unable to find the provided version ($version) in the list of valid Scala compiler versions: ${compilerSettings.compilers.map(_.scalaVersion).mkString(", ")}"))
  }

  //See: http://stackoverflow.com/questions/12626197/conditional-scalacoptions-with-sbt
  val scalacOptions =
    sbt.Keys.scalacOptions in ThisBuild <<= Def.task {
      val ver = sbt.Keys.scalaVersion.value
      val compilerSettings = org.scommon.sbt.settings.compilerSettings.value
      byVersion(ver, compilerSettings).scalacOptions.toSeq
    }

  //See: http://stackoverflow.com/questions/12626197/conditional-scalacoptions-with-sbt
  val javacOptions =
    sbt.Keys.javacOptions in ThisBuild <<= Def.task {
      val ver = sbt.Keys.scalaVersion.value
      val compilerSettings = org.scommon.sbt.settings.compilerSettings.value
      byVersion(ver, compilerSettings).javacOptions.toSeq
    }

  val crossScalaVersions = {
    val setting = Def.setting {
      val compilerSettings = org.scommon.sbt.settings.compilerSettings.value
      if (compilerSettings.compilers.size > 1)
        compilerSettings.compilers.map(_.scalaVersion).toSeq
      else
        Seq(compilerSettings.default.scalaVersion)
    }

    Seq(
      sbt.Keys.crossScalaVersions in Global <<= setting
    )
  }

  val scalaVersion =
    sbt.Keys.scalaVersion in Global <<= Def.setting {
      val compilerSettings = org.scommon.sbt.settings.compilerSettings.value
      compilerSettings.default.scalaVersion
    }

  val defaults: Seq[sbt.Def.Setting[_]] =
    crossScalaVersions ++ Seq(
      scalaVersion
    , scalacOptions
    , javacOptions
  )
}


text:
var cfg = {
    root: '.',
    pattern: /.\-tests\.ts/g,
    tsc: 'node ./_infrastructure/tests/typescript/tsc.js ',
    exclude: {
        '.git': true,
        '.gitignore': true,
        'package.json': true,
        '_infrastructure': true,
        '.travis.yml': true,
        'LICENSE': true,
        'README.md': true,
        '_ReSharper.DefinitelyTyped': true,
        'obj': true,
        'bin': true,
        'Properties': true,
        'DefinitelyTyped.csproj': true,
        'DefinitelyTyped.csproj.user': true,
        'DefinitelyTyped.sln': true,
        'DefinitelyTyped.v11.suo': true
    }
};

if (process.argv.length > 2) {
    cfg.root = process.argv[2];
}

class TestFile {
    public name: string;
    public errors: string[] = [];
}

class Test {
    public files: TestFile[] = [];
    constructor(public lib: string) { }
}

class Tests {
    public tests: Test[] = [];
}

function getLibDirectory(file: string) {
    return file.substr(cfg.root.length).split('/')[1];
}

function getErrorList(out): string[] {
    var splitContentByNewlines = function (content: string) {
        var lines = content.split('\r\n');
        if (lines.length === 1) {
            lines = content.split('\n');
        }
        return lines;
    }

    var result: string[] = [];

    var lines = splitContentByNewlines(out);

    for (var i = 0; i < lines.length; i++) {
        if (lines[i]) {
            result.push(lines[i]);
        }
    }

    return result;
}

function runTests(testFiles) {
    var tests = new Tests();

    Exec.exec(
        cfg.tsc,
		[testFiles[testIndex]],
        (ExecResult) => {
            var lib = getLibDirectory(testFiles[testIndex]);

            cache_visited_libs[lib] = true;

            var testFile = new TestFile();
            testFile.name = testFiles[testIndex];
            testFile.errors = getErrorList(ExecResult.stderr);

            if (testFile.errors.length == 0) {
                total_success++;
            } else {
                total_failure++;
            }

            console.log('  [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length)
                + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m'));

            var test = new Test(lib);
            test.files.push(testFile);
            tests.tests.push(test);

            testIndex++;
            if (testIndex < totalTest) {
                Exec.exec(
					cfg.tsc,
					[testFiles[testIndex]],
					<(ExecResult) => any>arguments.callee);
            } else {
                var withoutTests = {};
                for (var k = 0; k < allFiles.length; k++) {
                    var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1];
                    if (!(rootFolder in cfg.exclude)) {
                        if (!(rootFolder in cache_visited_libs)) {
                            withoutTests[rootFolder] = true;
                        }
                    }
                }

                var withoutTestsCount = 0;
                for (var attr in withoutTests) {

                    var test = new Test(attr);
                    tests.tests.push(test);

                    console.log('  [\033[36m' + attr + '\033[0m] without tests');
                    withoutTestsCount++;
                }

                console.log('\n> ' + (total_failure + total_success + withoutTestsCount)
                    + ' tests. '
                    + '\033[32m' + total_success + ' tests success\033[0m, '
                    + '\033[31m' + total_failure + ' tests failed\033[0m and '
                    + withoutTestsCount + ' definitions without tests.\n');

                if (total_failure > 0) {
                    process.exit(1);
                }
            }
        });
}

////// GLOBAL VARS

// get all files: "*-tests.ts"
var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 });

// get all proect files
var allFiles = IO.dir(cfg.root, null, { recursive: true });

var totalTest = testFiles.length;
var testIndex = 0;
var cache_visited_libs = {};

// total
var total_failure = 0;
var total_success = 0;

// var to have current typescript version
var tscVersion = '?.?.?';

////// END GLOBAL VARS

// entry point
Exec.exec(cfg.tsc, ['-version'], (ExecResult) => {
    tscVersion = ExecResult.stdout;

    console.log('$ tsc -version');
    console.log(tscVersion);

    runTests(testFiles);
});


text:
(function(document, $) {
  "use strict";

  // Collection of methods supported by user browser
  var fn = (function() {
    var fnMap = [
      ["requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror"],
      // new WebKit
      [
        "webkitRequestFullscreen",
        "webkitExitFullscreen",
        "webkitFullscreenElement",
        "webkitFullscreenEnabled",
        "webkitfullscreenchange",
        "webkitfullscreenerror"
      ],
      // old WebKit (Safari 5.1)
      [
        "webkitRequestFullScreen",
        "webkitCancelFullScreen",
        "webkitCurrentFullScreenElement",
        "webkitCancelFullScreen",
        "webkitfullscreenchange",
        "webkitfullscreenerror"
      ],
      [
        "mozRequestFullScreen",
        "mozCancelFullScreen",
        "mozFullScreenElement",
        "mozFullScreenEnabled",
        "mozfullscreenchange",
        "mozfullscreenerror"
      ],
      ["msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError"]
    ];

    var ret = {};

    for (var i = 0; i < fnMap.length; i++) {
      var val = fnMap[i];

      if (val && val[1] in document) {
        for (var j = 0; j < val.length; j++) {
          ret[fnMap[0][j]] = val[j];
        }

        return ret;
      }
    }

    return false;
  })();

  if (fn) {
    var FullScreen = {
      request: function (elem) {
        elem = elem || document.documentElement;

        elem[fn.requestFullscreen](elem.ALLOW_KEYBOARD_INPUT);
      },
      exit: function () {
        document[fn.exitFullscreen]();
      },
      toggle: function (elem) {
        elem = elem || document.documentElement;

        if (this.isFullscreen()) {
          this.exit();
        } else {
          this.request(elem);
        }
      },
      isFullscreen: function () {
        return Boolean(document[fn.fullscreenElement]);
      },
      enabled: function () {
        return Boolean(document[fn.fullscreenEnabled]);
      }
    };

    $.extend(true, $.fancybox.defaults, {
      btnTpl: {
        fullScreen:
        '<button data-fancybox-fullscreen class="fancybox-button fancybox-button--fsenter" title="{{FULL_SCREEN}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 16h3v3h2v-5H5zm3-8H5v2h5V5H8zm6 11h2v-3h3v-2h-5zm2-11V5h-2v5h5V8z"/></svg>' +
        "</button>"
      },
      fullScreen: {
        autoStart: false
      }
    });

    $(document).on(fn.fullscreenchange, function () {
      var isFullscreen = FullScreen.isFullscreen(),
        instance = $.fancybox.getInstance();

      if (instance) {
        // If image is zooming, then force to stop and reposition properly
        if (instance.current && instance.current.type === "image" && instance.isAnimating) {
          instance.isAnimating = false;

          instance.update(true, true, 0);

          if (!instance.isComplete) {
            instance.complete();
          }
        }

        instance.trigger("onFullscreenChange", isFullscreen);

        instance.$refs.container.toggleClass("fancybox-is-fullscreen", isFullscreen);

        instance.$refs.toolbar
          .find("[data-fancybox-fullscreen]")
          .toggleClass("fancybox-button--fsenter", !isFullscreen)
          .toggleClass("fancybox-button--fsexit", isFullscreen);
      }
    });
  }

  $(document).on({
    "onInit.fb": function(e, instance) {
      var $container;

      if (!fn) {
        instance.$refs.toolbar.find("[data-fancybox-fullscreen]").remove();

        return;
      }

      if (instance && instance.group[instance.currIndex].opts.fullScreen) {
        $container = instance.$refs.container;

        $container.on("click.fb-fullscreen", "[data-fancybox-fullscreen]", function(e) {
          e.stopPropagation();
          e.preventDefault();

          FullScreen.toggle();
        });

        if (instance.opts.fullScreen && instance.opts.fullScreen.autoStart === true) {
          FullScreen.request();
        }

        // Expose API
        instance.FullScreen = FullScreen;
      } else if (instance) {
        instance.$refs.toolbar.find("[data-fancybox-fullscreen]").hide();
      }
    },

    "afterKeydown.fb": function(e, instance, current, keypress, keycode) {
      // "F"
      if (instance && instance.FullScreen && keycode === 70) {
        keypress.preventDefault();

        instance.FullScreen.toggle();
      }
    },

    "beforeClose.fb": function(e, instance) {
      if (instance && instance.FullScreen && instance.$refs.container.hasClass("fancybox-is-fullscreen")) {
        FullScreen.exit();
      }
    }
  });
})(document, jQuery);


text:
<meta charset="utf-8">

  <img src="../photo_gallery/cu/images/CU_001.jpg" class="image1 resizeme" data-description="

													Caption

Satellite image of Cuba (center) and Jamaica (lower right). The southern tip of Florida, the Florida Keys, and the Florida Strait appear at the top. The bright blue green color around the islands, particularly around those of the Bahamas in the upper right, is likely due to the brighter solar reflection over the more shallow waters that surround the islands. Image courtesy of NASA.

													Dimensions
													File Size
													Download

													1125 X 1500
													298637 kb

													Usage

														Factbook photos - obtained from a wide variety of sources - are in the public domain and are copyright free.

Agency Copyright Notice

" data-link="../photo_gallery/cu/images/CU_001.jpg">


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="action_settings">Settings</string>
    <string name="title_section1">Calendar</string>
    <string name="title_section2">Events</string>

</resources>


text:
package org.zstack.header.vm;

import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;

/**
 * Created by root on 11/2/16.
 */
@Action(category = VmInstanceConstant.ACTION_CATEGORY)
@RestRequest(
        path = "/vm-instances/{uuid}/actions",
        isAction = true,
        method = HttpMethod.PUT,
        responseClass = APIResumeVmInstanceEvent.class
)
public class APIResumeVmInstanceMsg extends APIMessage implements VmInstanceMessage {
    @APIParam
    private String uuid;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    @Override
    public String getVmInstanceUuid() {
        return getUuid();
    }

    public static APIResumeVmInstanceMsg __example__() {
        APIResumeVmInstanceMsg msg = new APIResumeVmInstanceMsg();
        msg.uuid = uuid();
        return msg;
    }

}