text:
.. _Usage:

Usage
#####

As seen in the :ref:`Configuration` section, you first need to create a ``CacheManager``
instance.

Accessing Multiple Cache Stores
===============================

Using the ``CacheManager`` instance, you can access the configured cache stores via the ``store`` method.
The key passed to the store method should correspond to one of the stores listed in the ``stores``
configuration dictionary:

.. code-block:: python

    value = cache.store('redis').get('foo')

    cache.store('memcached').put('foo', 'bar', 10)

.. note::

    If you do not specify a store the default store will be used.

    .. code-block:: python

        value = cache.get('foo')

Retrieving Items From The Cache
===============================

The ``get`` method is used to retrieve items from the cache.
If the item does not exist in the cache, ``None`` will be returned.
If you wish, you can pass a second argument to the ``get`` method specifying the custom default value
you wish to be returned if the item doesn't exist:

.. code-block:: python

    value = cache.get('foo')

    value = cache.get('foo', 'default')

You may even pass a function as the default value.
The result of the function will be returned if the specified item does not exist in the cache.
Passing a function allows you to defer the retrieval of default values from a database or other external service:

.. code-block:: python

    value = cache.get('foo', lambda: db.table('users').get())

Checking For Item Existence
---------------------------

The ``has`` method may be used to determine if an item exists in the cache:

.. code-block:: python

    if cache.has('foo'):
        # ...

Incrementing / Decrementing Values
----------------------------------

The ``increment`` and ``decrement`` methods can be used to adjust the value of integer items in the cache.
Both of these methods optionally accept a second argument indicating the amount
by which to increment or decrement the item's value:

.. code-block:: python

    cache.increment('key')

    cache.increment('key', 3)

    cache.decrement('key')

    cache.decrement('key', 3)

Retrieve or Update
------------------

Sometimes you may wish to retrieve an item from the cache,
but also store a default value if the requested item doesn't exist.
For example, you may wish to retrieve all users from the cache or, if they don't exist,
retrieve them from the database and add them to the cache.
You may do this using the ``remember`` method:

.. code-block:: python

    value = cache.remember('users', 10, lambda: db.table('users').get())

If the item does not exist in the cache,
the function passed to the remember method will be executed and its result will be placed in the cache.

You may also combine the ``remember`` and ``forever`` methods:

.. code-block:: python

    value = cache.remember_forever('users', 10, lambda: db.table('users').get())

.. note::

    Using the ``remember`` method might not be the most practical in some cases,
    that's why you can use the ``CacheManager`` instance like a decorator.

    See :ref:`UsingDecorators`.

Retrieve and Delete
-------------------

If you need to retrieve an item from the cache and then delete it,
you can use the ``pull`` method.
Like the ``get`` method, ``None`` will be returned if the item does not exist in the cache:

.. code-block:: python

    value = cache.pull('key')

Storing Items In The Cache
==========================

You can use the ``put`` method to store items in the cache.
When you place an item in the cache, you will need to specify the number of minutes
for which the value should be cached:

.. code-block:: python

    cache.put('key', 'value', 10)

Instead of passing the number of minutes until the item expires,
you can also pass a ``datetime`` instance representing the expiration time of the cached item:

.. code-block:: python

    expires_at = datetime.now() + timedelta(minutes=10)

    cache.put('key', 'value', expires_at)

The ``add`` method will only add the item to the cache if it does not already exist in the cache store.
The method will return ``True`` if the item is actually added to the cache.
Otherwise, the method will return ``False``:

.. code-block:: python

    cache.add('key', 'value', 10)

The ``forever`` method can be used to store an item in the cache permanently.
These values must be manually removed from the cache using the ``forget`` method:

.. code-block:: python

    cache.forever('key', 'value')

Removing Items From The Cache
=============================

You can remove items from the cache using the ``forget``:

.. code-block:: python

    cache.forget('key')

.. _UsingDecorators:

Using Decorators
================

Instead of using the ``remember`` method, which might not be suitable for functions
with complex logic, you can use the ``CacheManager`` instance as a decorator:

.. code-block:: python

    @cache
    def get_users():
        return db.table('users').get()

This will store the result of the function for the default time of 60 minutes.
The key will automatically be generated based on the function name, its arguments and keyword arguments.

You can also specify a key and the number of minutes the result will be stored in the cache:

.. code-block:: python

    @cache(key='key', minutes=30)
    def get_users():
        return db.table('users').get()

.. warning::

    The ``key`` keyword will only serve as a prefix for the automatically generated key.
    The final cache key will still depend on the arguments and keyword arguments.

You can also specify a store when using the cache manager as a decorator:

.. code-block:: python

    @cache('redis', key='key', minutes=30)
    def get_users():
        return db.table('users').get()


text:
**Project Setup**

# **Setup NodeJS for Windows**

    1. **Install NodeJS**

To download Node, go to [nodejs.org](http://nodejs.org/), click "Download", and click "Windows Installer". This will give you a Windows Installer (MSI) file that will install Node and npm.

![image alt text](images/image_0.png)

Running the Windows installer will show a wizard, it's pretty easy to follow. It's just like installing any other Windows program – the Node binaries will end up in **C:\Program Files (x86)\nodejs\**, and will be accessible from **cmd.exe**.

![image alt text](images/image_1.png)

# **Setup Eclipse for AngularJS and GIT**

Refer to the link: [https://github.com/angelozerr/angularjs-eclipse](https://github.com/angelozerr/angularjs-eclipse) to setup you AngularJS plugin.

    2. **[Getting Started**:](https://github.com/angelozerr/angularjs-eclipse/wiki/Getting-Started)** **

[https://github.com/angelozerr/angularjs-eclipse/wiki/Getting-Started](https://github.com/angelozerr/angularjs-eclipse/wiki/Getting-Started)

How to install and configure AngularJS Eclipse, this Eclipse plugin is based on the powerful javascript inference engine [tern.js](http://ternjs.net/) which is written in javascript. To use this engine on Java context, tern.java is used. It executes [tern.js](http://ternjs.net/) with [node.js](http://nodejs.org/). That's why you will see that, you must [install node.js](#heading=h.gjdgxs)[ ](#heading=h.gjdgxs)server or use an embed [node.js](http://nodejs.org/).

If you don't [install node.js](#heading=h.gjdgxs)[ ](#heading=h.gjdgxs)or don't use an embed node.js, only syntax coloring and completions directives will be available in HTML editor.

        1. **Installation**

AngularJS Eclipse is developped/tested with Eclipse Kepler. It is adwised to use Kepler (even if AngularJS Eclipse could work with older version of Eclipse).

To install AngularJS Eclipse, please read [Installation - Update Site](https://github.com/angelozerr/angularjs-eclipse/wiki/Installation---Update-Site) section.

When you will use AngularJS Eclipse update site you will see that:

![image alt text](images/image_2.png)

You must select:

* **AngularJS Eclipse Tooling** which is AngularJS Eclipse plugins .

* select the well Embed Node.js according your OS, only if you have not [node.js](http://nodejs.org/) installed on your computer.

* **Tern** to use tern with Eclipse IDE.

* **Tern - JSDT** to benefit with angular (jquery, etc) completions and hyperlink in Javascript JSDT Editor.

* **Tern - server - Node.js** to use tern with [node.js](http://nodejs.org/).

        2. **AngularJS Configuration**

Before using AngularJS Eclipse features ([HTML features](https://github.com/angelozerr/angularjs-eclipse/wiki/HTML-Features) and [Javascript features](https://github.com/angelozerr/angularjs-eclipse/wiki/Javascript-Features)) you must convert your project to AngularJS Project :

![image alt text](images/image_3.png)

            1. **_[HTML Feature_**s](https://github.com/angelozerr/angularjs-eclipse/wiki/HTML-Features)

            2. **_Syntax Coloring_**

Highlight AngularJS directive and EL:

![image alt text](images/image_4.png)

            3. **_Directive management_**

Completion for directive name :

![image alt text](images/image_5.png)

You can configure directives syntax in order to that completion shows you the well directive names (ng-, ng_, etc).

                1. Customize Directives syntax

In HTML editor, directives completion provides directive names with the ng-* syntax :

![image alt text](images/image_6.png)

Angular supports several syntax like starting with 'x-', 'data-' and use ':', '-', '_' delimiters. You can customize the syntax that you wish for completion with the project properties. By default you will see this configuration :

![image alt text](images/image_7.png)

You can select other starts with and delimiters. You can see in the textarea the directive names that completion will show :

![image alt text](images/image_8.png)

After validating your configuration, completion will show you directive names with other syntaxes :

![image alt text](images/image_9.png)

                2. Completion by tags

Some directive supports only some HTML elements. For instance ngModel can be used only for 'inpu' HTML element. The completion shows ngModel only for 'input' element.

                3. Completion by restrict

Angular defines 4 restricts :

* A : the directive is available for attribute.

![image alt text](images/image_10.png)

* C : the directive is available for class attribute value.

* E : the directive is available for element.

![image alt text](images/image_11.png)

* M : the directive is available for comment.

                4. Completion for directive parameters

Some directive have parameters. A good sample is the [ngPluralize](http://docs.angularjs.org/api/ng.directive:ngPluralize) directive which defines required parameters like 'count', 'when' and optional 'offset' parameter:

![image alt text](images/image_12.png)

If you open completion inside HTML element, you will see ngPluralize :

![image alt text](images/image_13.png)

When you apply the completion on ngPluralize, 'count' and 'when' attribute are generated because there are required :

![image alt text](images/image_14.png)

Directive parameters are highlighted with a light blue color.

If you open completion inside the HTML element, you can see 'offset' directive parameter :

![image alt text](images/image_15.png)

ngPluralize can be used as element (restrict=EA), you can benefit too with completion for HTML element.

![image alt text](images/image_16.png)

When you apply the completion on ngPluralize, 'count' and 'when' attribute are generated because there are required :

![image alt text](images/image_17.png)

            4. **_Hover_**

![image alt text](images/image_18.png)

            5. **_Custom Directive_**

                5. Completions

Completion for custom directive name :

![image alt text](images/image_19.png)

                6. Hyperlink

Hyperlink for custom directive name :

![image alt text](images/image_20.png)

            6. **_[Tern Eclipse IDE - Node.j_**s](https://github.com/angelozerr/tern.java/wiki/Tern-Eclipse-IDE-Node.js)

To execute Tern (written in Javascript) it is recommanded to execute it with Node.js. Tern Eclipse IDE gives you preference page to configure Tern with Node.js.

                7. Tern with Node.js

Open Preferences with the menu Windows/Preferences and select Tern node tree :

![image alt text](images/image_21.png)

                8. Configure Node.js

After selecting Tern with node.js, you must configure the node.js runtime process. To do that go to the Tern->Node.js node tree.

                9. Native Node.js

If you have [installed node.js](http://nodejs.org/), select "Native Node.js" :

![image alt text](images/image_22.png)

IMPORTANT : if you have installed node.js, please restart your computer before using the Tern Eclipse IDE.

                10. Embed Node.js

If you have not installed node.js, you can select according your OS, (if it's available) the embed node.js install :

![image alt text](images/image_23.png)

            7. **_Module management_**

For module management, you need to configure tern server.

                11. Hyperlink

![image alt text](images/image_24.png)

                12. Hover

![image alt text](images/image_25.png)

                13. Completions

Completion for modules (declared in an external JS) :

![image alt text](images/image_26.png)

            8. **_Controller management_**

For controller management, you need to configure tern server.

                14. Completions

Completion for controllers (declared in an external JS) :

![image alt text](images/image_27.png)

                15. Hover

![image alt text](images/image_28.png)

                16. Hyperlink

![image alt text](images/image_29.png)

            9. **_Angular Expression management_**

For angular expression management, you need to configure tern server.

                17. Completions

Completion for angular expression :

![image alt text](images/image_30.png)

            10. **_Typing_**

                18. Auto close EL

![image alt text](images/image_31.png) ![image alt text](images/image_32.png)

                19. Validation

Imagine you have this valid HTML Angular file (module and controller exists) :

![image alt text](images/image_33.png)

If you fill ng-app with bad module, you will see this validation error :

![image alt text](images/image_34.png)

If you fill ng-app with existing module, but a controller which doesn't exists, you will see this validation error :

![image alt text](images/image_35.png)

        3. **[Javascript Feature**s](https://github.com/angelozerr/angularjs-eclipse/wiki/Javascript-Features)

            11. **_JSDT Editor_**

Tern.java extends the JSDT plugins to use tern completion, hyperlinks with the JSDT Javascript Editor.

Note : it should be possible to extend other Javascript editor with tern by developping a plugin eclipse.

            12. **_Completions_**

                20. Angular

Completion on angular variable :

![image alt text](images/image_36.png)

Completion on angular module :

![image alt text](images/image_37.png)

Completion on angular elements like $http :

![image alt text](images/image_38.png)

Completion on injected service :

![image alt text](images/image_39.png)

                21. Javascript

Completion on javascript elements like array :

![image alt text](images/image_40.png)

            13. **_Hyperlink_**

Ctrl+Click on any javascript elements (variable, function) open hyperlink :

![image alt text](images/image_41.png)

If you select "Tern - Go to definition", tern is used to search and select the javascript definition:

![image alt text](images/image_42.png)

It works too if your variable, functions is defined on other files (if script path is well configured).

        4. **Preferences Settings**

This section explains how to configure tern and angular.

            14. **_Global Preferences_**

This section is about "global preferences" dialog that you open with **Window/Preferences.**

                22. Node.js

AngularJS Eclipse is based on the javascript inference engine tern.js is written in Javascript. To use it, tern is executed with node.js (Rhino is too slow for that). You must configure node.js. To do that you can:

* use your installed node.js. For that, you must select the "Native node" install type and select the well node file :

![image alt text](images/image_43.png)

when the native node is selected, it searches node binary in default folders installation (ex : "C:\Program Files\nodejs\node.exe" for Windows) and if it doesn't find, it searches in your node in your "PATH" environment.

If you wish to [download and install node.js](#heading=h.gjdgxs)[,](#heading=h.gjdgxs) it's important to restart your computer before using AngularJS Eclipse in order to your OS update correctly your "PATH" environment with your installed node.js.

* use an embed node. For that you must install the well embed node.js according your OS :

![image alt text](images/image_44.png)

            15. **_Project preferences_**

This section is about "project properties" dialog which is available if you select your project and use "Properties" menu item of the contextual menu (or Alt/Enter).

                23. Tern Plugins

tern.js provides several [Tern Plugin](http://ternjs.net/doc/manual.html#plugins). Check that angular plugin is checked

![image alt text](images/image_45.png)

The angular plugin gives you the capability to retrieve module, controllers,(custom) directives, etc from your javascript, manages completion hyperlink, hover, validation in HTML and Javascript editor. It's enable to emulate the angular injection on your $scope, $http, etc.

                24. JSON Tern definitions

tern.js provides several [JSON Type definition](http://ternjs.net/doc/manual.html#typedef). If you wish to benefit with completion about browser model (ex: document.get...), select it. It provides too an ecma5, jquery definition. For angular, the definition is inside the angular plugin.

![image alt text](images/image_46.png)

                25. Scripts path

When tern is used for completion, validation, hover, hyperlink, it must load before (just the first time) a list of your Javascript. To do that you must configure your script paths by selecting your js folder which contains your javascripts (it's the same thing than for Java build path) :

![image alt text](images/image_47.png)

                26. Customize Directives syntax

In HTML editor, directives completion provides directive names with the ng-* syntax :

![image alt text](images/image_48.png)

Angular supports several syntax like starting with 'x-', 'data-' and use ':', '-', '_' delimiters. You can customize the syntax that you wish for completion with the project properties. By default you will see this configuration :

![image alt text](images/image_49.png)

After validating your configuration, completion will show you directive names with other syntaxes :

![image alt text](images/image_50.png)

                27. Validation

If you validate with "Validate" menu contextual menu :

![image alt text](images/image_51.png)

you will see that AngularJS directives will have warn messages :

![image alt text](images/image_52.png)

In this sample you have 2 warnings messages :

* a warning with ng-app which is an Angular directive

* a warning with "a" attribute in the head element which doesn't exist.

You could disable the warning message for unknown attribute, but AngularJS Eclipse provides the "HTML Angular Syntax Validator" which is an extension of the "HTML Syntax Validator" to support Angular directives. To use this Angular validator, you must enable it and disable "HTML Syntax Validator":

![image alt text](images/image_53.png)

If you revalidate you will see that directive are not marked as warning and other unknown attributes are marked as warning:

![image alt text](images/image_54.png)

        5. **Let's go!**

At this step we have finished to configure AngularJS Eclipse, now it's time to check that everything works (tern with node.js is well configured).

            16. **_HTML Editor_**

Open an HTML file by using **Open with/AngularJS Editor:**

![image alt text](images/image_55.png)

If you open your HTML file without this editor, you will have not angular syntax coloration, but completion, hyperlink should working.

Try completion on ng-app to open your module:

![image alt text](images/image_56.png)

This feature is managed by tern, if it doesn't work, see [Troubleshooting](#heading=h.3znysh7)[ ](#heading=h.3znysh7)section.

        6. **Javascript Editor**

Open a javascript editor and try to open completion for angular model:

![image alt text](images/image_57.png)

This feature is managed by tern, if it doesn't work, see [Troubleshooting](#heading=h.3znysh7)[ ](#heading=h.3znysh7)section.

        7. **Troubleshooting**

If you have checked your configuration and completion doesn't work for HTML and Javascript editor, it means that there is a problem with tern with node.js. To verify that you can see errors with:

* Error log view.

* Tern console

            17. **_Error log view_**

![image alt text](images/image_58.png)

            18. **_Tern console_**

You can trace the start of node.js server and the request/response of the tern server by using the Eclipse console.

To do that, you must active the tern console for your project:

![image alt text](images/image_59.png)

and open the tern console:

![image alt text](images/image_60.png)

If you retry to execute completion for instance to use tern server, you will see the node.js command and the error in the console:

![image alt text](images/image_61.png)

When you have no problem, you can see the JSON request/response of the tern server when it is use it:

![image alt text](images/image_62.png)

        8. **[Angular Explore**r](https://github.com/angelozerr/angularjs-eclipse/wiki/Angular-Explorer-View)

Angular Explorer View gives you the capability to display Angular elements like modules, controllers of your AngularJS application. To open it go to **Window/Show View** and select **Angular Explorer:**

![image alt text](images/image_63.png)

After that you can see your modules, controllers, etc:

![image alt text](images/image_64.png)

            19. **_Angular Explorer View_**

Angular Explorer View gives you the capability to display Angular elements like modules, controllers of your AngularJS application:

![image alt text](images/image_65.png)

This view is useful for :

* display modules, controllers, etc in a view and go to the definition if you double click on it (open the JS editor and select the module, controller).

* AngularJS "HTML templates" where module and controller is not defined inside the HTML. So you can link module and controller to the current HTML editor to benefit with Angular expression completion.

            20. **_How to configure the view?_**

                28. Define script path

To use Angular Explorer View, you must defines the whole Javascripts files which must be used to load with Tern the Angular modules, controllers. To do that you must configure Script path. Here a screenshot where script path was configured with an HTML file which defines "script" elements by using "Add File" button:

![image alt text](images/image_66.png)

You can define a folder with "Add Folder" which contains the Javascript files to load. This configuration is used when your scripts to load are not declared in script element (or if script/@src cannot be resolved if you use for instance JSP EL contextPath).

![image alt text](images/image_67.png)

            21. **_Use the Angular Explorer view?_**

                29. Go To Definition

The "Go To Definition" contextual menu gives the capability to open the JS editor and select the module, controller selected (you can do that too with double click):

![image alt text](images/image_68.png)

                30. HTML Template (Link/Unlink)

No completion:

![image alt text](images/image_69.png)

To resolve this problem, you can link the HTML file to a controller with "Link to controller" menu action:

![image alt text](images/image_70.png)

If you reopen completion, you will see completion :

![image alt text](images/image_71.png)

# **Setup Github**

You can get a Git project using two main approaches. The first takes an existing project or directory and imports it into Git. The second clones an existing Git repository from another server.

## Initializing a Repository in an Existing Directory

If you're starting to track an existing project in Git, you need to go to the project's directory and type

`$ git init`

This creates a new subdirectory named **`.git` that contains all of your necessary repository files — a Git repository skeleton. At this point, nothing in your project is tracked yet. (See Chapter 9 for more information about exactly what files are contained in the **`.git` directory you just created.)

If you want to start version-controlling existing files (as opposed to an empty directory), you should probably begin tracking those files and do an initial commit. You can accomplish that with a few git add commands that specify the files you want to track, followed by a commit:

`$ git add *.js`

`$ git add README`

`$ git commit -m 'initial project version'`

At this point, you have a Git repository with tracked files and an initial commit.

## Cloning an Existing Repository

If you want to get a copy of an existing Git repository — for example, a project you'd like to contribute to — the command you need is `git clone`. If you're familiar with other VCS systems such as Subversion, you'll notice that the command is `clone` and not `checkout`. This is an important distinction — Git receives a copy of nearly all data that the server has. Every version of every file for the history of the project is pulled down when you run `git clone`. In fact, if your server disk gets corrupted, you can use any of the clones on any client to set the server back to the state it was in when it was.

You clone a repository with `git clone [url]`. For example, if you want to clone the Ruby Git library called Grit, you can do so like this:

`$ git clone git://github.com/HardiBhattatWork/myWebsite.git`

That creates a directory named `grit`, initializes a .`git` directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. If you go into the new grit directory, you'll see the project files in there, ready to be worked on or used. If you want to clone the repository into a directory named something other than `grit`, you can specify that as the next command-line option:

`$ git clone git://github.com/HardiBhattatWork/myWebsite.git myDirectory`

That command does the same thing as the previous one, but the target directory is called `mygrit`

## Adding Git to Windows 7 Path

Note: You must have msysgit installed on your machine. Also, the path to my git install is "C:\Program Files (x86)\Git" yours might be different. Please check were yours is before continuing.

### Open Windows Environment Variables/Path Window

·         Right-Click on **My Computer**

·         Click **Advanced System Settings** link from the left side column

·         Click **Environment Variables** in the bottom of the window

·         Then under **System Variables** look for the **path** variable and click **edit**

·         Add the pwd to git's bin and cmd at the end of the string like this:

`;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd`

Now test it out in PowerShell; type git and see if it recognizes the command.

redpajama_set_name: RedPajamaGithub


text:
// Include format.cc instead of format.h to test implementation-specific stuff.
#include "format.cc"

#include <cstring>

#include "gtest-extra.h"
#include "util.h"

#undef max

TEST(FormatTest, ArgConverter) {
  using fmt::internal::Arg;
  Arg arg = Arg();
  arg.type = Arg::LONG_LONG;
  arg.long_long_value = std::numeric_limits<fmt::LongLong>::max();
  ArgConverter<fmt::LongLong>(arg, 'd').visit(arg);
  EXPECT_EQ(Arg::LONG_LONG, arg.type);
}

TEST(FormatTest, FormatNegativeNaN) {
  double nan = std::numeric_limits<double>::quiet_NaN();
  if (fmt::internal::getsign(-nan))
    EXPECT_EQ("-nan", fmt::format("{}", -nan));
  else
    fmt::print("Warning: compiler doesn't handle negative NaN correctly");
}

TEST(FormatTest, StrError) {
  char *message = 0;
  char buffer[BUFFER_SIZE];
#ifndef NDEBUG
  EXPECT_DEBUG_DEATH(safe_strerror(EDOM, message = 0, 0), "Assertion");
  EXPECT_DEBUG_DEATH(safe_strerror(EDOM, message = buffer, 0), "Assertion");
#endif
  buffer[0] = 'x';
#ifdef _GNU_SOURCE
  // Use invalid error code to make sure that safe_strerror returns an error
  // message in the buffer rather than a pointer to a static string.
  int error_code = -1;
#else
  int error_code = EDOM;
#endif

  int result = safe_strerror(error_code, message = buffer, BUFFER_SIZE);
  EXPECT_EQ(0, result);
  std::size_t message_size = std::strlen(message);
  EXPECT_GE(BUFFER_SIZE - 1u, message_size);
  EXPECT_EQ(get_system_error(error_code), message);

  // safe_strerror never uses buffer on MinGW.
#ifndef __MINGW32__
  result = safe_strerror(error_code, message = buffer, message_size);
  EXPECT_EQ(ERANGE, result);
  result = safe_strerror(error_code, message = buffer, 1);
  EXPECT_EQ(buffer, message);  // Message should point to buffer.
  EXPECT_EQ(ERANGE, result);
  EXPECT_STREQ("", message);
#endif
}

TEST(FormatTest, FormatErrorCode) {
  std::string msg = "error 42", sep = ": ";
  {
    fmt::MemoryWriter w;
    w << "garbage";
    format_error_code(w, 42, "test");
    EXPECT_EQ("test: " + msg, w.str());
  }
  {
    fmt::MemoryWriter w;
    std::string prefix(
        fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size() + 1, 'x');
    format_error_code(w, 42, prefix);
    EXPECT_EQ(msg, w.str());
  }
  {
    fmt::MemoryWriter w;
    std::string prefix(
        fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size(), 'x');
    format_error_code(w, 42, prefix);
    EXPECT_EQ(prefix + sep + msg, w.str());
    std::size_t size = fmt::internal::INLINE_BUFFER_SIZE;
    EXPECT_EQ(size, w.size());
  }
}


text:
<?php

if (!class_exists("ApiError", false)) {
  /**
   * The API error base class that provides details about an error that occurred
   * while processing a service request.
   *
   *
The OGNL field path is provided for parsers to identify the request data
   * element that may have caused the error.

   */
  class ApiError {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "ApiError";

    /**
     * @var string
     */
    public $fieldPath;

    /**
     * @var string
     */
    public $trigger;

    /**
     * @var string
     */
    public $type;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($fieldPath = null,
        $trigger = null,
        $type = null
    ) {
      $this->fieldPath = $fieldPath;
      $this->trigger = $trigger;
      $this->type = $type;
    }
  }
}

if (!class_exists("ReportDownloadError", false)) {
  /**
   * Specifies why and how report download contains errors.
   */
  class ReportDownloadError {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "";

    /**
     * @var ApiError[]
     */
    public $ApiError;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($ApiError = null) {
      $this->ApiError = $ApiError;
    }
  }
}

if (!class_exists("ReportDefinition", false)) {
  /**
   * Represents a report definition.
   */
  class ReportDefinition {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "ReportDefinition";

    /**
       * @var integer
     */
    public $id;

    /**
       * @var Selector
     */
    public $selector;

    /**
       * @var string
     */
    public $reportName;

    /**
       * @var tnsReportDefinitionReportType
     */
    public $reportType;

    /**
       * @var boolean
     */
    public $hasAttachment;

    /**
       * @var tnsReportDefinitionDateRangeType
     */
    public $dateRangeType;

    /**
       * @var tnsDownloadFormat
     */
    public $downloadFormat;

    /**
       * @var string
     */
    public $creationTime;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct(
        $id = null,
        $selector = null,
        $reportName = null,
        $reportType = null,
        $hasAttachment = null,
        $dateRangeType = null,
        $downloadFormat = null,
        $creationTime = null
    ) {
      $this->id = $id;
      $this->selector = $selector;
      $this->reportName = $reportName;
      $this->reportType = $reportType;
      $this->hasAttachment = $hasAttachment;
      $this->dateRangeType = $dateRangeType;
      $this->downloadFormat = $downloadFormat;
      $this->creationTime = $creationTime;
    }
  }
}

if (!class_exists("Selector", false)) {
  /**
   * A generic selector to specify the type of information to return.
   */
  class Selector {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "Selector";

    /**
       * @var string[]
     */
    public $fields;

    /**
       * @var Predicate[]
     */
    public $predicates;

    /**
       * @var DateRange
     */
    public $dateRange;

    /**
       * @var OrderBy[]
     */
    public $ordering;

    /**
       * @var Paging
     */
    public $paging;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($fields = null,
        $predicates = null,
        $dateRange = null,
        $ordering = null,
        $paging = null
    ) {
      $this->fields = $fields;
      $this->predicates = $predicates;
      $this->dateRange = $dateRange;
      $this->ordering = $ordering;
      $this->paging = $paging;
    }
  }
}

if (!class_exists("Predicate", false)) {
  /**
   * Specifies how an entity (eg. adgroup, campaign, criterion, ad) should be
   * filtered.
   */
  class Predicate {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "Predicate";

    /**
     * @var string
     */
    public $field;

    /**
     * @var tnsPredicateOperator
     */
    public $operator;

    /**
     * @var string[]
     */
    public $values;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($field = null, $operator = null,
        $values = null) {
      $this->field = $field;
      $this->operator = $operator;
      $this->values = $values;
    }
  }
}

if (!class_exists("PredicateOperator", false)) {
  /**
   * Defines the valid set of operators.
   */
  class PredicateOperator {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "Predicate.Operator";

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct() {}
  }
}

if (!class_exists("DateRange", false)) {
  /**
   * Represents a range of dates that has either an upper or a lower bound.
   * The format for the date is YYYYMMDD.
   */
  class DateRange {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "DateRange";

    /**
     * @var string
     */
    public $min;

    /**
     * @var string
     */
    public $max;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($min = null, $max = null) {
      $this->min = $min;
      $this->max = $max;
    }
  }
}

if (!class_exists("OrderBy", false)) {
  /**
   * Specifies how the resulting information should be sorted.
   */
  class OrderBy {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "OrderBy";

    /**
     * @var string
     */
    public $field;

    /**
     * @var tnsSortOrder
     */
    public $sortOrder;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($field = null, $sortOrder = null) {
      $this->field = $field;
      $this->sortOrder = $sortOrder;
    }
  }
}

if (!class_exists("Paging", false)) {
  /**
   * Specifies the page of results to return in the response. A page is
   * specified by the result position to start at and the maximum number of
   * results to return.
   */
  class Paging {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "Paging";

    /**
     * @var integer
     */
    public $startIndex;

    /**
     * @var integer
     */
    public $numberResults;

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct($startIndex = null, $numberResults = null) {
      $this->startIndex = $startIndex;
      $this->numberResults = $numberResults;
    }
}}

if (!class_exists("SortOrder", false)) {
  /**
   * Possible orders of sorting.
   */
  class SortOrder {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "SortOrder";

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct() {}
  }
}

if (!class_exists("ReportDefinitionReportType", false)) {
  /**
   * Enums for report types.
   */
  class ReportDefinitionReportType {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "ReportDefinition.ReportType";

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct() {}
  }
}

if (!class_exists("ReportDefinitionDateRangeType", false)) {
  /**
   * Enums for date range of report.
   */
  class ReportDefinitionDateRangeType {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "ReportDefinition.DateRangeType";

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct() {}
  }
}

if (!class_exists("DownloadFormat", false)) {
  /**
   * Enum class that describes the supported formats for content downloads.
   * The order mimics the order in which download options are presented in the
   * legacy report center.
   */
  class DownloadFormat {

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201809";
    const XSI_TYPE = "DownloadFormat";

    /**
     * Gets the namesapce of this class
     * @return the namespace of this class
     */
    public function getNamespace() {
      return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return the xsi:type name of this class
     */
    public function getXsiTypeName() {
      return self::XSI_TYPE;
    }

    public function __construct() {
      if(get_parent_class('DownloadFormat')) parent::__construct();
    }
  }
}


text:
package org.lvcp.eepperly.expr;

/**
 * Created by dboyd16 on 12/16/15.
 */
import org.lvcp.eepperly.exception.MultivariableException;
import org.lvcp.eepperly.exception.VariableNoValueException;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;

public class GeneralLog extends BinOp {
	public GeneralLog(Expr base, Expr yield) {
		super(base, yield);
	}
	public Expr differentiate(Variable withRespectTo) throws MultivariableException{
		if (arg1.hasVars() && arg2.hasVars()) {
			return new Sum(
					new Product(
							arg2.differentiate(withRespectTo),
							Power.unaryMultInv(new Product(
									arg2.differentiate(withRespectTo),
									new NaturalLog(arg1)
							))
					),
					Product.unaryNegation(new Product(
							arg1.differentiate(withRespectTo),
							new NaturalLog(arg2),
							Power.unaryMultInv(arg1),
							new Power(new NaturalLog(arg1), new NumConstant(-2))
					))
			);
		} else if (arg2.hasVars()){
			return new Product(
					arg2.differentiate(withRespectTo),
					Power.unaryMultInv(new NaturalLog(arg1)),
					Power.unaryMultInv(arg2)
			);
		} else if (arg1.hasVars()){
			return new Product(
					Expr.MINUS_ONE,
					new NaturalLog(arg2),
					arg1.differentiate(withRespectTo),
					Power.unaryMultInv(arg1),
					new Power(new NaturalLog(arg1),new NumConstant(-2))
			);
		} else{
			return Expr.ZERO;
		}
	}

	public String toString(){
		return String.format("log_{%s}(%s)", arg1.toString(), arg2.toString());
	}

	@Override
	public Expr substitute(Map<Variable, Expr> subMap){
		return new GeneralLog(getArguments().get(0).substitute(subMap),
				getArguments().get(1).substitute(subMap));
	}

	@Override
	public double evaluate(Map<Variable, Double> evalMap) throws VariableNoValueException {
		return Math.log(arg2.evaluate(evalMap)) /
				Math.log(arg1.evaluate(evalMap));
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof GeneralLog)) return false;

		GeneralLog binOp = (GeneralLog) o;

		if (arg1 != null ? !arg1.equals(binOp.arg1) : binOp.arg1 != null) return false;
		if (arg2 != null ? !arg2.equals(binOp.arg2) : binOp.arg2 != null) return false;

		return true;
	}

	@Override
	public int hashCode() {
		int result = arg1 != null ? arg1.hashCode() : 0;
		result = 31 * result + (arg2 != null ? arg2.hashCode() : 0);
		return result;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NBitcoin;
using Stratis.SmartContracts.Core;

namespace Stratis.SmartContracts.CLR.Serialization
{
    /// <summary>
    /// Class that handles method parameter serialization.
    /// </summary>
    public sealed class MethodParameterStringSerializer : IMethodParameterStringSerializer
    {
        private readonly Network network;

        public MethodParameterStringSerializer(Network network)
        {
            this.network = network;
        }

        /// <inheritdoc />
        public string Serialize(object methodParameter)
        {
            return this.SerializeObject(methodParameter);
        }

        /// <summary>
        /// Serializes an array of method parameter objects to the bytes of their string-encoded representation.
        /// </summary>
        public string Serialize(object[] methodParameters)
        {
            var sb = new List<string>();

            foreach (object obj in methodParameters)
            {
                sb.Add(this.SerializeObject(obj));
            }

            return this.EscapeAndJoin(sb.ToArray());
        }

        private string SerializeObject(object obj)
        {
            Prefix prefix = Prefix.ForObject(obj);

            string serialized = Serialize(obj, this.network);

            return string.Format("{0}#{1}", (int) prefix.DataType, serialized);
        }

        public static string Serialize(object obj, Network network)
        {
            MethodParameterDataType primitiveType = GetPrimitiveType(obj);

            // ToString works fine for all of our data types except byte arrays and addresses
            string serialized;

            switch (primitiveType)
            {
                case MethodParameterDataType.ByteArray:
                    serialized = ((byte[]) obj).ToHexString();
                    break;
                case MethodParameterDataType.Address:
                    serialized = ((Address) obj).ToUint160().ToBase58Address(network);
                    break;
                default:
                    serialized = obj.ToString();
                    break;
            }

            return serialized;
        }

        private static MethodParameterDataType GetPrimitiveType(object o)
        {
            if (o is bool)
                return MethodParameterDataType.Bool;

            if (o is byte)
                return MethodParameterDataType.Byte;

            if (o is byte[])
                return MethodParameterDataType.ByteArray;

            if (o is char)
                return MethodParameterDataType.Char;

            if (o is string)
                return MethodParameterDataType.String;

            if (o is uint)
                return MethodParameterDataType.UInt;

            if (o is ulong)
                return MethodParameterDataType.ULong;

            if (o is Address)
                return MethodParameterDataType.Address;

            if (o is long)
                return MethodParameterDataType.Long;

            if (o is int)
                return MethodParameterDataType.Int;

            // Any other types are not supported.
            throw new MethodParameterStringSerializerException(string.Format("{0} is not supported.", o.GetType().Name));
        }

        public object[] Deserialize(string[] parameters)
        {
            return this.StringToObjects(this.EscapeAndJoin(parameters));
        }

        public object[] Deserialize(string parameters)
        {
            return this.StringToObjects(parameters);
        }

        private object[] StringToObjects(string parameters)
        {
            string[] split = Regex.Split(parameters, @"(?<!(?<!\\)*\\)\|").ToArray();

            var processedParameters = new List<object>();

            foreach (string parameter in split)
            {
                string parameterType = "";
                string parameterValue = "";

                try
                {
                    string[] parameterSignature =
                        Regex.Split(parameter.Replace(@"\|", "|"), @"(?<!(?<!\\)*\\)\#").ToArray();
                    parameterSignature[1] = parameterSignature[1].Replace(@"\#", "#");

                    parameterType = ulong.TryParse(parameterSignature[0], out var parsedParameterType)
                        ? Enum.GetName(typeof(MethodParameterDataType), parsedParameterType) ?? parameterSignature[0]
                        : parameterSignature[0];

                    parameterValue = parameterSignature[1];

                    if (parameterSignature[0] == MethodParameterDataType.Bool.ToString("d"))
                        processedParameters.Add(bool.Parse(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.Byte.ToString("d"))
                        processedParameters.Add(Convert.ToByte(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.Char.ToString("d"))
                        processedParameters.Add(parameterSignature[1][0]);

                    else if (parameterSignature[0] == MethodParameterDataType.String.ToString("d"))
                        processedParameters.Add(parameterSignature[1]);

                    else if (parameterSignature[0] == MethodParameterDataType.UInt.ToString("d"))
                        processedParameters.Add(uint.Parse(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.Int.ToString("d"))
                        processedParameters.Add(int.Parse(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.ULong.ToString("d"))
                        processedParameters.Add(ulong.Parse(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.Long.ToString("d"))
                        processedParameters.Add(long.Parse(parameterSignature[1]));

                    else if (parameterSignature[0] == MethodParameterDataType.Address.ToString("d"))
                        processedParameters.Add(parameterSignature[1].ToAddress(this.network));

                    else if (parameterSignature[0] == MethodParameterDataType.ByteArray.ToString("d"))
                        processedParameters.Add(parameterSignature[1].HexToByteArray());

                    else
                        throw new MethodParameterStringSerializerException($"Parameter type '{parameterType}' is not supported.");
                }
                catch (Exception e) when (e is FormatException || e is OverflowException || e is ArgumentException || e is ArgumentNullException)
                {
                    throw new MethodParameterStringSerializerException($"Error deserializing parameter {parameterType} with value {parameterValue}", e);
                }
            }

            return processedParameters.ToArray();
        }

        /// <inheritdoc />
        private string EscapeAndJoin(string[] parameters)
        {
            IEnumerable<string> escaped = this.EscapePipesAndHashes(parameters);
            return string.Join('|', escaped);
        }

        /// <summary>
        /// Escapes any pipes and hashes in the method parameters.
        /// </summary>
        private IEnumerable<string> EscapePipesAndHashes(string[] parameter)
        {
            IEnumerable<string> processedPipes = parameter.Select(pipeparam => pipeparam = pipeparam.Replace("|", @"\|"));

            IEnumerable<string> processedHashes = processedPipes.Select(hashparam =>
            {

                // This delegate splits the string by the hash character.
                //
                // If the split array is longer than 2 then we need to
                // reconstruct the parameter by escaping all hashes
                // after the first one.
                //
                // Once this is done, prepend the string with the data type,
                // which is an integer representation of MethodParameterDataType,
                // as well as a hash, so that it can be split again upon deserialization.
                //
                // I.e. 3#dcg#5d# will split into 3 / dcg / 5d
                // and then dcg / fd will be reconstructed to dcg\\#5d\\# and
                // 3# prepended to make 3#dcg\\#5d\\#

                string[] hashes = hashparam.Split('#');
                if (hashes.Length == 2)
                    return hashparam;

                var reconstructed = new List<string>();
                for (int i = 1; i < hashes.Length; i++)
                {
                    reconstructed.Add(hashes[i]);
                }

                string result = string.Join('#', reconstructed).Replace("#", @"\#");
                return hashes[0].Insert(hashes[0].Length, "#" + result);
            });

            return processedHashes;
        }
    }

    public class MethodParameterStringSerializerException : Exception
    {
        public MethodParameterStringSerializerException(string message) : base(message)
        {
        }

        public MethodParameterStringSerializerException(string message, Exception innerException)
        : base(message, innerException)
        {
        }
    }
}


text:
using System;
using UnityEngine;

namespace UnityContrib.UnityEngine
{
    /// <summary>
    /// Provides methods for doing measurements of code execution.
    /// </summary>
    public static class Measure
    {
        /// <summary>
        /// Measures the time the specified <paramref name="action"/> takes to execute.
        /// </summary>
        /// <param name="action">
        /// The action to measure.
        /// </param>
        public static float Time(Action action)
        {
            var start = global::UnityEngine.Time.realtimeSinceStartup;
            action();
            var end = global::UnityEngine.Time.realtimeSinceStartup;
            var delta = end - start;
            return delta;
        }

        /// <summary>
        /// Measures the time the specified <paramref name="action"/> takes to execute.
        /// </summary>
        /// <param name="caption">
        /// The caption of the measurement.
        /// </param>
        /// <param name="action">
        /// The action to measure.
        /// </param>
        public static void DebugLogTime(string caption, Action action)
        {
            var time = Measure.Time(action);
            Debug.Log("Time Measure: " + caption + " (" + time + "ms)");
        }
    }
}


text:
package org.springframework.orm.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.OptimisticLockException;

import org.junit.Test;

import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

/**
 * @author Costin Leau
 * @author Phillip Webb
 */
public class DefaultJpaDialectTests {

	private JpaDialect dialect = new DefaultJpaDialect();

	@Test
	public void testDefaultTransactionDefinition() throws Exception {
		DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
		definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);

		try {
			dialect.beginTransaction(null, definition);
			fail("expected exception");
		}
		catch (TransactionException e) {
			// ok
		}
	}

	@Test
	public void testDefaultBeginTransaction() throws Exception {
		TransactionDefinition definition = new DefaultTransactionDefinition();
		EntityManager entityManager = mock(EntityManager.class);
		EntityTransaction entityTx = mock(EntityTransaction.class);

		given(entityManager.getTransaction()).willReturn(entityTx);

		dialect.beginTransaction(entityManager, definition);
	}

	@Test
	public void testTranslateException() {
		OptimisticLockException ex = new OptimisticLockException();
		assertEquals(
				EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(),
				dialect.translateExceptionIfPossible(ex).getCause());
	}
}


text:
\clearpage
\phantomsection
\addcontentsline{toc}{subsection}{speculation}
\label{subr:speculation}
\subsection*{speculation: Activate an inactive speculation}

\subsubsection*{Calling convention}

\begin{description}
\item[\registerop{rd}] Either an active speculation or 0.
\end{description}

\subsubsection*{Description}

The \subroutine{speculation} subroutine transitions an inactive
speculation to the active state, and returns it to the caller, or
returns 0 if there are no inactive speculations available.

\subsubsection*{Failure modes}

This subroutine has no run-time failure modes beyond its constraints.


text:
import * as Router from "universal-router";
//Resolve Universal react routing components in server side
export function serverRouter(routes) {
  function resolveServerRoute(context, params) {
    if (typeof context.route.action === "function") {
      let props = {};
      if (typeof context.route.getInitialProps === "function") {
        return Promise.resolve(
          context.route.getInitialProps(context)
        ).then(props => {
          context.props = props;
          if (props) {
            context.state.route[context.route.path] = props;
          }
          return context.route.action(context, params);
        });
      }
      return context.route.action(context, params);
    }

    return null;
  }

  return new Router(routes, { resolveRoute: resolveServerRoute });
}


text:
namespace todo_list.Droid.UI.Fragments
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Util;
    using Android.Views;
    using Android.Widget;
    using Android.Support.V7.Widget;

    public class TaskListFragment : Android.Support.V4.App.Fragment
    {
        #region Inner Classes

        private class TaskListViewHolder : RecyclerView.ViewHolder
        {
            public TextView TitleLabel;
            public TextView DescriptionLabel;

            public TaskListViewHolder(View view, Action<int> listener) : base(view)
            {
                this.TitleLabel = view.FindViewById<TextView>(Resource.Id.TitleLabel);
                this.DescriptionLabel = view.FindViewById<TextView>(Resource.Id.DescriptionLabel);

                view.Click += (sender, e) => listener(Position);
            }
        }

        private class TaskListAdapter : RecyclerView.Adapter
        {
            private List<Poco.TodoItem> _tasks = null;
            public event EventHandler<int> ItemClick;

            public TaskListAdapter(IEnumerable<Poco.TodoItem> items)
            {
                _tasks = new List<Poco.TodoItem>(items);
            }

            public override int ItemCount
            {
                get
                {
                    return _tasks.Count;
                }
            }

            void OnClick(int position)
            {
                if (ItemClick != null)
                    ItemClick(this, position);
            }

            public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
            {
                TaskListViewHolder h = (TaskListViewHolder)holder;
                Poco.TodoItem item = _tasks[position];
                h.TitleLabel.Text = item.Title;
                h.DescriptionLabel.Text = item.Description;
            }

            public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
            {
                LayoutInflater inflater = LayoutInflater.From(parent.Context);
                View view = inflater.Inflate(Resource.Layout.CellTask, parent, false);
                RecyclerView.ViewHolder holder = new TaskListViewHolder(view, OnClick);
                return holder;
            }
        }

        #endregion

        #region Constants and Fields

        private TaskListAdapter _adapter;

        #endregion

        #region Widgets

        private RecyclerView _taskList;

        #endregion

        #region Constructors

        public TaskListFragment()
        {
        }

        #endregion

        #region Properties
        #endregion

        #region Fragment Methods

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            this.HasOptionsMenu = true;

        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            #region Desinger Stuff

            View view = inflater.Inflate(Resource.Layout.FragmentTaskList, container, false);

            #endregion

            ((Android.Support.V7.App.AppCompatActivity)this.Activity).SupportActionBar.Show();
            ((Android.Support.V7.App.AppCompatActivity)this.Activity).SupportActionBar.Title = "Tasks";

            _taskList = view.FindViewById<RecyclerView>(Resource.Id.TaskList);
            _adapter = new TaskListAdapter(new[] {
                new Poco.TodoItem() { Title = "Title1", Description = "Description 1" },
                new Poco.TodoItem() { Title = "Title2", Description = "Description 2" },
                new Poco.TodoItem() { Title = "Title3", Description = "Description 3" },
                new Poco.TodoItem() { Title = "Title4", Description = "Description 4" },
                new Poco.TodoItem() { Title = "Title5", Description = "Description 5" },
                new Poco.TodoItem() { Title = "Title6", Description = "Description 6" },
                new Poco.TodoItem() { Title = "Title7", Description = "Description 7" },
                new Poco.TodoItem() { Title = "Title8", Description = "Description 8" },
                new Poco.TodoItem() { Title = "Title9", Description = "Description 9" },
                new Poco.TodoItem() { Title = "Title10", Description = "Description 10" },
                new Poco.TodoItem() { Title = "Title11", Description = "Description 11" },
                new Poco.TodoItem() { Title = "Title12", Description = "Description 12" },
                new Poco.TodoItem() { Title = "Title13", Description = "Description 13" }});

            _adapter.ItemClick += _adapter_ItemClick;

            _taskList.SetLayoutManager(new LinearLayoutManager(this.Context));
            _taskList.SetAdapter(_adapter);

            return view;
        }

        public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
        {
            base.OnCreateOptionsMenu(menu, inflater);

            menu.Add("New").SetShowAsAction(ShowAsAction.Always);
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch(item.ItemId)
            {
                case 0:
                    return true; // lo stiamo gestendo

                default:
                    return base.OnOptionsItemSelected(item);
            }
        }

        private void _adapter_ItemClick(object sender, int position)
        {
            //int photoNum = position + 1;
            //Toast.MakeText(this.Context, "This is photo number " + photoNum, ToastLength.Short).Show();

            Bundle arguments = new Bundle();
            arguments.PutInt("id", position);
            TaskFragment fragment = new TaskFragment();
            fragment.Arguments = arguments;

            this.FragmentManager.BeginTransaction()
                       .AddToBackStack("before_TaskFragment") // identificatore nel back stack
                       .Replace(Resource.Id.ContentLayout, fragment, "TaskFragment")
                       .Commit();
        }

        public override void OnDestroyView()
        {
            base.OnDestroyView();
        }

        #endregion

        #region Public Methods
        #endregion

        #region Methods
        #endregion

        #region Event Handlers
        #endregion
    }
}


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

<RelativeLayout
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:background="#AA000000"
    android:minHeight="40dp"
    android:padding="10dp">

    <TextView
		android:id="@android:id/text1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:singleLine="false"
		android:textSize="13sp"
        android:textAlignment="center"
        android:autoLink="all"
        android:textStyle="bold"
        android:textAppearance="@style/TextAppearance.AppCompat.Small">

	</TextView>
</RelativeLayout>


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.10
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.badlogic.gdx.physics.bullet.collision;

import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;

public class GIM_BVH_DATA extends BulletBase {
	private long swigCPtr;

	protected GIM_BVH_DATA(final String className, long cPtr, boolean cMemoryOwn) {
		super(className, cPtr, cMemoryOwn);
		swigCPtr = cPtr;
	}

	/** Construct a new GIM_BVH_DATA, normally you should not need this constructor it's intended for low-level usage. */
	public GIM_BVH_DATA(long cPtr, boolean cMemoryOwn) {
		this("GIM_BVH_DATA", cPtr, cMemoryOwn);
		construct();
	}

	@Override
	protected void reset(long cPtr, boolean cMemoryOwn) {
		if (!destroyed)
			destroy();
		super.reset(swigCPtr = cPtr, cMemoryOwn);
	}

	public static long getCPtr(GIM_BVH_DATA obj) {
		return (obj == null) ? 0 : obj.swigCPtr;
	}

	@Override
	protected void finalize() throws Throwable {
		if (!destroyed)
			destroy();
		super.finalize();
	}

  @Override protected synchronized void delete() {
		if (swigCPtr != 0) {
			if (swigCMemOwn) {
				swigCMemOwn = false;
				CollisionJNI.delete_GIM_BVH_DATA(swigCPtr);
			}
			swigCPtr = 0;
		}
		super.delete();
	}

  public void setBound(btAABB value) {
    CollisionJNI.GIM_BVH_DATA_bound_set(swigCPtr, this, btAABB.getCPtr(value), value);
  }

  public btAABB getBound() {
    long cPtr = CollisionJNI.GIM_BVH_DATA_bound_get(swigCPtr, this);
    return (cPtr == 0) ? null : new btAABB(cPtr, false);
  }

  public void setData(int value) {
    CollisionJNI.GIM_BVH_DATA_data_set(swigCPtr, this, value);
  }

  public int getData() {
    return CollisionJNI.GIM_BVH_DATA_data_get(swigCPtr, this);
  }

  public GIM_BVH_DATA() {
    this(CollisionJNI.new_GIM_BVH_DATA(), true);
  }

}


text:
![CodeIgniter](http://www.elreplicante.com.ar/wp-content/uploads/2012/05/codeigniter-logo.png)
### meets
![Segment.io](http://nathaniel.talbott.ws/images/posts/segmentio_homepage.png)

<div style="margin-top: 50px;">
This library keeps Segment.io integration away from the meat of your app (i.e. the controllers/models/views). It wraps the identify and track methods from Segment.io's own PHP bindings for ease of use.
</div>

## Installation
Either download and unpack the archive into application/libraries/Loggly or use git submodules. Use sudo if you're in a restricted directory.

#### Add Segment.io API key + secret
Add your Segment.io API key and secret to your default config file (values below are non-working) and any custom environment config files you've created

application/config/config.php
application/config/(development|staging|whatever)/config.php

```php
/* Segment.io config data */
$config['segment']['API_key'] = 'xxxxxxx';
$config['segment']['secret'] = 'yyyyyyyyyyyyyyyyyyyy';
```

## Usage
Haven't figured that part out yet

## Acknowledgements
PHP API taken from [Segment.io](https://github.com/segmentio/analytics-php)


text:
import getopt
import sys

from sdcclient import SdcClient

#
# Parse arguments
#
def usage():
    print(('usage: %s [-c|--channel <name>] <sysdig-token>' % sys.argv[0]))
    print('-c|--channel: Set name of channel to create')
    print('You can find your token at https://app.sysdigcloud.com/#/settings/user')
    sys.exit(1)

try:
    opts, args = getopt.getopt(sys.argv[1:], "c:", ["channel="])
except getopt.GetoptError:
    usage()

# Name for the dashboard to create
channel_name = "Api Channel"
for opt, arg in opts:
    if opt in ("-c", "--channel"):
        channel_name = arg

if len(args) != 1:
    usage()

sdc_token = args[0]

#
# Instantiate the SDC client
#
sdclient = SdcClient(sdc_token)

#
# Create an email notification channel
#
ok, res = sdclient.create_email_notification_channel(channel_name, ['gianluca.borello@sysdig.com', 'foo@sysdig.com',
                                                                    'bar@sysdig.com'])
if not ok:
    print(res)
    sys.exit(1)

#
# The notification channel will contain the id, that can be used when creating alerts
#
channel = res['notificationChannel']
print(channel)

#
# Notification channels can also be programmatically deleted
#
ok, res = sdclient.delete_notification_channel(channel)
if not ok:
    print(res)
    sys.exit(1)


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/httpClient.dir/mainClient.cpp.o"
  "httpClient.pdb"
  "httpClient"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/httpClient.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
<?php

$installer = $this;

$installer->startSetup();

try {
    $items = Mage::getModel('dhcarousel/item')->getCollection();

    foreach ($items as $item) {
        $item
            ->setActive(1)
            ->save();
    }
} catch (Exception $e) {
    Mage::logException($e);
    throw $e;
}

$installer->endSetup();


text:
package org.winterblade.minecraft.harmony.mobs.drops.matchers;

import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import org.winterblade.minecraft.harmony.api.Component;
import org.winterblade.minecraft.harmony.api.PrioritizedObject;
import org.winterblade.minecraft.harmony.api.Priority;
import org.winterblade.minecraft.harmony.api.BaseMatchResult;
import org.winterblade.minecraft.harmony.api.mobs.drops.IMobDropMatcher;
import org.winterblade.minecraft.harmony.common.matchers.BaseHeightMatcher;

/**
 * Created by Matt on 5/13/2016.
 */
@Component(properties = {"minHeight"})
@PrioritizedObject(priority = Priority.HIGHER)
public class MinHeightMatcher extends BaseHeightMatcher implements IMobDropMatcher {
    public MinHeightMatcher(int level) {super(level, Integer.MAX_VALUE);}

    /**
     * Should return true if this matcher matches the given event
     *
     * @param evt The event to match
     * @param drop              The dropped item; this can be modified.
     * @return True if it should match; false otherwise
     */
    @Override
    public BaseMatchResult isMatch(LivingDropsEvent evt, ItemStack drop) {
        return matches(evt.getEntity().getPosition());
    }
}


text:
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interactivity;

namespace Encommit.Interactivity
{
    public class FileDialogAction : TriggerAction<DependencyObject>
    {
        public string FilePath
        {
            get { return (string)GetValue(FilePathProperty); }
            set { SetValue(FilePathProperty, value); }
        }

        public static readonly DependencyProperty FilePathProperty =
            DependencyProperty.Register("FilePath", typeof(string), typeof(FileDialogAction), new PropertyMetadata(""));

        public bool IsFolderPicker
        {
            get { return (bool)GetValue(IsFolderPickerProperty); }
            set { SetValue(IsFolderPickerProperty, value); }
        }

        public static readonly DependencyProperty IsFolderPickerProperty =
            DependencyProperty.Register("IsFolderPicker", typeof(bool), typeof(FileDialogAction), new PropertyMetadata(false));

        protected override void Invoke(object parameter)
        {
            var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = IsFolderPicker;

            var result = dialog.ShowDialog();
            if (result == CommonFileDialogResult.Ok)
            {
                FilePath = dialog.FileName;
            }
        }
    }
}


text:
set -euo pipefail

LOCATION=${LOCATION-eastus}
MACHINE_SIZE=${MACHINE_SIZE-Standard_F16}
USER=${USER-$(id -un)}
CLUSTER=azworker-${USER}
NAME=${AZWORKER_NAME-${CLUSTER}}

# Names for various resources just reuse cluster/vm name depending on scope.
RG=${CLUSTER}
NET=${CLUSTER}
SUBNET=${CLUSTER}
NIC=${NAME}
IP=${NAME}
DOMAIN=cockroach-${NAME}
FQDN=${DOMAIN}.${LOCATION}.cloudapp.azure.com

case ${1-} in
    create)
    # To support multiple workers per user, factor the group and vnet creation out.
    azure group create "${RG}" -l "${LOCATION}"
    azure network vnet create -g "${RG}" -n "${NET}" -a 192.168.0.0/16 -l "${LOCATION}"
    azure network vnet subnet create -g "${RG}" -e "${NET}" -n "${SUBNET}" -a 192.168.1.0/24

    azure network public-ip create -g "${RG}" -n "${IP}" -l "${LOCATION}" -d "${DOMAIN}"
    azure network nic create -g "${RG}" -n "${NIC}" -l "${LOCATION}" -p "${IP}" --subnet-name "${SUBNET}" --subnet-vnet-name "${NET}"

    azure vm create \
        --resource-group "${RG}" \
        --name "${NAME}" \
        --location "${LOCATION}" \
        --os-type linux \
        --image-urn canonical:UbuntuServer:16.04.0-LTS:latest \
        --ssh-publickey-file ~/.ssh/id_rsa.pub \
        --admin-username "${USER}" \
        --vm-size "${MACHINE_SIZE}" \
        --nic-name "${NIC}" \
        --vnet-name "${NET}" \
        --vnet-subnet-name "${SUBNET}"

    # Clear any cached host keys for this hostname and accept the new one.
    ssh-keygen -R "${FQDN}"
    # Retry while vm and sshd to start up.
    "$(dirname "${0}")/travis_retry.sh" ssh -o StrictHostKeyChecking=no "${FQDN}" true

    rsync -az "$(dirname "${0}")/../build/bootstrap/" "${FQDN}:bootstrap/"
    rsync -az "$(dirname "${0}")/../build/parallelbuilds-"* "${FQDN}:bootstrap/"
    ssh -A "${FQDN}" ./bootstrap/bootstrap-debian.sh

    # TODO(bdarnell): autoshutdown.cron.sh does not work on azure. It
    # halts the VM, but halting the VM doesn't stop billing. The VM
    # must instead be "deallocated" with the azure API.
    # Install automatic shutdown after ten minutes of operation without a
    # logged in user. To disable this, `sudo touch /.active`.
    #ssh "${FQDN}" "sudo cp bootstrap/autoshutdown.cron.sh /root/; echo '* * * * * /root/autoshutdown.cron.sh 10' | sudo crontab -i -"

    echo "VM now running at ${FQDN}"
    ;;
    start)
    azure vm start "${RG}" "${NAME}"
    ;;
    stop)
    azure vm deallocate "${RG}" "${NAME}"
    ;;
    delete)
    azure group delete "${RG}"
    ;;
    ssh)
    shift
    # shellcheck disable=SC2029
    ssh -A "${FQDN}" -- "$@"
    ;;
    *)
    echo "$0: unknown command: ${1-}, use one of create, start, stop, delete, or ssh"
    exit 1
    ;;
esac


text:
#ifndef __vtkScalarsToColorsHistogramChart_h
#define __vtkScalarsToColorsHistogramChart_h

#include "ctkVisualizationVTKCoreExport.h"

#include <vtkChartXY.h>
#include <vtkNew.h>

class vtkPlotBar;
class vtkScalarsToColors;
class vtkTable;

class CTK_VISUALIZATION_VTK_CORE_EXPORT vtkScalarsToColorsHistogramChart
  : public vtkChartXY
{
public:
  vtkTypeMacro(vtkScalarsToColorsHistogramChart, vtkChartXY)
  static vtkScalarsToColorsHistogramChart* New();

  enum
  {
    VTK_AUTO, // VTK auto scaling: scale the axis to view all data that is visible.
    MAXIMUM, // Scale the axis to the maximum value of histogram.
    MEAN_PLUS_THREE_SIGMA // Scale the axis to "mean + 3 * sigma".
  };

  /// Set/Get the left axis mode, which controls the axis range computation.
  ///   VTK_AUTO: VTK auto scaling. Scale the axis to view all data that is visible.
  ///   MAXIMUM: Scale the axis to the maximum value of histogram.
  ///   MEAN_PLUS_THREE_SIGMA: Scale the axis to "mean + 3 * sigma".
  /// Default mode is VTK_AUTO.
  void SetLeftAxisMode(int mode);
  int GetLeftAxisMode();

  /// Set input for histogram
  virtual void SetHistogramInputData(vtkTable* table, const char* xAxisColumn,
    const char* yAxisColumn);

  /// Set scalar visibility in the histogram plot bar
  virtual void SetScalarVisibility(bool visible);

  /// Set lookup table
  virtual void SetLookupTable(vtkScalarsToColors* lut);

  /// Set the color array name
  virtual void SelectColorArray(const char* arrayName);

protected:
  vtkNew<vtkPlotBar> HistogramPlotBar;
  int LeftAxisMode;

private:
  vtkScalarsToColorsHistogramChart();
  virtual ~vtkScalarsToColorsHistogramChart();
};

#endif // __vtkScalarsToColorsHistogramChart_h


text:
.reserved {
	background: #FFF;
    border: 2px solid lightgreen !important;
    border-width: 10px 1px !important;
	color: #000 !important;;
	}
.integer {
	background: #333;
	color: #CCC;
	border: 1px solid #eee;
	}
.any {
	background: orange;
	color: #666;
	border: 1px solid #eee;
	}
.regexp {
	background: purple;
	border: 1px solid lime;
	}
.block {
	background: lime;
	border: 1px solid purple;
	}
.concat {
    background: #EEE;
    border: 1px solid #FC0;
    color: #000000;
	}
.alternation {
    background: #FF0000;
    border: 1px solid #333;
	}
.quantifier {
	background: yellow;
	border: 1px solid blue;
	}
.charclass {
	background: blue;
	color: #fff;
	border: 1px solid yellow;
	}
.negated {
	background: darkblue;
	}
.characters_range {
	background: #A52A2A;
    border: 1px solid #FFF;
    color: #FFFFFF;
	}
.charclass .reserved,
.character {
	background: green !important;
	border: 1px solid #BBB;
	color: white;
	}


text:
namespace gpu {

VulkanCommandPool::VulkanCommandPool(VulkanDeviceQueue* device_queue)
    : device_queue_(device_queue) {}

VulkanCommandPool::~VulkanCommandPool() {
  DCHECK_EQ(0u, command_buffer_count_);
  DCHECK_EQ(static_cast<VkCommandPool>(VK_NULL_HANDLE), handle_);
}

bool VulkanCommandPool::Initialize(bool use_protected_memory) {
  VkCommandPoolCreateInfo command_pool_create_info = {};
  command_pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  command_pool_create_info.flags =
      VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  command_pool_create_info.queueFamilyIndex =
      device_queue_->GetVulkanQueueIndex();
  if (use_protected_memory) {
    command_pool_create_info.flags |= VK_COMMAND_POOL_CREATE_PROTECTED_BIT;
  }

  VkResult result =
      vkCreateCommandPool(device_queue_->GetVulkanDevice(),
                          &command_pool_create_info, nullptr, &handle_);
  if (VK_SUCCESS != result) {
    DLOG(ERROR) << "vkCreateCommandPool() failed: " << result;
    return false;
  }

  use_protected_memory_ = use_protected_memory;

  return true;
}

void VulkanCommandPool::Destroy() {
  DCHECK_EQ(0u, command_buffer_count_);
  if (VK_NULL_HANDLE != handle_) {
    vkDestroyCommandPool(device_queue_->GetVulkanDevice(), handle_, nullptr);
    handle_ = VK_NULL_HANDLE;
  }
}

std::unique_ptr<VulkanCommandBuffer>
VulkanCommandPool::CreatePrimaryCommandBuffer() {
  std::unique_ptr<VulkanCommandBuffer> command_buffer(new VulkanCommandBuffer(
      device_queue_, this, true, use_protected_memory_));
  if (!command_buffer->Initialize())
    return nullptr;

  return command_buffer;
}

std::unique_ptr<VulkanCommandBuffer>
VulkanCommandPool::CreateSecondaryCommandBuffer() {
  auto command_buffer = std::make_unique<VulkanCommandBuffer>(
      device_queue_, this, false, use_protected_memory_);
  if (!command_buffer->Initialize())
    return nullptr;

  return command_buffer;
}

void VulkanCommandPool::IncrementCommandBufferCount() {
  command_buffer_count_++;
}

void VulkanCommandPool::DecrementCommandBufferCount() {
  DCHECK_LT(0u, command_buffer_count_);
  command_buffer_count_--;
}

}  // namespace gpu


text:
/*
 * BEGIN CSS RESET
 *
 * http://meyerweb.com/eric/tools/css/reset/
 *  v2.0 | 20110126
 *  License: none (public domain)
 */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}

/*
 * END CSS RESET
 */

/*
 * Theme colors:
 * - Dark primary:  #512da8
 * - Primary:       #673ab7
 * - Light primary: #d1c4e9
 * - Text/icons:    #fff
 * - Accent color:  #607d8b (around icons)
 * - Primary text:  #212121
 * - Second. text:  #727272
 * - Border color:  #b6b6b6
 */

html, body {
  display: flex;
  flex-direction: column;
  color: #212121;
  font: lighter 16px/1.25em Helvetica, Geneva, Arial, sans-serif;
}
body { min-height: 100vh; }

header:first-child a,
footer:last-child a {
  color: #d1c4e9;
}
header:first-child a:hover,
footer:last-child a:hover {
  color: #fff;
}
header:first-child a:active,
footer:last-child a:active {
  color: #607d8b;
}

header:first-child {
  color: #fff;
  background: #673ab7;
}

header:first-child h1,
header:first-child h2 {
  display: inline-block;
  padding: 12px;
}
header:first-child h1 {
  font-size: 1.3em;
  border-right: 1px solid #b6b6b6;
}
header:first-child h2 { font-size: 1em; }
header:first-child nav { float: right; }
header:first-child nav ul { padding: 3px; }
header:first-child nav ul li {
  display: inline-block;
  padding: 10px 15px;
}
header:first-child nav ul li { border-left: 1px solid #b6b6b6; }

main {
  display: flex;
  flex: 1;
  flex-direction: column;
}

main img { object-fit: none; }
main h2 { font-size: 24px; }

.imagelist {
  flex-direction: row;
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-around;
}
.imagelist figure { padding: 2rem; }

footer :not(main) {
  padding: 12px;
  text-align: center;
  color: #fff;
  background: #212121;
}
footer :not(main) a { padding: 0; }

#section-comments blockquote {
	padding: 20px;
}
#section-comments blockquote footer {
	text-indent: 1rem;
}

.setup-admin {
  max-height: 500px;
  width: 80%;
  height: 80%;
  padding: 1rem;
}
.setup-admin form input,
.setup-admin form label { font-size: 1.1rem; }
.setup-admin form {
  display: flex;
  flex-direction: column;
}
form input { margin-bottom: 1rem; }
form input:last-child {
  margin-bottom: 0;
  margin-top: 1.5rem;
  font-size: 1.2rem;
}

.center { margin: auto; }
.runsetup { font-size: 2rem; }

.comments .number::after  { content: " ⌨"; }
.likes .number::after     { content: " ♥"; }


text:
class SimplifyActivitySchedule < ActiveRecord::Migration
  def up
    change_table :activities do |t|
      t.remove :return_depart_time, :depart_time
      t.rename :return_arrive_time, :return
      t.rename :start, :leave
    end
  end

  def down
    change_table :activities do |t|
      t.time :return_depart_time
      t.time :depart_time
      t.rename :return, :return_arrive_time
      t.rename :leave, :start
    end
  end
end


text:
using System;

namespace SharpKit.Html.svg
{

using SharpKit.JavaScript;
using SharpKit.Html.fileapi;
using SharpKit.Html.html.shadow;
using SharpKit.Html.html.track;
using SharpKit.Html.inspector;
using SharpKit.Html.loader.appcache;
using SharpKit.Html.battery;
using SharpKit.Html.filesystem;
using SharpKit.Html.gamepad;
using SharpKit.Html.geolocation;
using SharpKit.Html.indexeddb;
using SharpKit.Html.intents;
using SharpKit.Html.mediasource;
using SharpKit.Html.mediastream;
using SharpKit.Html.navigatorcontentutils;
using SharpKit.Html.networkinfo;
using SharpKit.Html.notifications;
using SharpKit.Html.proximity;
using SharpKit.Html.quota;
using SharpKit.Html.speech;
using SharpKit.Html.vibration;
using SharpKit.Html.webaudio;
using SharpKit.Html.webdatabase;
using SharpKit.Html.plugins;
using SharpKit.Html.storage;
using SharpKit.Html.svg;
using SharpKit.Html.workers;

[JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "SVGZoomEvent")]
public partial class SvgZoomEvent : UIEvent
{
	public  SvgRect zoomRectScreen {get; set; }
	public  double previousScale {get; set; }
	public  SvgPoint previousTranslate {get; set; }
	public  double newScale {get; set; }
	public  SvgPoint newTranslate {get; set; }
}

}


text:
package org.apereo.cas.adaptors.duo.web;

import org.apereo.cas.adaptors.duo.DuoSecurityUserAccount;
import org.apereo.cas.adaptors.duo.DuoSecurityUserAccountStatus;
import org.apereo.cas.adaptors.duo.authn.DuoSecurityAuthenticationService;
import org.apereo.cas.adaptors.duo.authn.DuoSecurityMultifactorAuthenticationProvider;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.mfa.DuoSecurityMultifactorProperties;
import org.apereo.cas.util.spring.ApplicationContextProvider;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link DuoSecurityUserAccountStatusEndpointTests}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@SpringBootTest(classes = RefreshAutoConfiguration.class)
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Tag("MFA")
public class DuoSecurityUserAccountStatusEndpointTests {
    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @Autowired
    private CasConfigurationProperties casProperties;

    @Test
    public void verifyOperation() {
        ApplicationContextProvider.holdApplicationContext(applicationContext);

        val account = new DuoSecurityUserAccount("casuser");
        account.setMessage("User is valid");
        account.setStatus(DuoSecurityUserAccountStatus.AUTH);

        val duoService = mock(DuoSecurityAuthenticationService.class);
        when(duoService.ping()).thenReturn(true);
        when(duoService.getApiHost()).thenReturn("https://api.duosecurity.com");
        when(duoService.getUserAccount(eq("casuser"))).thenReturn(account);

        val bean = mock(DuoSecurityMultifactorAuthenticationProvider.class);
        when(bean.getId()).thenReturn(DuoSecurityMultifactorProperties.DEFAULT_IDENTIFIER);
        when(bean.getDuoAuthenticationService()).thenReturn(duoService);
        when(bean.matches(eq(DuoSecurityMultifactorProperties.DEFAULT_IDENTIFIER))).thenReturn(true);
        ApplicationContextProvider.registerBeanIntoApplicationContext(applicationContext, bean, "duoProvider");

        val indicator = new DuoSecurityUserAccountStatusEndpoint(casProperties, this.applicationContext);
        val result = indicator.fetchAccountStatus("casuser", DuoSecurityMultifactorProperties.DEFAULT_IDENTIFIER);
        assertNotNull(result);
        assertTrue(result.containsKey(DuoSecurityMultifactorProperties.DEFAULT_IDENTIFIER));
    }
}


text:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/a2r"
    android:dither="true"
    android:gravity="center"
    android:tileMode="disabled" />


text:
/*
 * $Id$
 */

/*

Copyright (c) 2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.jetty;

import org.lockss.util.Logger;
import org.mortbay.html.Tag;

import java.io.IOException;
import java.io.Writer;

/**
 * A button element for Jetty. This provides an element that is represented by
 * the HTML button element rather than an input element. This means that submit
 * buttons can have a separate label and value, supporting i18n.
 */
public class Button extends Tag {

  static Logger log = Logger.getLogger("Button");

  /** The text displayed on the button. This can be internationalised. */
  protected String label;

  /**
   * Create a button.
   * @param key    the name of the button
   * @param value  the value submitted by the button
   * @param type   the type of the button, such as submit, reset, cancel
   * @param label  the text displayed on the button
   */
  public Button(String key, String value, String type, String label) {
    super(key);
    this.label = label;
    // Add attributes to the map
    attribute("name", key);
    attribute("value", value);
    attribute("type", type);
  }

  public void write(Writer out) throws IOException {
    out.write( String.format(
        "<button %s>%s</button>",
        combineAttributes(), label)
    );
  }

  /**
   * Combine the attribute key/value pairs into a string which can be inserted
   * into the element's opening tag.
   * @return
   */
  protected String combineAttributes() {
    StringBuilder sb = new StringBuilder();
    for (Object k : attributeMap.keySet()) {
      // Jetty seems to quote string values before putting them in the
      // attributeMap, so don't quote them again!
      sb.append(" ").append(k).append("=").append(attributeMap.get(k));
    }
    return sb.toString();
  }

}


text:
package org.apache.jackrabbit.test.api.query;

import javax.jcr.query.Query;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ItemNotFoundException;

/**
 * Test the method {@link Query#getStoredQueryPath()}.
 *
 * @test
 * @sources GetPersistentQueryPathLevel1Test.java
 * @executeClass org.apache.jackrabbit.test.api.query.GetPersistentQueryPathLevel1Test
 * @keywords level1
 */
public class GetPersistentQueryPathLevel1Test extends AbstractQueryTest {

    /** A read-only session */
    private Session session;

    /**
     * Sets up the test cases
     */
    protected void setUp() throws Exception {
        isReadOnly = true;
        super.setUp();
        session = helper.getReadOnlySession();
        testRootNode = session.getRootNode().getNode(testPath);
    }

    /**
     * Releases the session acquired in setUp().
     */
    protected void tearDown() throws Exception {
        if (session != null) {
            session.logout();
            session = null;
        }
        super.tearDown();
    }

    /**
     * Tests if a non-persistent query throws an {@link ItemNotFoundException}
     * when {@link Query#getStoredQueryPath()} is called.
     */
    public void testGetStoredQueryPath() throws RepositoryException {
        String statement = "/" + jcrRoot;
        Query q = session.getWorkspace().getQueryManager().createQuery(statement, Query.XPATH);
        try {
            q.getStoredQueryPath();
            fail("Query.getStoredQueryPath() on a transient query must throw an ItemNotFoundException.");
        } catch (ItemNotFoundException e) {
            // success
        }
    }
}


text:
using NetMud.DataStructure.Architectural;
using System;
using System.Collections.Generic;

namespace NetMud.Models.Admin
{
    public class ManageContentApprovalsViewModel : PagedDataModel<IKeyedData>
    {
        public ManageContentApprovalsViewModel(IEnumerable<IKeyedData> items)
            : base(items)
        {
            CurrentPageNumber = 1;
            ItemsPerPage = 20;
        }

        internal override Func<IKeyedData, bool> SearchFilter
        {
            get
            {
                return item => item.Name.ToLower().Contains(SearchTerms.ToLower());
            }
        }

        internal override Func<IKeyedData, object> OrderPrimary
        {
            get
            {
                return item => item.Name;
            }
        }

        internal override Func<IKeyedData, object> OrderSecondary
        {
            get
            {
                return null;
            }
        }
    }

}


text:
(function () {
    "use strict";

    const exec = require("child_process").exec,
        path = require("path");

    const DEBUG_DOMAIN = "debugDomain";

    let _domainManager;

    function init(domainManager) {
        _domainManager = domainManager;
        if (!_domainManager.hasDomain(DEBUG_DOMAIN)) {
            _domainManager.registerDomain(DEBUG_DOMAIN, {major: 0, minor: 1});
        }

        function handleWasm2Wast(projectId, src, callback) {
            const sourcePath = path.join(process.cwd(), "projects", projectId);
            const source = path.join(sourcePath, src);
            const output = path.join(path.dirname(source), path.basename(src, ".wasm") + ".wast");

            const wabtPath = path.join(process.cwd(), "tools", "wabt");
            const wasm2wastBin = path.join(wabtPath, "bin", "wasm2wast");

            const command = wasm2wastBin + " " + source + " -o " + output;

            let child = exec(command, { cwd: sourcePath });

            child.on("exit", () => {
                callback(null);
            });

            child.on("error", (err) => {
                callback(err);
            });
        }

        function handleWast2Wasm(projectId, src, callback) {
            const sourcePath = path.join(process.cwd(), "projects", projectId);
            const source = path.join(sourcePath, src);
            const output = path.join(path.dirname(source), path.basename(src, ".wast") + ".wasm");

            const wabtPath = path.join(process.cwd(), "tools", "wabt");
            const wast2wasmBin = path.join(wabtPath, "bin", "wast2wasm");

            const command = wast2wasmBin + " " + source + " -o " + output;

            let child = exec(command, { cwd: sourcePath });

            child.on("exit", () => {
                callback(null);
            });

            child.on("error", (err) => {
                callback(err);
            });
        }

        function handleInstall(projectId, callback) {
            const sourcePath = path.join(process.cwd(), "projects", projectId);
            var command = sourcePath + "/install.sh";
            let child = exec(command, { cwd: sourcePath });

            child.on("error", (err) => {
                console.error("Error");
                callback(err);
            });
        }

        _domainManager.registerCommand(
            DEBUG_DOMAIN,
            "wasm2wast",
            handleWasm2Wast,
            true,
            "Translate wasm to wast",
            [
                {name: "projectId", type: "string"},
                {name: "src", type: "string"}
            ],
            []
        );

        _domainManager.registerCommand(
            DEBUG_DOMAIN,
            "wast2wasm",
            handleWast2Wasm,
            true,
            "Translate wast to wasm",
            [
                {name: "projectId", type: "string"},
                {name: "src", type: "string"}
            ],
            []
        );

        _domainManager.registerCommand(
            DEBUG_DOMAIN,
            "install",
            handleInstall,
            true,
            "Test for install",
            [
                {name: "projectId", type: "string"},
                {name: "src", type: "string"}
            ],
            []
        );
    }

    exports.init = init;
}());


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pregunta.Me.Core.Administration;
using Pregunta.Me.Core.ValueObjects;

namespace Pregunta.Me.Services.Operators.Questions
{
    internal class QuestionRequest : IQuestionRequest
    {
        public static QuestionRequest Issue(InquirerInfo askedBy, ExpertInfo askedTo, string questionText)
        {
            return new QuestionRequest(askedBy, askedTo, questionText);
        }

        private QuestionRequest(InquirerInfo askedBy, ExpertInfo askedTo, string text)
        {
            this.AskedBy = askedBy;
            this.AskTo = askedTo;
            this.QuestionText = text;
        }

        public InquirerInfo AskedBy { get; private set; }
        public ExpertInfo AskTo { get; private set; }
        public string QuestionText { get; private set; }
        public Question DraftQuestion()
        {
            return new Question(this.QuestionText);
        }
    }
}