text:
Changelog
=========

0.6.2 (2013-09-05)
------------------
- Fix bug that resulted in a ``UnicodeEncodeError`` when tagging text with non-ascii characters.
- Add ``DecisionTreeClassifier``.
- Add ``labels()`` and ``train()`` methods to classifiers.

0.6.1 (2013-09-01)
------------------
- Classifiers can be trained and tested on CSV, JSON, or TSV data.
- Add basic WordNet lemmatization via the ``Word.lemma`` property.
- ``WordList.pluralize()`` and ``WordList.singularize()`` methods return ``WordList`` objects.

0.6.0 (2013-08-25)
------------------
- Add Naive Bayes classification. New ``text.classifiers`` module, ``TextBlob.classify()``, and ``Sentence.classify()`` methods.
- Add parsing functionality via the ``TextBlob.parse()`` method. The ``text.parsers`` module currently has one implementation (``PatternParser``).
- Add spelling correction. This includes the ``TextBlob.correct()`` and ``Word.spellcheck()`` methods.
- Update NLTK.
- Backwards incompatible: ``clean_html`` has been deprecated, just as it has in NLTK. Use Beautiful Soup's ``soup.get_text()`` method for HTML-cleaning instead.
- Slight API change to language translation: if ``from_lang`` isn't specified, attempts to detect the language.
- Add ``itokenize()`` method to tokenizers that returns a generator instead of a list of tokens.

0.5.3 (2013-08-21)
------------------
- Unicode fixes: This fixes a bug that sometimes raised a ``UnicodeEncodeError`` upon creating accessing ``sentences`` for TextBlobs with non-ascii characters.
- Update NLTK

0.5.2 (2013-08-14)
------------------
- `Important patch update for NLTK users`: Fix bug with importing TextBlob if local NLTK is installed.
- Fix bug with computing start and end indices of sentences.

0.5.1 (2013-08-13)
------------------
- Fix bug that disallowed display of non-ascii characters in the Python REPL.
- Backwards incompatible: Restore ``blob.json`` property for backwards compatibility with textblob<=0.3.10. Add a ``to_json()`` method that takes the same arguments as ``json.dumps``.
- Add ``WordList.append`` and ``WordList.extend`` methods that append Word objects.

0.5.0 (2013-08-10)
------------------
- Language translation and detection API!
- Add ``text.sentiments`` module. Contains the ``PatternAnalyzer`` (default implementation) as well as a ``NaiveBayesAnalyzer``.
- Part-of-speech tags can be accessed via ``TextBlob.tags`` or ``TextBlob.pos_tags``.
- Add ``polarity`` and ``subjectivity`` helper properties.

0.4.0 (2013-08-05)
------------------
- New ``text.tokenizers`` module with ``WordTokenizer`` and ``SentenceTokenizer``. Tokenizer instances (from either textblob itself or NLTK) can be passed to TextBlob's constructor. Tokens are accessed through the new ``tokens`` property.
- New ``Blobber`` class for creating TextBlobs that share the same tagger, tokenizer, and np_extractor.
- Add ``ngrams`` method.
- `Backwards-incompatible`: ``TextBlob.json()`` is now a method, not a property. This allows you to pass arguments (the same that you would pass to ``json.dumps()``).
- New home for documentation: https://textblob.readthedocs.org/
- Add parameter for cleaning HTML markup from text.
- Minor improvement to word tokenization.
- Updated NLTK.
- Fix bug with adding blobs to bytestrings.

0.3.10 (2013-08-02)
-------------------
- Bundled NLTK no longer overrides local installation.
- Fix sentiment analysis of text with non-ascii characters.

0.3.9 (2013-07-31)
------------------
- Updated nltk.
- ConllExtractor is now Python 3-compatible.
- Improved sentiment analysis.
- Blobs are equal (with `==`) to their string counterparts.
- Added instructions to install textblob without nltk bundled.
- Dropping official 3.1 and 3.2 support.

0.3.8 (2013-07-30)
------------------
- Importing TextBlob is now **much faster**. This is because the noun phrase parsers are trained only on the first call to ``noun_phrases`` (instead of training them every time you import TextBlob).
- Add text.taggers module which allows user to change which POS tagger implementation to use. Currently supports PatternTagger and NLTKTagger (NLTKTagger only works with Python 2).
- NPExtractor and Tagger objects can be passed to TextBlob's constructor.
- Fix bug with POS-tagger not tagging one-letter words.
- Rename text/np_extractor.py -> text/np_extractors.py
- Add run_tests.py script.

0.3.7 (2013-07-28)
------------------

- Every word in a ``Blob`` or ``Sentence`` is a ``Word`` instance which has methods for inflection, e.g ``word.pluralize()`` and ``word.singularize()``.

- Updated the ``np_extractor`` module. Now has an new implementation, ``ConllExtractor`` that uses the Conll2000 chunking corpus. Only works on Py2.


text:
package com.rox.emu.processor.mos6502.op.util;

import com.rox.emu.UnknownOpCodeException;
import com.rox.emu.processor.mos6502.Mos6502;
import com.rox.emu.processor.mos6502.op.Mos6502AddressingMode;
import com.rox.emu.processor.mos6502.op.Mos6502OpCode;
import com.rox.emu.processor.mos6502.op.Mos6502Operation;

import java.util.EnumSet;

import static com.rox.emu.processor.mos6502.op.Mos6502Operation.*;

/**
 * Utility for converting internal {@link Mos6502} {@link Mos6502OpCode} representation names to human readable descriptions
 *
 * e.g.  ADC_I → "ADC (Immediate)"
 *
 * @author Ross Drew
 */
public class OpCodeConverter {
    /**
     * The separator used to delimit different elements in the {@link String} enum id
     */
    public static final String TOKEN_SEPARATOR = "_";
    /**
     * The index of the op-code name in the {@link String} enum id,
     * using the token delimiter {@value TOKEN_SEPARATOR}
     */
    public static final int CODE_I = 0;
    /**
     * The index of the addressing mode token in the {@link String} enum id,
     * using the token delimiter {@value TOKEN_SEPARATOR}
     */
    public static final int ADDR_I = CODE_I + 1;
    /**
     * The index of the indexing mode token in the {@link String} enum id,
     * using the token delimiter {@value TOKEN_SEPARATOR}
     */
    public static final int INDX_I = ADDR_I + 1;

    private OpCodeConverter(){/* Used to hide implicitly public constructor for a utility class*/}

    /**
     * Extract a command line op-code of the {@link Mos6502} instruction set from the {@link String} representation of an {@link Mos6502OpCode}.
     *
     * @param internalOpCodeName the {@link String} representation of an {@link Mos6502OpCode}
     * @return A {@link String} instruction from the {@link Mos6502} instruction set, associated with the intended {@link Mos6502OpCode}
     */
    public static String getOpCode(String internalOpCodeName){
        final String[] tokens = internalOpCodeName.split(TOKEN_SEPARATOR);
        return tokens[CODE_I];
    }

    /**
     * @param internalOpCodeName {@link String} representation of an {@link Mos6502OpCode}
     * @return the {@link Mos6502Operation} associated with this {@link Mos6502OpCode}
     */
    public static Mos6502Operation getOperation(final String internalOpCodeName) {
        return valueOf(getOpCode(internalOpCodeName));
    }

    /**
     * Extract the {@link Mos6502} {@link Mos6502AddressingMode} from the {@link String} representation of an {@link Mos6502OpCode}.
     *
     * @param internalOpCodeName the {@link String} representation of an {@link Mos6502OpCode}
     * @return An {@link Mos6502AddressingMode} object that represents the intended addressing mode of the {@link Mos6502OpCode} in question
     */
    public static Mos6502AddressingMode getAddressingMode(String internalOpCodeName){
        final String[] tokens = internalOpCodeName.split(TOKEN_SEPARATOR);
        if (tokens.length <= ADDR_I) {
            //XXX Write this less ugly
            if (EnumSet.of(JSR,BPL,BMI,BVC,BVS,BCC,BCS,BNE,BEQ).contains(getOperation(internalOpCodeName)))
                return Mos6502AddressingMode.RELATIVE;

            return Mos6502AddressingMode.IMPLIED;
        }

        final String addressingModeDescriptor = tokens[ADDR_I];

        //XXX Not pretty but necessary for proper test coverage - update if JaCoCo ever learns to deal with it
        final String indexToken = (tokens.length <= INDX_I) ? "" : tokens[INDX_I];
        if ("I".equals(addressingModeDescriptor))
            return Mos6502AddressingMode.IMMEDIATE;
        else if ("A".equals(addressingModeDescriptor))
            return Mos6502AddressingMode.ACCUMULATOR;
        else if ("Z".equals(addressingModeDescriptor))
            return withIndexing(Mos6502AddressingMode.ZERO_PAGE, indexToken);
        else if ("ABS".equals(addressingModeDescriptor))
            return withIndexing(Mos6502AddressingMode.ABSOLUTE, indexToken);
        else if ("IND".equals(addressingModeDescriptor))
            return withIndexing(Mos6502AddressingMode.INDIRECT, indexToken);
        else
            throw new UnknownOpCodeException("Unrecognised addressing mode " + addressingModeDescriptor, internalOpCodeName);
    }

    private static Mos6502AddressingMode withIndexing(final Mos6502AddressingMode addressingMode, final String indexToken){
        if ("IX".equalsIgnoreCase(indexToken))
            return addressingMode.xIndexed();
        else if ("IY".equalsIgnoreCase(indexToken))
            return addressingMode.yIndexed();
        else
            return addressingMode;
    }
}

redpajama_set_name: RedPajamaGithub


text:
This chapter provides a step-by-step guide on how to deploy your Django applications. We'll be looking at deploying applications on [PythonAnywhere](https://www.pythonanywhere.com/?affiliate_id=000116e3), an online IDE and web hosting service. The service provides in-browser access to the server-based Python and Bash command line interfaces, meaning you can interact with PythonAnywhere's servers just like you would with a regular terminal instance on your own computer. Currently, PythonAnywhere are offering a free account that sets you up with an adequate amount of storage space and CPU time to get a Django application up and running.

I> ### Go Git It!
I> You can do this chapter independently as we have already implemented Rango and it is available from GitHub. If you haven't used Git/GitHub before, you can check out our [chapter on using Git](#chapter-git)).

## Creating a PythonAnywhere Account
First, [sign up for a Beginner PythonAnywhere account](https://www.pythonanywhere.com/?affiliate_id=000116e3). If your application takes off and becomes popular, you can always upgrade your account at a later stage to gain more storage space and CPU time along with a number of other benefits - such as hosting specific domains and SSH abilities, for example.

Once your account has been created, you will have your own little slice of the World Wide Web at `http://<username>.pythonanywhere.com`, where `<username>` is your PythonAnywhere username. It is from this URL that your hosted application will be available.

## The PythonAnywhere Web Interface
The PythonAnywhere web interface contains a *dashboard* which in turn provides a series of different components allowing you to manage your application. The components as [illustrated in the figure below](#pa-interface) include:

- *Consoles*, allowing you to create and interact with Python and Bash console instances;
- *Files*, which allows you to upload to and organise files within your disk quota; and
- *Web Apps*, allowing you to configure settings for your hosted web application;

Other components exist, such as *Notebooks*, but we won't be using them here -- we'll be working primarily with the *consoles* and *web* components. The [PythonAnywhere Wiki](https://www.pythonanywhere.com/wiki/) provides a series of detailed explanations on how to use the other components if you are interested in finding out more.

{#pa-interface}
![The PythonAnywhere dashboard, showing the main components you can use.](images/ch-deploy-pa-interface.png)

## Creating a Virtual Environment
As part of its standard default Bash environment, PythonAnywhere comes with Python 2.7.6 and a number of pre-installed Python Packages (including *Django 1.3.7* and *Django-Registration 0.8*). Since we are using a different setup, we need to select a particular Python version and setup a virtual environment for our application.

First, open a Bash console. From the PythonAnywhere dashboard, click the *$Bash$* button under the *Consoles* component. You will then be taken to a black screen where a terminal will be initialised. When the terminal is ready for you to use (i.e. you see the time presented to you), enter the following commands.

{lang="bash",linenos=off}
	$ mkvirtualenv --python=<python-version> rango

If you've coded up the tutorial using Python 3.x, then change `<python-version>` to either `python3.4`, `python3.5` or `python3.6` (double check what version you used by running `python --version` on your own computer!). If you are using Python 2.7.x, then change `<python-version>` to `python2.7`. The command you enter creates a new virtual environment called `rango` using the version of Python that you specified. For example, below is the output for when we created a Python 2.7 virtual environment.

{lang="bash",linenos=off}
	11:45 ~ $ mkvirtualenv --python=python3.6 rango
	Running virtualenv with interpreter /usr/bin/python3.6
	New python executable in /home/rangodemo2018/.virtualenvs/rango/bin/python3.6
	Also creating executable in /home/rangodemo2018/.virtualenvs/rango/bin/python
	Installing setuptools, pip, wheel...done.
	virtualenvwrapper creating /home/rangodemo2018/.virtualenvs/.../predeactivate
	virtualenvwrapper creating /home/rangodemo2018/.virtualenvs/.../postdeactivate
	virtualenvwrapper creating /home/rangodemo2018/.virtualenvs/.../preactivate
	virtualenvwrapper creating /home/rangodemo2018/.virtualenvs/.../postactivate
	virtualenvwrapper creating /home/rangodemo2018/.virtualenvs/.../get_env_details

Note in the example above, the PythonAnywhere username used is `rangodemo2018` - this will be replaced with your own username. The process of creating the virtual environment will take a little while to complete, after which you will be presented with a slightly different prompt.

{lang="text",linenos=off}
	(rango) 11:45 ~ $

Note the inclusion of `(rango)` compared to the previous command prompt. This signifies that the `rango` virtual environment has been activated, so any package installations will be done within that virtual environment, leaving the wider system setup alone. If you issue the command `ls -la`, you will see that a directory called `.virtualenvs` has been created. This is the directory in which all of your virtual environments and associated packages will be stored. To confirm the setup, issue the command `which pip`. This will print the location in which the active `pip` binary is located - hopefully within `.virtualenvs` and `rango`, as shown in the example below.

{lang="text",linenos=off}
	/home/<username>/.virtualenvs/test/bin/pip

To see what packages are already installed, enter `pip list`. Now we can customise the virtual environment by installing the required packages for our Rango application. Install all the required packages, by issuing the following commands.

{lang="text",linenos=off}
	$ pip install -U django==1.9.10
	$ pip install pillow
	$ pip install django-registration-redux
	$ pip install django-bootstrap-toolkit

**Ensure that you replace the version of Django specified above with the one you used during development. Not doing so will in all probability cause you to get weird, weird exceptions and will result in you pulling out your hair in frustration.** You could alternatively use `pip freeze > requirements.txt` to save your current development environment, and then on PythonAnywhere, run `pip install -r requirements.txt` to install all the packages in one go.

I> ### Waiting to Download...
I> Installing all theses packages may take some time, so you can relax, call a friend, or tweet about our tutorial `@tangowithdjango`!

Once installed, check if Django has been installed with the command `which django-admin.py`. You should receive output similar to the following example.

{lang="text",linenos=off}
	/home/<username>/.virtualenvs/rango/bin/django-admin.py

I> ### Virtual Environments on PythonAnywhere
I> PythonAnywhere also provides instructions on how to setup virtual environments. [Check out their Wiki documentation for more information](https://help.pythonanywhere.com/pages/VirtualEnvForNewerDjango).

### Virtual Environment Switching
Moving between virtual environments can be done pretty easily. PythonAnywhere should have this covered for you. Below, we provide you with a quick tutorial on how to switch between virtual environments.

At your terminal, you can launch into a pre-existing virtual environment with the `workon` command. For example, to load up the `rango` environment, enter:

{lang="text",linenos=off}
	16:48 ~ $ workon rango

where `rango` can be replaced with the name of the virtual environment you wish to use. Your prompt should then change to indicate you are working within a virtual environment. This is shown by the addition of `(rango)` to your prompt.

{lang="text",linenos=off}
	(rango) 16:49 ~ $

You can then leave the virtual environment using the `deactivate` command. Your prompt should then be missing the `(rango)` prefix, with an example shown below.

{lang="text",linenos=off}
	(rango) 16:49 ~ $ deactivate
	16:51 ~ $

### Cloning your Git Repository
Now that your virtual environment for Rango is all setup, you can now clone your Git repository to obtain a copy of your project's files. Clone your repository by issuing the following command from your home directory:

{lang="text",linenos=off}
	$ git clone https://<USERNAME>:<PASSWORD>@github.com/<OWNER>/<REPO_NAME>.git

where you replace - `<USERNAME>` with your GitHub username; - `<PASSWORD>` with your GitHub password; - `<OWNER>` with the username of the person who owns the repository; and - `<REPO_NAME>` with the name of your project's repository.

### Setting Up the Database
With your files cloned, you must then prepare your database. We'll be using the `populate_rango.py` module that we created earlier in the book. As we'll be running the module, you must ensure that you are using the `rango` virtual environment (i.e. you see `(rango)` as part of your prompt - if not, invoke `workon rango`). From your home directory, move into the `tango_with_django_19` directory, then to the `code` directory. This directory will be named after your git repository, so the name may differ. For example, if you called your repository `twd`, the directory will also be called `twd`. Depending upon how you configured your repository, you should also `cd` into the directory with `manage.py` in it - `tango_with_django_project`. Now issue the following commands.

{lang="text",linenos=off}
	(rango) 16:55 ~/tango_with_django $ python manage.py makemigrations rango
	(rango) 16:55 ~/tango_with_django $ python manage.py migrate
	(rango) 16:56 ~/tango_with_django $ python populate_rango.py
	(rango) 16:57 ~/tango_with_django $ python manage.py createsuperuser

As discussed earlier in the book, the first command creates the migrations for the `rango` app, then the `migrate` command creates the *SQLlite3* database. Once the database is created, the database can be populated and a superuser created.

## Setting up Your Web Application
Now that the database is setup, we need to configure the PythonAnywhere [*NGINX*](https://www.nginx.com/resources/wiki/) Web server to serve up your application. From PythonAnywhere's dashboard, open up the *Web* tab. On the left of the page that appears, click *Add a new web app.*

A popup box will then appear. Follow the instructions on-screen, and when the time comes, select the *manual configuration* option and complete the wizard. Make sure you select the same Python version as the one you selected earlier.

In a new tab or window in your Web browser, go visit your PythonAnywhere subdomain at the address `http://<username>.pythonanywhere.com`. You should be presented with the [default `Hello, World!` webpage, as shown below](#hello-world). This is because the WSGI script is currently serving up this page, and not your Django application. This is what we need to change next.

{#hello-world}
![The default PythonAnywhere *hello world* webpage.](images/ch-deploy-hello-world.png)

### Configure the Virtual Environment
To set the virtual environment for your app, navigate again to the *Web* tab in PythonAnywhere's interface. From there, scroll all the way down under you see the heading *Virtualenv*.

Enter in the path to your virtual environment. Assuming you created a virtual environment called `rango` the path would be:

{lang="text",linenos=off}
	/home/<username>/.virtualenvs/rango

You can start a console to check if it is successful.

Now in the *Code* section, you can set the path to your web applications source code.

{lang="text",linenos=off}
	/home/<username>/<path-to>/tango_with_django_project/

Note that this path should be pointing to the directory with your project's `manage.py` file within it.
If for example you cloned a repository called `tango_with_django19` into your account's home directory, the path will be something like:

{lang="text",linenos=off}
	/home/<username>/tango_with_django_19/code/tango_with_django_project/

### Configuring the WSGI Script
The [Web Server Gateway Interface](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface), a.k.a. *WSGI* provides a simple and universal interface between Web servers and Web applications. PythonAnywhere uses WSGI to bridge the server-application link and map incoming requests to your subdomain to your web application.

To configure the WSGI script, navigate to the *Web* tab in PythonAnywhere's interface. Under the Code heading you can see a link to the WSGI configuration file in the Code section: e.g. `/var/www/<username>_pythonanywhere_com_wsgi.py`.

The people at PythonAnywhere have set up a sample WSGI file for us with several possible configurations. For your Web application, you'll need to configure the Django section of the file by clicking on the link to open a simple editor. The example below demonstrates a possible configuration for your application.

{lang="python",linenos=off}
	import os
	import sys

	# Add your project's directory the PYTHONPATH
	path = '/home/<username>/<path-to>/tango_with_django_project/'
	if path not in sys.path:
	    sys.path.append(path)

	# Move to the project directory
	os.chdir(path)

	# Tell Django where the settings.py module is located
	os.environ.setdefault('DJANGO_SETTINGS_MODULE',
	                      'tango_with_django_project.settings')

	# Import your Django project's configuration
	import django
	django.setup()

	# Import the Django WSGI to handle any requests
	import django.core.handlers.wsgi
	application = django.core.handlers.wsgi.WSGIHandler()

Ensure that you replace `<username>` with your PythonAnywhere username, and update any other path settings to suit your application. You should also remove all other code from the WSGI configuration script to ensure no conflicts take place.

The script adds your project's directory to the `PYTHONPATH` for the Python instance that runs your web application. This allows Python to access your project's modules. If you have additional paths to add, you can easily insert them here. You can then specify the location of your project's `settings.py` module. The final step is to include the Django WSGI handler and invoke it for your application.

When you have completed the WSGI configuration, click the *Save* button at the top-right of the webpage. Navigate back to the *Web* tab within the PythonAnywhere interface, and click the *Reload* button at the top of the page (the big green one). When the application is reloaded, you can then revisit your PythonAnywhere subdomain at `http://<username>.pythonanywhere.com`. Hopefully, if all went well, you should see your application up and running. If not, check through your scripts and paths carefully. Double check your paths by actually visiting the directories, and use `pwd` to confirm the path. If you see a `DisallowedHost` exception, you need to follow the steps below.

I> ### Bad Gateway Errors
I> During testing, we noted that you can sometimes receive `HTTP 502 - Bad Gateway` errors instead of your application. Try reloading your application again, and then waiting a longer. If the problem persists, try reloading again. If the problem still persists, [check out your log files](#section-deploy-logfiles) to see if any accesses/errors are occurring, before contacting the PythonAnywhere support.

### Allowing your Hostname
A security feature in more recent versions of Django is that of allowed hosts. By only allowing a particular set of domains to be served by your web server, this reduces the chance that your app could be part of a so-called [HTTP Host Header attack](https://www.acunetix.com/blog/articles/automated-detection-of-host-header-attacks/). You may find that when you run your app for the first time, you see a `DisallowedHost` exception stopping your app from loading.

This is a simple problem to fix, and involves a change in your project's `settings.py` module. First, work out your app's URL on PythonAnywhere. For a basic account, this will be `http://<username>.pythonanywhere.com`, where `<username>` is replaced with your PythonAnywhere username. It's a good idea to edit this file locally (on your own computer), then `git add`, `git commit` and `git push` your changes to your Git repository, before downloading the changes to your PythonAnywhere account. Alternatively, you can edit the file directly on PythonAnywhere by editing the file in the Web interface's files component -- or using a text editor in the terminal, like `nano` or `vi`.

With this information, open your project's `settings.py` module and locate the `ALLOWED_HOSTS` list, which by default will be empty (and found near the top of the file). Add a string with your PythonAnywhere URL into that list -- such that it now looks like the following example.

{lang="python",linenos=off}
	ALLOWED_HOSTS = ['http://<username>.pythonanywhere.com']

If you have edited the file on your own computer, you can now go through the (hopefully) now familiar process of running the `git add settings.py`, `git commit` and `git push` commands to make changes to your Git repository. Once done, you should then run the `git pull` command to retrieve the changes on your PythonAnywhere account. If you have edited the file directly on PythonAnywhere, simply save the file.

All that then remains is for you to reload your PythonAnywhere app. This can be done by clicking the *Reload* button in the PythonAnywhere web components page. Once you've done this, access your app's URL, and you should see your app working, but without static media!

### Assigning Static Paths
We're almost there. One issue that we still have to address is to sort out paths for our application. Doing so will allow PythonAnywhere's servers to serve your static content, for example From the PythonAnywhere dashboard, click the URL of your app and wait for the page to load.

Once loaded, perform the following under the *Static files* header. We essentially are adding in the correct URLs and filesystem paths to allow PythonAnywhere's web server to find and serve your static media files.

First, we should set the location of the Django admin interface's static media files. Click the *Enter URL* link, and type in `/static/admin/`. Click the tick to confirm your input, and then click the *Enter path* link, entering the following long-winded filesystem path (all on a single line).

{lang="python",linenos=off}
	/home/<username>/.virtualenvs/rango/lib/<python-version>/site-packages/django/
	  contrib/admin/static/admin

As usual, replace `<username>` with your PythonAnywhere username. `<python-version>` should also be replaced with `python2.7`, `python3.6`, etc., depending on which Python version you selected. You may also need to change `rango` if this is not the name of your application's virtual environment. Remember to hit return to confirm the path, or click the tick.

Repeat the two steps above for the URL `/static/` and filesystem path `/home/<username>/<path-to>/tango_with_django_project/static`, with the path setting pointing to the `static` directory of your Web application.

With these changes saved, reload your web application by clicking the *Reload* button at the top of the page. Don't forget the about potential for `HTTP 502 - Bad Gateway` errors. Setting the static directories means that when you visit the `admin` interface, it has the predefined Django stylesheets, and that you can access images and scripts. Reload your Web application, and you should now notice that your images are present.

### Search API Key
[Add your search API key]({#section-searchapi-adding-key}) to `search.key` to enable the search functionality in Rango.

### Turning off `DEBUG` Mode
When you application is ready to go, it's a good idea to instruct Django that your application is now hosted on a production server. To do this, open your project's `settings.py` file and change `DEBUG = True` to `DEBUG = False`. This disables [Django's debug mode](https://docs.djangoproject.com/en/1.9/ref/settings/#debug), and removes explicit error messages. You can still however view Python stack traces to debug any exceptions that are raised as people use your app -- see the section below.

## Log Files {#section-deploy-logfiles}
Deploying your Web application to an online environment introduces another layer of complexity. It is likely that you will encounter new and bizarre errors due to unsuspecting problems. When facing such errors, vital clues may be found in one of the three log files that the Web server on PythonAnywhere creates.

Log files can be viewed via the PythonAnywhere web interface by clicking on the *Web* tab, or by viewing the files in `/var/log/` within a Bash console instance. The files provided are:

- `access.log`, which provides a log of requests made to your subdomain;
- `error.log`, which logs any error messages produced by your web application; and
- `server.log`, providing log details for the UNIX processes running your application.

Note that the names for each log file are prepended with your subdomain. For example, `access.log` will have the name `<username>.pythonanywhere.com.access.log`.

When debugging, you may find it useful to delete or move the log files so that you don't have to scroll through a huge list of previous attempts. If the files are moved or deleted, they will be recreated automatically when a new request or error arises.

X> ###Exercises
X> Congratulations, you've successfully deployed Rango!
X>
X> -  Tweet a link of your application to [@tangowithdjango](https://twitter.com/tangowithdjango).
X> -  Tweet or e-mail us to let us know your thoughts on the tutorial!


text:
using namespace std;
using namespace boost;
using namespace apache::thrift::transport;
using namespace apache::thrift;

DECLARE_string(ssl_client_ca_certificate);

namespace impala {

Status ThriftClientImpl::Open() {
  if (!socket_create_status_.ok()) return socket_create_status_;
  try {
    if (!transport_->isOpen()) {
      transport_->open();
    }
  } catch (const TException& e) {
    stringstream msg;
    msg << "Couldn't open transport for " << address_ << "(" << e.what() << ")";
    return Status(msg.str());
  }
  return Status::OK;
}

Status ThriftClientImpl::OpenWithRetry(uint32_t num_tries, uint64_t wait_ms) {
  uint32_t try_count = 0L;
  while (true) {
    ++try_count;
    Status status = Open();
    if (status.ok()) return status;

    LOG(INFO) << "Unable to connect to " << address_;
    if (num_tries == 0) {
      LOG(INFO) << "(Attempt " << try_count << ", will retry indefinitely)";
    } else {
      if (num_tries != 1) {
        // No point logging 'attempt 1 of 1'
        LOG(INFO) << "(Attempt " << try_count << " of " << num_tries << ")";
      }
      if (try_count == num_tries) return status;
    }
    SleepForMs(wait_ms);
  }
}

void ThriftClientImpl::Close() {
  if (transport_.get() != NULL && transport_->isOpen()) transport_->close();
}

Status ThriftClientImpl::CreateSocket() {
  if (!ssl_) {
    socket_.reset(new TSocket(address_.hostname, address_.port));
  } else {
    try {
      TSSLSocketFactory factory;
      // TODO: No need to do this every time we create a socket, the factory can be
      // shared. But since there may be many certificates, this needs some slightly more
      // complex infrastructure to do right.
      factory.loadTrustedCertificates(FLAGS_ssl_client_ca_certificate.c_str());
      socket_ = factory.createSocket(address_.hostname, address_.port);
    } catch (const TException& ex) {
      stringstream err_msg;
      err_msg << "Failed to create socket: " << ex.what();
      return Status(err_msg.str());
    }
  }

  return Status::OK;
}

}


text:
If you feel new features should be added and you know how to implement them:

Ensure any python code is PEP8 compliant, and any HTML is valid HTML5.

Then simply create a Pull Request with a brief summary of your changes and
the update will be reviewed

#### Suggestions

If you have ideas for features or would like to see a new features added
please feel free to open an issue on github to discuss it.

If you believe new advanced features should be implemented that will
take more work and want to make sure the new changes will be a good fit
for the project, then feel free to open an issue on github for discussion.

Any suggestions are greatly appreciated.

#### Bugs
If you find any bugs please open an issue on github
with any details about the bug.

If possible, please list the steps to reproduce
the bug or what happened when the bug occurred.


text:
namespace SharpVectors.Dom.Svg
{
	/// <summary>
	/// The SvgZoomAndPan interface defines attribute "zoomAndPan" and associated constants.
	/// </summary>
	/// <developer>niklas@protocol7.com</developer>
	/// <completed>100</completed>
	public interface ISvgZoomAndPan
	{
		SvgZoomAndPanType ZoomAndPan{get;set;}
	}
}


text:
{% extends "../layout.html" %} {% block content %}

      BETA
      This is a new service – your feedback will help us to improve it.

Find documents

View exceptions

Resolve exception

Resolve exception

Enter the case reference to resolve this exception

      <form action="exceptions-afterresolve.html" method="get">

            Case reference
            <input class="form-control" id="documentname" name="documentname" type="text" value="">

          <input class="button" type="submit" value="Resolve">

          Cancel

      </form>

{% endblock %}


text:
module('Test common function - array');
test('Basic functions added to an array after calling html.array', function(){
    var sut = html.array([1,2,3,4]);
    ok(sut.add, 'ok, add method has been added to the array');
    ok(sut.addRange, 'ok, addRange method has been added to the array');
    ok(sut.each, 'ok, each method has been added to the array');
    ok(sut.select, 'ok, select method has been added to the array');
    ok(sut.where, 'ok, where method has been added to the array');
    ok(sut.reduce, 'ok, reduce method has been added to the array');
    ok(sut.reduceRight, 'ok, reduceRight method has been added to the array');
    ok(sut.find, 'ok, reduceRight method has been added to the array');
    ok(sut.first, 'ok, first method has been added to the array');
    ok(sut.firstOrDefault, 'ok, firstOrDefault method has been added to the array');
    ok(sut.remove, 'ok, remove method has been added to the array');
    ok(sut.removeAt, 'ok, removeAt method has been added to the array');
    ok(sut.orderBy, 'ok, orderBy method has been added to the array');
});

test('Test add method in html.array', function(){
    var sut = html.array([1,2,3,4]);
    sut.add(5);
    ok(sut.length === 5, 'An element has been added to the array');
});

test('Test add method in html.array', function(){
    var sut = html.array([1,2,3,4]);
    sut.add();
    ok(sut.length === 4, 'No element has been added to the array');
});

test('Test select method in html.array - no mapper', function(){
    var sut = html.array([1,2,3,4]);
    throws(
        function() {
            sut.select();
        },
        "Mapping function is required"
    );
});

test('Test select method in html.array - simple mapper', function(){
    var sut = html.array([1,2,3,4]);
    var res = sut.select(function(x){return x+1;});

    ok(res[0] === sut[0] + 1, 'ok, increased 1 at index 0');
    ok(res[2] === sut[2] + 1, 'ok, increased 1 at index 2');
    ok(res[3] === sut[3] + 1, 'ok, increased 1 at index 3');
});

test('Test select method in html.array - square mapper', function(){
    var sut = html.array([1,2,3,4]);
    var res = sut.select(function(x){return x*x;});

    ok(res[0] === sut[0]*sut[0], 'ok, squared element at index 0');
    ok(res[2] === sut[2]*sut[2], 'ok, squared element at index 2');
    ok(res[3] === sut[3]*sut[3], 'ok, squared element at index 3');
});

test('Test select method in html.array - null mapper', function(){
    var sut = html.array([1,2,3,4]);
    var res = sut.select(function(x){return null;});

    ok(res.length === sut.length, 'number of elements are equal');
    ok(res[0] === null, 'return null at index 0');
});

test('Test method where in html.array - no predicate function', function(){
    var sut = html.array([1,2,3,4]);
    throws(
        function(){
            var res = sut.where();
        },
        'Predicate function is required'
    );
});

test('Test method where in html.array - simple predicate, no result', function(){
    var sut = html.array([1,2,3,4]);
    var res = sut.where(function(x){return x > 5;});

    equal(res.length, 0, 'Return array only contains no element');
});

test('Test method where in html.array - simple predicate, got result', function(){
    var sut = html.array([1,2,3,4]);
    var res = sut.where(function(x){return x > 2;});

    equal(res.length, 2, 'Returned array only contains 2 elements');
    equal(res[0], 3, 'Result at index 0 equal to 3');
});

test('Test method where in html.array - complex predicate, got result', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}]);
    var res = sut.where(function(x){return x.Name ==='Nhan';});

    equal(res.length, 1, 'Returned array only contains 1 element');
    deepEqual(res[0], {Name: 'Nhan', Age: 25}, 'Result at index 0 : {Name: \'Nhan\', Age: 25}');
});

test('Test method where in html.array - complex predicate, got 2 elements', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var res = sut.where(function(x){return x.Name ==='Nhan' || x.Age === 12;});

    equal(res.length, 2, 'Returned array only contains 2 elements');
    deepEqual(res[0], {Name: 'Nhan', Age: 25}, 'Result at index 0 : {Name: \'Nhan\', Age: 25}');
    deepEqual(res[1], {Name: 'test', Age: 12}, 'Result at index 0 : {Name: \'test\', Age: 25}');
});

test('Test method reduce in html.array, no iterator', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    throws(
        function(){
            var res = sut.reduce();
        },
        'Iterator function is required'
    );
});

test('Test method reduce in html.array, sum age', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var sum = sut.reduce(function(x, y){return x+y.Age}, 0);

    ok(sum === 1237, 'Sum age of people 1237');
});

test('Test method reduce in html.array, greatest age', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var oldest = sut.reduce(function(x, y){return x.Age>y.Age? x: y}, sut[0]);

    ok(oldest.Age === 1200, 'Oldest guy is 1200 years old');
});

test('Test method reduce in html.array, least age', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var oldest = sut.reduce(function(x, y){return x.Age<y.Age? x: y}, sut[0]);

    ok(oldest.Age === 12, 'Youngest guy is 1200 years old');
});

test('Test method find in html.array, least age', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var oldest = sut.reduce(function(x, y){return x.Age<y.Age? x: y});

    ok(oldest.Age === 12, 'Youngest guy is 1200 years old');
});

test('Test method find in html.array, greatest age', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var oldest = sut.reduce(function(x, y){return x.Age>y.Age? x: y});

    ok(oldest.Age === 1200, 'Oldest guy is 1200 years old');
});

test('Test method first in html.array - first one without any condition', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var first = sut.first();

    deepEqual(first, {Name: 'Nhan', Age: 25}, "The first one is {Name: 'Nhan', Age: 25}");
});

test('Test method first in html.array - first one named "Nhan"', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Nhan', Age: 25}]);
    var first = sut.first(function(x){return x.Name === 'Nhan';});

    deepEqual(first, {Name: 'Nhan', Age: 12}, "The first one is {Name: 'Nhan', Age: 12}");
});

test('Test method first in html.array - first one has 12 years old', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Another Nhan', Age: 12}]);
    var first = sut.first(function(x){return x.Age === 12;});

    deepEqual(first, {Name: 'Nhan', Age: 12}, "The first one is {Name: 'Nhan', Age: 12}");
});

test('Test method first in html.array - no element matches the predicate', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Another Nhan', Age: 12}]);
    throws(
        function(){
            var first = sut.first(function(x){return x.Name === 'No matched element';});
        },
        'Can\'t find any element matches'
    )
});

test('Test method firstOrDefault in html.array - first one without any condition', function(){
    var sut = html.array([{Name: 'Nhan', Age: 25}, {Name: "test", Age: 12}, {Name: "no one", Age: 1200}]);
    var first = sut.firstOrDefault();

    deepEqual(first, {Name: 'Nhan', Age: 25}, "The first one is {Name: 'Nhan', Age: 25}");
});

test('Test method firstOrDefault in html.array - first one named "Nhan"', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Nhan', Age: 25}]);
    var first = sut.firstOrDefault(function(x){return x.Name === 'Nhan';});

    deepEqual(first, {Name: 'Nhan', Age: 12}, "The first one is {Name: 'Nhan', Age: 12}");
});

test('Test method firstOrDefault in html.array - first one has 12 years old', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Another Nhan', Age: 12}]);
    var first = sut.firstOrDefault(function(x){return x.Age === 12;});

    deepEqual(first, {Name: 'Nhan', Age: 12}, "The first one is {Name: 'Nhan', Age: 12}");
});

test('Test method firstOrDefault in html.array - no element matches the predicate', function(){
    var sut = html.array([{Name: "no one", Age: 1200}, {Name: "Nhan", Age: 12}, {Name: 'Another Nhan', Age: 12}]);
    var first = sut.firstOrDefault(function(x){return x.Name === 'No matched element';});

    ok(first === null, 'No element founded, return null');
});

test('Test method indexOf in html.array - not found', function(){
    var sut = html.array([1,2,3,4,5,6,7,8]);
    var index = sut.indexOf(9);

    ok(index === -1, 'Not found');
});

test('Test method indexOf in html.array - index of 100', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    var index = sut.indexOf(100);

    ok(index === 5, 'Index of 100 in array is 5');
});

test('Test method indexOf in html.array - index of 8', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    var index = sut.indexOf(8);

    ok(index === 7, 'Index of 8 in array is 7');
});

test('Test method remove in html.array - remove 8 from list', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'Length of the array is now 8');

    sut.remove(8);

    ok(sut.length === 7, 'Remove 8, the length of the array is now 7');
});

test('Test method remove in html.array - remove 25 but not in the list', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'Length of the array is now 8');

    sut.remove(25);

    ok(sut.length === 8, 'Remove 25 but 25 is not in the lust, the array is still 8');
});

test('Test method removeAt in html.array - removeAt index 2', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'The length of the array is now 8');

    sut.removeAt(2);

    ok(sut.length === 7, 'Remove at index 2, the array now has 7 elements');
});

test('Test method removeAt in html.array - no parameter', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'The length of the array is now 8');

    sut.removeAt();

    ok(sut.length === 8, 'Nothing happens, this means you should pass index what from you want to remove');
});

test('Test method removeAt in html.array - index out of range', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'The length of the array is now 8');

    sut.removeAt(20);

    ok(sut.length === 8, 'Nothing happens, this means you should pass correct index what from you want to remove');
});

test('Test method removeAt in html.array - index out of range', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
    ok(sut.length === 8, 'The length of the array is now 8');

    sut.removeAt(20);

    ok(sut.length === 8, 'Nothing happens, this means you should pass correct index what from you want to remove');
});

test('Test method swap in html.array - swap 2 elements at 2 and 5', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
	ok(sut[2] === 3, 'Item at index 2 is 3');
	ok(sut[4] === 5, 'Item at index 3 is 5');
	sut.swap(2, 4);

    ok(sut[2] === 5, 'Item at index 2 is 3 after swapping');
    ok(sut[4] === 3, 'Item at index 4 is 3 after swapping');
});

test('Test method swap in html.array - swap 2 elements at index 2 and 100 - out of range', function(){
    var sut = html.array([1,2,3,4,5,100,7,8]);
	ok(sut[2] === 3, 'Item at index 2 is 3');
	ok(sut[100] === undefined, 'Item at index 100 is undefined');
	sut.swap(2, 100);

    ok(sut[2] === 3, 'Item at index 2 is still 3, no swapping');
    ok(sut[100] === undefined, 'Item at index 100 is undefined');
});

test('Test method orderBy in html.array - sort by name ascendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'Johnson', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy('Name');
	deepEqual(sut[0], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 0");
	deepEqual(sut[1], {Name: 'Jack', Age: 12} , "{Name: 'Jack', Age: 12} is now at index 1");
	deepEqual(sut[2], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 2");
	deepEqual(sut[3], {Name: 'Johnson', Age: 25}, "{Name: 'Johnson', Age: 25} is now at index 3");
	deepEqual(sut[4], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 4");
	deepEqual(sut[5], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 25} is now at index 5");
	deepEqual(sut[6], {Name: 'Peter', Age: 35}, "{Name: 'Peter', Age: 35} is now at index 6");
	deepEqual(sut[7], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 7");
});

test('Test method orderBy in html.array - sort by name descendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'Johnson', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy({field: 'Name', isAsc: false});
	deepEqual(sut[7], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 7");
	deepEqual(sut[6], {Name: 'Jack', Age: 12} , "{Name: 'Jack', Age: 12} is now at index 6");
	deepEqual(sut[5], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 5");
	deepEqual(sut[4], {Name: 'Johnson', Age: 25}, "{Name: 'Johnson', Age: 25} is now at index 4");
	deepEqual(sut[3], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 25} is now at index 3");
	deepEqual(sut[2], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 2");
	deepEqual(sut[1], {Name: 'Peter', Age: 35}, "{Name: 'Peter', Age: 35} is now at index 1");
	deepEqual(sut[0], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 0");
});

test('Test method orderBy in html.array - sort by name ascendingly and then by age descendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy('Name', {field: 'Age', isAsc: false});
	deepEqual(sut[0], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 0");
	deepEqual(sut[1], {Name: 'Jack', Age: 12} , "{Name: 'Jack', Age: 12} is now at index 1");
	deepEqual(sut[2], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 2");
	deepEqual(sut[3], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 3");
	deepEqual(sut[4], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 200} is now at index 4");
	deepEqual(sut[5], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 5");
	deepEqual(sut[6], {Name: 'Peter', Age: 35}, "{Name: 'Peter', Age: 35} is now at index 6");
	deepEqual(sut[7], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 7");
});

test('Test method orderBy in html.array - sort by name descendingly and then by age descendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy({field: 'Name', isAsc: false}, {field: 'Age', isAsc: false});
	deepEqual(sut[0], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 0");
	deepEqual(sut[1], {Name: 'Peter', Age: 35} , "{Name: 'Peter', Age: 35} is now at index 1");
	deepEqual(sut[2], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 200} is now at index 2");
	deepEqual(sut[3], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 3");
	deepEqual(sut[4], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 4");
	deepEqual(sut[5], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 5");
	deepEqual(sut[6], {Name: 'Jack', Age: 12}, "{Name: 'Jack', Age: 12} is now at index 6");
	deepEqual(sut[7], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 7");
});

test('Test method orderBy in html.array - sort by age descendingly and then by age descendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy({field: 'Age', isAsc: false}, {field: 'Name', isAsc: false});
	deepEqual(sut[0], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 200} is now at index 0");
	deepEqual(sut[1], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 1");
	deepEqual(sut[2], {Name: 'Peter', Age: 35} , "{Name: 'Peter', Age: 35} is now at index 2");
	deepEqual(sut[3], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 4");
	deepEqual(sut[4], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 5");
	deepEqual(sut[5], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 6");
	deepEqual(sut[6], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 7");
	deepEqual(sut[7], {Name: 'Jack', Age: 12}, "{Name: 'Jack', Age: 12} is now at index 8");
});

test('Test method orderBy in html.array - sort by age ascendingly and then by age descendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy('Age', {field: 'Name', isAsc: false});
	deepEqual(sut[0], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 0");
	deepEqual(sut[1], {Name: 'Jack', Age: 12}, "{Name: 'Jack', Age: 12} is now at index 1");
	deepEqual(sut[2], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 2");
	deepEqual(sut[3], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 3");
	deepEqual(sut[4], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 4");
	deepEqual(sut[5], {Name: 'Peter', Age: 35} , "{Name: 'Peter', Age: 35} is now at index 5");
	deepEqual(sut[6], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 6");
	deepEqual(sut[7], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 200} is now at index 7");
});

test('Test method orderBy in html.array - sort by name descendingly and then by age ascendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 25}, {Name: 'Nhan', Age: 200},
						  {Name: 'John', Age: 12}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy({field: 'Name', isAsc: false}, 'Age');
	deepEqual(sut[0], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 0");
	deepEqual(sut[1], {Name: 'Peter', Age: 35} , "{Name: 'Peter', Age: 35} is now at index 1");
	deepEqual(sut[2], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 2");
	deepEqual(sut[3], {Name: 'Nhan', Age: 200}, "{Name: 'Nhan', Age: 200} is now at index 3");
	deepEqual(sut[4], {Name: 'John', Age: 12}, "{Name: 'John', Age: 12} is now at index 5");
	deepEqual(sut[5], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 6");
	deepEqual(sut[6], {Name: 'Jack', Age: 12}, "{Name: 'Jack', Age: 12} is now at index 4");
	deepEqual(sut[7], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 7");
});

test('Test method orderBy in html.array - sort by name ascendingly and then by age ascendingly', function(){
    var sut = html.array([{Name: 'Jack', Age: 12}, {Name: 'Andrew', Age: 21}, {Name: 'Nhan', Age: 210}, {Name: 'Nhan', Age: 25},
						  {Name: 'John', Age: 120}, {Name: 'John', Age: 25}, {Name: 'Peter', Age: 35}, {Name: 'Test', Age: 55}]);

	sut.orderBy('Name', 'Age');
	deepEqual(sut[0], {Name: 'Andrew', Age: 21}, "{Name: 'Andrew', Age: 21} is now at index 0");
	deepEqual(sut[1], {Name: 'Jack', Age: 12}, "{Name: 'Jack', Age: 12} is now at index 1");
	deepEqual(sut[2], {Name: 'John', Age: 25}, "{Name: 'John', Age: 25} is now at index 2");
	deepEqual(sut[3], {Name: 'John', Age: 120}, "{Name: 'John', Age: 12} is now at index 3");
	deepEqual(sut[4], {Name: 'Nhan', Age: 25}, "{Name: 'Nhan', Age: 25} is now at index 4");
	deepEqual(sut[5], {Name: 'Nhan', Age: 210}, "{Name: 'Nhan', Age: 200} is now at index 5");
	deepEqual(sut[6], {Name: 'Peter', Age: 35} , "{Name: 'Peter', Age: 35} is now at index 6");
	deepEqual(sut[7], {Name: 'Test', Age: 55}, "{Name: 'Test', Age: 55} is now at index 7");
});


text:
<!DOCTYPE html>
<html lang="en-US">
<title>Media Controls: time elements accessibility test</title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../media-controls.js"></script>
<video controls></video>
<script>
async_test(t => {
  var video = document.querySelector('video');
  video.src = '../content/test.ogv';

  enableTestMode(video);

  var current_time = currentTimeElement(video);
  var remaining_time = timeRemainingElement(video);

  assert_not_equals(current_time, null);
  assert_not_equals(remaining_time, null);

  assert_equals(current_time.ariaHidden, 'true');
  assert_equals(remaining_time.ariaHidden, 'true');

video.oncanplaythrough = t.step_func_done(_ => {
  assert_equals(current_time.ariaHidden, 'true');
  assert_equals(remaining_time.ariaHidden, 'true');

    video.currentTime = 1;
    video.onseeked = t.step_func(_ => {
      assert_equals(current_time.ariaHidden, 'true');
      assert_equals(remaining_time.ariaHidden, 'true');
    });
  });
});
</script>
</html>


text:
from ctypes import *
from functools import partial

from .utils import *
from .breakpoint import *

class DEBUG_STACK_FRAME_EX(Structure):
  _fields_ = [
      ("InstructionOffset", c_ulonglong),
      ("ReturnOffset", c_ulonglong),
      ("FrameOffset", c_ulonglong),
      ("StackOffset", c_ulonglong),
      ("FuncTableEntry", c_ulonglong),
      ("Params", c_ulonglong * 4),
      ("Reserved", c_ulonglong * 6),
      ("Virtual", c_bool),
      ("FrameNumber", c_ulong),
      ("InlineFrameContext", c_ulong),
      ("Reserved1", c_ulong)
    ]
PDEBUG_STACK_FRAME_EX = POINTER(DEBUG_STACK_FRAME_EX)

class DEBUG_VALUE_U(Union):
  _fields_ = [
      ("I8", c_byte),
      ("I16", c_short),
      ("I32", c_int),
      ("I64", c_long),
      ("F32", c_float),
      ("F64", c_double),
      ("RawBytes", c_ubyte * 24) # Force length to 24b.
    ]

class DEBUG_VALUE(Structure):
  _fields_ = [
      ("U", DEBUG_VALUE_U),
      ("TailOfRawBytes", c_ulong),
      ("Type", c_ulong)
    ]
PDEBUG_VALUE = POINTER(DEBUG_VALUE)

class DebugValueType(IntEnum):
  DEBUG_VALUE_INVALID      = 0
  DEBUG_VALUE_INT8         = 1
  DEBUG_VALUE_INT16        = 2
  DEBUG_VALUE_INT32        = 3
  DEBUG_VALUE_INT64        = 4
  DEBUG_VALUE_FLOAT32      = 5
  DEBUG_VALUE_FLOAT64      = 6
  DEBUG_VALUE_FLOAT80      = 7
  DEBUG_VALUE_FLOAT82      = 8
  DEBUG_VALUE_FLOAT128     = 9
  DEBUG_VALUE_VECTOR64     = 10
  DEBUG_VALUE_VECTOR128    = 11
  DEBUG_VALUE_TYPES        = 12

# UUID for DebugControl7 interface.
DebugControl7IID = IID(0xb86fb3b1, 0x80d4, 0x475b, IID_Data4_Type(0xae, 0xa3, 0xcf, 0x06, 0x53, 0x9c, 0xf6, 0x3a))

class IDebugControl7(Structure):
  pass

class IDebugControl7Vtbl(Structure):
  wrp = partial(WINFUNCTYPE, c_long, POINTER(IDebugControl7))
  idc_getnumbereventfilters = wrp(c_ulong_p, c_ulong_p, c_ulong_p)
  idc_setexceptionfiltersecondcommand = wrp(c_ulong, c_char_p)
  idc_waitforevent = wrp(c_long, c_long)
  idc_execute = wrp(c_long, c_char_p, c_long)
  idc_setexpressionsyntax = wrp(c_ulong)
  idc_addbreakpoint2 = wrp(c_ulong, c_ulong, POINTER(POINTER(DebugBreakpoint2)))
  idc_setexecutionstatus = wrp(c_ulong)
  idc_getexecutionstatus = wrp(c_ulong_p)
  idc_getstacktraceex = wrp(c_ulonglong, c_ulonglong, c_ulonglong, PDEBUG_STACK_FRAME_EX, c_ulong, c_ulong_p)
  idc_evaluate = wrp(c_char_p, c_ulong, PDEBUG_VALUE, c_ulong_p)
  idc_setengineoptions = wrp(c_ulong)
  _fields_ = [
      ("QueryInterface", c_void_p),
      ("AddRef", c_void_p),
      ("Release", c_void_p),
      ("GetInterrupt", c_void_p),
      ("SetInterrupt", c_void_p),
      ("GetInterruptTimeout", c_void_p),
      ("SetInterruptTimeout", c_void_p),
      ("GetLogFile", c_void_p),
      ("OpenLogFile", c_void_p),
      ("CloseLogFile", c_void_p),
      ("GetLogMask", c_void_p),
      ("SetLogMask", c_void_p),
      ("Input", c_void_p),
      ("ReturnInput", c_void_p),
      ("Output", c_void_p),
      ("OutputVaList", c_void_p),
      ("ControlledOutput", c_void_p),
      ("ControlledOutputVaList", c_void_p),
      ("OutputPrompt", c_void_p),
      ("OutputPromptVaList", c_void_p),
      ("GetPromptText", c_void_p),
      ("OutputCurrentState", c_void_p),
      ("OutputVersionInformation", c_void_p),
      ("GetNotifyEventHandle", c_void_p),
      ("SetNotifyEventHandle", c_void_p),
      ("Assemble", c_void_p),
      ("Disassemble", c_void_p),
      ("GetDisassembleEffectiveOffset", c_void_p),
      ("OutputDisassembly", c_void_p),
      ("OutputDisassemblyLines", c_void_p),
      ("GetNearInstruction", c_void_p),
      ("GetStackTrace", c_void_p),
      ("GetReturnOffset", c_void_p),
      ("OutputStackTrace", c_void_p),
      ("GetDebuggeeType", c_void_p),
      ("GetActualProcessorType", c_void_p),
      ("GetExecutingProcessorType", c_void_p),
      ("GetNumberPossibleExecutingProcessorTypes", c_void_p),
      ("GetPossibleExecutingProcessorTypes", c_void_p),
      ("GetNumberProcessors", c_void_p),
      ("GetSystemVersion", c_void_p),
      ("GetPageSize", c_void_p),
      ("IsPointer64Bit", c_void_p),
      ("ReadBugCheckData", c_void_p),
      ("GetNumberSupportedProcessorTypes", c_void_p),
      ("GetSupportedProcessorTypes", c_void_p),
      ("GetProcessorTypeNames", c_void_p),
      ("GetEffectiveProcessorType", c_void_p),
      ("SetEffectiveProcessorType", c_void_p),
      ("GetExecutionStatus", idc_getexecutionstatus),
      ("SetExecutionStatus", idc_setexecutionstatus),
      ("GetCodeLevel", c_void_p),
      ("SetCodeLevel", c_void_p),
      ("GetEngineOptions", c_void_p),
      ("AddEngineOptions", c_void_p),
      ("RemoveEngineOptions", c_void_p),
      ("SetEngineOptions", idc_setengineoptions),
      ("GetSystemErrorControl", c_void_p),
      ("SetSystemErrorControl", c_void_p),
      ("GetTextMacro", c_void_p),
      ("SetTextMacro", c_void_p),
      ("GetRadix", c_void_p),
      ("SetRadix", c_void_p),
      ("Evaluate", idc_evaluate),
      ("CoerceValue", c_void_p),
      ("CoerceValues", c_void_p),
      ("Execute", idc_execute),
      ("ExecuteCommandFile", c_void_p),
      ("GetNumberBreakpoints", c_void_p),
      ("GetBreakpointByIndex", c_void_p),
      ("GetBreakpointById", c_void_p),
      ("GetBreakpointParameters", c_void_p),
      ("AddBreakpoint", c_void_p),
      ("RemoveBreakpoint", c_void_p),
      ("AddExtension", c_void_p),
      ("RemoveExtension", c_void_p),
      ("GetExtensionByPath", c_void_p),
      ("CallExtension", c_void_p),
      ("GetExtensionFunction", c_void_p),
      ("GetWindbgExtensionApis32", c_void_p),
      ("GetWindbgExtensionApis64", c_void_p),
      ("GetNumberEventFilters", idc_getnumbereventfilters),
      ("GetEventFilterText", c_void_p),
      ("GetEventFilterCommand", c_void_p),
      ("SetEventFilterCommand", c_void_p),
      ("GetSpecificFilterParameters", c_void_p),
      ("SetSpecificFilterParameters", c_void_p),
      ("GetSpecificFilterArgument", c_void_p),
      ("SetSpecificFilterArgument", c_void_p),
      ("GetExceptionFilterParameters", c_void_p),
      ("SetExceptionFilterParameters", c_void_p),
      ("GetExceptionFilterSecondCommand", c_void_p),
      ("SetExceptionFilterSecondCommand", idc_setexceptionfiltersecondcommand),
      ("WaitForEvent", idc_waitforevent),
      ("GetLastEventInformation", c_void_p),
      ("GetCurrentTimeDate", c_void_p),
      ("GetCurrentSystemUpTime", c_void_p),
      ("GetDumpFormatFlags", c_void_p),
      ("GetNumberTextReplacements", c_void_p),
      ("GetTextReplacement", c_void_p),
      ("SetTextReplacement", c_void_p),
      ("RemoveTextReplacements", c_void_p),
      ("OutputTextReplacements", c_void_p),
      ("GetAssemblyOptions", c_void_p),
      ("AddAssemblyOptions", c_void_p),
      ("RemoveAssemblyOptions", c_void_p),
      ("SetAssemblyOptions", c_void_p),
      ("GetExpressionSyntax", c_void_p),
      ("SetExpressionSyntax", idc_setexpressionsyntax),
      ("SetExpressionSyntaxByName", c_void_p),
      ("GetNumberExpressionSyntaxes", c_void_p),
      ("GetExpressionSyntaxNames", c_void_p),
      ("GetNumberEvents", c_void_p),
      ("GetEventIndexDescription", c_void_p),
      ("GetCurrentEventIndex", c_void_p),
      ("SetNextEventIndex", c_void_p),
      ("GetLogFileWide", c_void_p),
      ("OpenLogFileWide", c_void_p),
      ("InputWide", c_void_p),
      ("ReturnInputWide", c_void_p),
      ("OutputWide", c_void_p),
      ("OutputVaListWide", c_void_p),
      ("ControlledOutputWide", c_void_p),
      ("ControlledOutputVaListWide", c_void_p),
      ("OutputPromptWide", c_void_p),
      ("OutputPromptVaListWide", c_void_p),
      ("GetPromptTextWide", c_void_p),
      ("AssembleWide", c_void_p),
      ("DisassembleWide", c_void_p),
      ("GetProcessrTypeNamesWide", c_void_p),
      ("GetTextMacroWide", c_void_p),
      ("SetTextMacroWide", c_void_p),
      ("EvaluateWide", c_void_p),
      ("ExecuteWide", c_void_p),
      ("ExecuteCommandFileWide", c_void_p),
      ("GetBreakpointByIndex2", c_void_p),
      ("GetBreakpointById2", c_void_p),
      ("AddBreakpoint2", idc_addbreakpoint2),
      ("RemoveBreakpoint2", c_void_p),
      ("AddExtensionWide", c_void_p),
      ("GetExtensionByPathWide", c_void_p),
      ("CallExtensionWide", c_void_p),
      ("GetExtensionFunctionWide", c_void_p),
      ("GetEventFilterTextWide", c_void_p),
      ("GetEventfilterCommandWide", c_void_p),
      ("SetEventFilterCommandWide", c_void_p),
      ("GetSpecificFilterArgumentWide", c_void_p),
      ("SetSpecificFilterArgumentWide", c_void_p),
      ("GetExceptionFilterSecondCommandWide", c_void_p),
      ("SetExceptionFilterSecondCommandWider", c_void_p),
      ("GetLastEventInformationWide", c_void_p),
      ("GetTextReplacementWide", c_void_p),
      ("SetTextReplacementWide", c_void_p),
      ("SetExpressionSyntaxByNameWide", c_void_p),
      ("GetExpressionSyntaxNamesWide", c_void_p),
      ("GetEventIndexDescriptionWide", c_void_p),
      ("GetLogFile2", c_void_p),
      ("OpenLogFile2", c_void_p),
      ("GetLogFile2Wide", c_void_p),
      ("OpenLogFile2Wide", c_void_p),
      ("GetSystemVersionValues", c_void_p),
      ("GetSystemVersionString", c_void_p),
      ("GetSystemVersionStringWide", c_void_p),
      ("GetContextStackTrace", c_void_p),
      ("OutputContextStackTrace", c_void_p),
      ("GetStoredEventInformation", c_void_p),
      ("GetManagedStatus", c_void_p),
      ("GetManagedStatusWide", c_void_p),
      ("ResetManagedStatus", c_void_p),
      ("GetStackTraceEx", idc_getstacktraceex),
      ("OutputStackTraceEx", c_void_p),
      ("GetContextStackTraceEx", c_void_p),
      ("OutputContextStackTraceEx", c_void_p),
      ("GetBreakpointByGuid", c_void_p),
      ("GetExecutionStatusEx", c_void_p),
      ("GetSynchronizationStatus", c_void_p),
      ("GetDebuggeeType2", c_void_p)
    ]

IDebugControl7._fields_ = [("lpVtbl", POINTER(IDebugControl7Vtbl))]

class DebugStatus(IntEnum):
  DEBUG_STATUS_NO_CHANGE =            0
  DEBUG_STATUS_GO =                   1
  DEBUG_STATUS_GO_HANDLED =           2
  DEBUG_STATUS_GO_NOT_HANDLED =       3
  DEBUG_STATUS_STEP_OVER =            4
  DEBUG_STATUS_STEP_INTO =            5
  DEBUG_STATUS_BREAK =                6
  DEBUG_STATUS_NO_DEBUGGEE =          7
  DEBUG_STATUS_STEP_BRANCH =          8
  DEBUG_STATUS_IGNORE_EVENT =         9
  DEBUG_STATUS_RESTART_REQUESTED =   10
  DEBUG_STATUS_REVERSE_GO =          11
  DEBUG_STATUS_REVERSE_STEP_BRANCH = 12
  DEBUG_STATUS_REVERSE_STEP_OVER =   13
  DEBUG_STATUS_REVERSE_STEP_INTO =   14
  DEBUG_STATUS_OUT_OF_SYNC =         15
  DEBUG_STATUS_WAIT_INPUT =          16
  DEBUG_STATUS_TIMEOUT =             17

class DebugSyntax(IntEnum):
  DEBUG_EXPR_MASM = 0
  DEBUG_EXPR_CPLUSPLUS = 1

class Control(object):
  def __init__(self, control):
    self.ptr = control
    self.control = control.contents
    self.vt = self.control.lpVtbl.contents
    # Keep a handy ulong for passing into C methods.
    self.ulong = c_ulong()

  def GetExecutionStatus(self, doprint=False):
    ret = self.vt.GetExecutionStatus(self.control, byref(self.ulong))
    aborter(ret, "GetExecutionStatus")
    status = DebugStatus(self.ulong.value)
    if doprint:
      print("Execution status: {}".format(status))
    return status

  def SetExecutionStatus(self, status):
    assert isinstance(status, DebugStatus)
    res = self.vt.SetExecutionStatus(self.control, status.value)
    aborter(res, "SetExecutionStatus")

  def WaitForEvent(self, timeout=100):
    # No flags are taken by WaitForEvent, hence 0
    ret = self.vt.WaitForEvent(self.control, 0, timeout)
    aborter(ret, "WaitforEvent", ignore=[S_FALSE])
    return ret

  def GetNumberEventFilters(self):
    specific_events = c_ulong()
    specific_exceptions = c_ulong()
    arbitrary_exceptions = c_ulong()
    res = self.vt.GetNumberEventFilters(self.control, byref(specific_events),
                                    byref(specific_exceptions),
                                    byref(arbitrary_exceptions))
    aborter(res, "GetNumberEventFilters")
    return (specific_events.value, specific_exceptions.value,
            arbitrary_exceptions.value)

  def SetExceptionFilterSecondCommand(self, index, command):
    buf = create_string_buffer(command.encode('ascii'))
    res = self.vt.SetExceptionFilterSecondCommand(self.control, index, buf)
    aborter(res, "SetExceptionFilterSecondCommand")
    return

  def AddBreakpoint2(self, offset=None, enabled=None):
    breakpoint = POINTER(DebugBreakpoint2)()
    res = self.vt.AddBreakpoint2(self.control, BreakpointTypes.DEBUG_BREAKPOINT_CODE, DEBUG_ANY_ID, byref(breakpoint))
    aborter(res, "Add breakpoint 2")
    bp = Breakpoint(breakpoint)

    if offset is not None:
      bp.SetOffset(offset)
    if enabled is not None and enabled:
      bp.SetFlags(BreakpointFlags.DEBUG_BREAKPOINT_ENABLED)

    return bp

  def RemoveBreakpoint(self, bp):
    res = self.vt.RemoveBreakpoint2(self.control, bp.breakpoint)
    aborter(res, "RemoveBreakpoint2")
    bp.die()

  def GetStackTraceEx(self):
    # XXX -- I can't find a way to query for how many stack frames there _are_
    # in  advance. Guess 128 for now.
    num_frames_buffer = 128

    frames = (DEBUG_STACK_FRAME_EX * num_frames_buffer)()
    numframes = c_ulong()

    # First three args are frame/stack/IP offsets -- leave them as zero to
    # default to the current instruction.
    res = self.vt.GetStackTraceEx(self.control, 0, 0, 0, frames, num_frames_buffer, byref(numframes))
    aborter(res, "GetStackTraceEx")
    return frames, numframes.value

  def Execute(self, command):
    # First zero is DEBUG_OUTCTL_*, which we leave as a default, second
    # zero is DEBUG_EXECUTE_* flags, of which we set none.
    res = self.vt.Execute(self.control, 0, command.encode('ascii'), 0)
    aborter(res, "Client execute")

  def SetExpressionSyntax(self, cpp=True):
    if cpp:
      syntax = DebugSyntax.DEBUG_EXPR_CPLUSPLUS
    else:
      syntax = DebugSyntax.DEBUG_EXPR_MASM

    res = self.vt.SetExpressionSyntax(self.control, syntax)
    aborter(res, "SetExpressionSyntax")

  def Evaluate(self, expr):
    ptr = DEBUG_VALUE()
    res = self.vt.Evaluate(self.control, expr.encode("ascii"), DebugValueType.DEBUG_VALUE_INVALID, byref(ptr), None)
    aborter(res, "Evaluate", ignore=[E_INTERNALEXCEPTION, E_FAIL])
    if res != 0:
      return None

    val_type = DebugValueType(ptr.Type)

    # Here's a map from debug value types to fields. Unclear what happens
    # with unsigned values, as DbgEng doesn't present any unsigned fields.

    extract_map = {
      DebugValueType.DEBUG_VALUE_INT8    : ("I8", "char"),
      DebugValueType.DEBUG_VALUE_INT16   : ("I16", "short"),
      DebugValueType.DEBUG_VALUE_INT32   : ("I32", "int"),
      DebugValueType.DEBUG_VALUE_INT64   : ("I64", "long"),
      DebugValueType.DEBUG_VALUE_FLOAT32 : ("F32", "float"),
      DebugValueType.DEBUG_VALUE_FLOAT64 : ("F64", "double")
    } # And everything else is invalid.

    if val_type not in extract_map:
      raise Exception("Unexpected debug value type {} when evalutaing".format(val_type))

    # Also produce a type name...

    return getattr(ptr.U, extract_map[val_type][0]), extract_map[val_type][1]

  def SetEngineOptions(self, opt):
    res = self.vt.SetEngineOptions(self.control, opt)
    aborter(res, "SetEngineOptions")
    return


text:
<?php

class starbuy_tasks_cancelorder extends base_task_abstract implements base_interface_task{

    function exec($params=null){
        $cancel_mdl = app::get('starbuy')->model('cancelorder');
        $cancel_obj = kernel::single('starbuy_special_order');
        $orders = $cancel_mdl->getList("order_id",array('canceltime|sthan'=>time()));
        $cancel_obj->check_order($orders);
    }
}


text:
<?php

abstract class BaseController {
    protected $controllerName;
    protected $layoutName = DEFAULT_LAYOUT;
    protected $isViewRendered = false;
    protected $isPost = false;
    protected $user;
    protected $isLoggedIn;
    protected $validationError;

    function __construct($controllerName, $actionName) {
        $this->controllerName = $controllerName;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->isPost = true;
        }

        if($_SESSION['username']) {
            $this->isLoggedIn = true;
        }

        $this->onInit();
    }

    public function onInit() {
        // Implement initializing logic in the subclasses
    }

    public function index() {
        // Implement the default action in the subclasses
    }

    public function renderView($viewName = 'index', $includeLayout = true) {
        if (!$this->isViewRendered) {
            $viewFileName = 'views/' . $this->controllerName
                . '/' . $viewName . '.php';
            if ($includeLayout) {
                $headerFile = 'views/layouts/' . $this->layoutName . '/header.php';
                include_once($headerFile);
            }
            include_once($viewFileName);
            if ($includeLayout) {
                $footerFile = 'views/layouts/' . $this->layoutName . '/footer.php';
                include_once($footerFile);
            }
            $this->isViewRendered = true;
        }
    }

    public function redirectToUrl($url) {
        header("Location: " . $url);
        die;
    }

    public function redirect($controllerName, $actionName = 'null', $params = null) {
        $url = '/' . urlencode($controllerName);
        if ($actionName != null) {
            $url .= '/' . urlencode($actionName);
        }
        if ($params != null) {
            $encodedParams = array_map(urlencode, $params);
            $url .= '/' . implode('/', $encodedParams);
        }
        $this->redirectToUrl($url);
    }

    public function getUser(){

    }

    public function authorize() {
        if(!$this->isLoggedIn) {
//            $this->addErrorMessage('Unauthorized');
            $this->redirect('account', 'login');
        }
    }

    function addMessage($msg, $type) {
        if (!isset($_SESSION['messages'])) {
            $_SESSION['messages'] = array();
        };
        array_push($_SESSION['messages'],
            array('text' => $msg, 'type' => $type));
    }

    function addInfoMessage($msg) {
        $this->addMessage($msg, 'info');
    }

    function addErrorMessage($msg) {
        $this->addMessage($msg, 'error');
    }

    function addValidationError($field, $message) {
        $this->validationError[$field] = $message;
    }

    function getValidationError($field) {
        return $this->validationError[$field];
    }

    protected function validateCsft() {
        $isValid = CsftGuard::validateToken($_POST['CSRFName'], $_POST['CSRFToken']);

        if(!$isValid) {
            $this->redirect("problem", "csrfvalidationfail");
        }
    }
}


text:
package org.aracrown.commons.util;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class TestItem {
	@NotNull(message = "Value is missing")
	private String value;

	@Size(min = 3, max = 5, message = "Value size must be between " + 3 + " and " + 5)
	private String value1;

	@NotNull(message = "Name is missing")
	@Size(max = 255)
	private String name;

	/**
	 * @return the value1
	 */
	public String getValue1() {
		return value1;
	}

	/**
	 * @param value1
	 *            the value1 to set
	 */
	public void setValue1(String value1) {
		this.value1 = value1;
	}

	/**
	 * @return the value
	 */
	public String getValue() {
		return value;
	}

	/**
	 * @param value
	 *            the value to set
	 */
	public void setValue(String value) {
		this.value = value;
	}

}


text:
'use strict'

const tap = require('tap')

const nodeLabels = require('../../lib/node-labels')

tap.test('label: "test" when only ./test/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'test/debugger/test-debugger-pid.js',
    'test/debugger/test-debugger-repl-break-in-module.js',
    'test/debugger/test-debugger-repl-term.js'
  ])

  t.same(labels, ['test'])

  t.end()
})

tap.test('no labels: when ./test/ and ./doc/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'test/debugger/test-debugger-pid.js',
    'doc/api/fs.md'
  ])

  t.same(labels, [])

  t.end()
})

// This ensures older mislabelling issues doesn't happen again
// https://github.com/nodejs/node/pull/6432
// https://github.com/nodejs/node/pull/6448
tap.test('no labels: when ./test/ and ./lib/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'lib/punycode.js',
    'test/parallel/test-assert.js'
  ])

  t.same(labels, [])

  t.end()
})

tap.test('label: "doc" when only ./doc/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'doc/api/fs.md',
    'doc/api/http.md',
    'doc/onboarding.md'
  ])

  t.same(labels, ['doc'])

  t.end()
})

tap.test('label: "benchmark" when only ./benchmark/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'benchmark/http_server_lag.js',
    'benchmark/http/check_is_http_token.js'
  ])

  t.same(labels, ['benchmark'])

  t.end()
})

tap.test('label: "c++" when ./src/* has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'src/async-wrap.h',
    'src/async-wrap.cc'
  ])

  t.same(labels, ['c++'])

  t.end()
})

tap.test('label: not "c++" when ./src/node_version.h has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'src/node_version.h'
  ])

  t.same(labels, [])

  t.end()
})

tap.test('label: "v8_inspector" when ./src/inspector_* has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'src/inspector_socket.cc'
  ])

  t.same(labels, ['c++', 'v8_inspector', 'dont-land-on-v4.x'])

  t.end()
})

tap.test('label: "v8" when ./deps/v8/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/src/arguments.cc'
  ])

  t.same(labels, ['v8'])

  t.end()
})

tap.test('label: "libuv" when ./deps/uv/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/uv/src/fs-poll.c'
  ])

  t.same(labels, ['libuv'])

  t.end()
})

tap.test('label: "v8", "openssl" when ./deps/v8/ and ./deps/openssl/ files has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/src/arguments.cc',
    'deps/openssl/openssl/ssl/ssl_rsa.c'
  ])

  t.same(labels, ['v8', 'openssl'])

  t.end()
})

//
// Planned tests to be resolved later
//

tap.test('label: "repl" when ./lib/repl.js has been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'lib/repl.js',
    'test/debugger/test-debugger-pid.js',
    'test/debugger/test-debugger-repl-break-in-module.js',
    'test/debugger/test-debugger-repl-term.js'
  ])

  t.same(labels, ['repl'])

  t.end()
})

tap.test('label: "lib / src" when 5 or more JS sub-systems have been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'lib/assert.js',
    'lib/dns.js',
    'lib/repl.js',
    'lib/process.js',
    'lib/module.js'
  ])

  t.same(labels, ['lib / src'])

  t.end()
})

// https://github.com/nodejs/node/pull/7488 wrongfully labelled with "lib / src"
tap.test('label: not "lib / src" when only deps have been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/test/cctest/interpreter/bytecode_expectations/ArrayLiterals.golden',
    'deps/v8/test/cctest/interpreter/bytecode_expectations/ArrayLiteralsWide.golden',
    'deps/v8/test/cctest/interpreter/bytecode_expectations/AssignmentsInBinaryExpression.golden',
    'deps/v8/test/cctest/interpreter/bytecode_expectations/BasicBlockToBoolean.golden',
    'deps/v8/test/cctest/interpreter/bytecode_expectations/BasicLoops.golden'
  ])

  t.same(labels, ['v8'])

  t.end()
})

tap.test('label: "JS sub-systems when less than 5 sub-systems have changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'lib/assert.js',
    'lib/dns.js',
    'lib/repl.js',
    'lib/process.js'
  ])

  t.same(labels, ['assert', 'dns', 'repl', 'process'])

  t.end()
})

tap.test('label: "meta" when meta-info files have changed', (t) => {
  // e.g. LICENSE, AUTHORS, some ./*.md files
  const labels = nodeLabels.resolveLabels([
    '.gitattributes',
    '.gitignore',
    '.mailmap',
    'AUTHORS',
    'LICENSE',
    'CHANGELOG.md',
    'CODE_OF_CONDUCT.md',
    'GOVERNANCE.md',
    'ROADMAP.md',
    'WORKING_GROUPS.md'
  ])

  t.same(labels, ['meta'])

  t.end()
})

tap.test('label: not "meta" when other top-level have been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'BUILDING.md',
    'README.md',
    'COLLABORATOR_GUIDE.md',
    'CONTRIBUTING.md',
    'configure'
  ])

  t.same(labels.indexOf('meta'), -1)

  t.end()
})

tap.test('label: "doc" when top-level .md files have changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'BUILDING.md',
    'README.md'
  ])

  t.same(labels, ['doc'])

  t.end()
})

tap.test('label: not "doc" when other top-level files have been changed', (t) => {
  const labels = nodeLabels.resolveLabels([
    'LICENSE',
    'configure',
    '.mailmap'
  ])

  t.same(labels.indexOf('doc'), -1)

  t.end()
})

tap.test('label: version labels (old)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'common.gypi'
  ], 'v0.12')

  t.same(labels, ['build', 'v0.12'])

  t.end()
})

tap.test('label: version labels (old, staging)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'common.gypi'
  ], 'v0.12-staging')

  t.same(labels, ['build', 'v0.12'])

  t.end()
})

tap.test('label: version labels (new)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/include/v8-version.h',
    'deps/v8/src/crankshaft/hydrogen.cc',
    'deps/v8/test/mjsunit/regress/regress-5033.js'
  ], 'v6.x')

  t.same(labels, ['v8', 'v6.x'])

  t.end()
})

tap.test('label: version labels (new, staging)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/include/v8-version.h',
    'deps/v8/src/crankshaft/hydrogen.cc',
    'deps/v8/test/mjsunit/regress/regress-5033.js'
  ], 'v6.x-staging')

  t.same(labels, ['v8', 'v6.x'])

  t.end()
})

tap.test('label: no version labels (master)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'deps/v8/include/v8-version.h',
    'deps/v8/src/crankshaft/hydrogen.cc',
    'deps/v8/test/mjsunit/regress/regress-5033.js'
  ], 'master')

  t.same(labels, ['v8'])

  t.end()
})

tap.test('label: tools label', (t) => {
  const labels = nodeLabels.resolveLabels([
    'tools/doc/json.js'
  ])

  t.same(labels, ['tools'])

  t.end()
})

tap.test('label: build label (windows)', (t) => {
  const labels = nodeLabels.resolveLabels([
    'vcbuild.bat'
  ])

  t.same(labels, ['build'])

  t.end()
})


text:
<?php

/**
 * PHPExcel_Shared_Escher_DgContainer_SpgrContainer
 *
 * @category   PHPExcel
 * @package    PHPExcel_Shared_Escher
 * @copyright  Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Shared_Escher_DgContainer_SpgrContainer
{
	/**
	 * Parent Shape Group Container
	 *
	 * @var PHPExcel_Shared_Escher_DgContainer_SpgrContainer
	 */
	private $_parent;

	/**
	 * Shape Container collection
	 *
	 * @var array
	 */
	private $_children = array();

	/**
	 * Set parent Shape Group Container
	 *
	 * @param PHPExcel_Shared_Escher_DgContainer_SpgrContainer $parent
	 */
	public function setParent($parent)
	{
		$this->_parent = $parent;
	}

	/**
	 * Get the parent Shape Group Container if any
	 *
	 * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer|null
	 */
	public function getParent()
	{
		return $this->_parent;
	}

	/**
	 * Add a child. This will be either spgrContainer or spContainer
	 *
	 * @param mixed $child
	 */
	public function addChild($child)
	{
		$this->_children[] = $child;
		$child->setParent($this);
	}

	/**
	 * Get collection of Shape Containers
	 */
	public function getChildren()
	{
		return $this->_children;
	}

	/**
	 * Recursively get all spContainers within this spgrContainer
	 *
	 * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer[]
	 */
	public function getAllSpContainers()
	{
		$allSpContainers = array();

		foreach ($this->_children as $child) {
			if ($child instanceof PHPExcel_Shared_Escher_DgContainer_SpgrContainer) {
				$allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers());
			} else {
				$allSpContainers[] = $child;
			}
		}

		return $allSpContainers;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap@next/dist/css/bootstrap.min.css" />
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />

    <title>TOML to JSON Converter</title>

TOML

JSON


text:
from troposphere import (
    GetAtt,
    Join,
    Output,
    Ref,
    iam,
    logs,
    ec2,
)

from troposphere.iam import Policy as TropoPolicy

from stacker.blueprints.base import Blueprint

from awacs.aws import (
    Statement,
    Policy,
)

import awacs
import awacs.logs

from .policies import flowlogs_assumerole_policy
from .cloudwatch_logs import (
    LOG_RETENTION_STRINGS,
    validate_cloudwatch_log_retention
)

ALLOWED_TRAFFIC_TYPES = ["ACCEPT", "REJECT", "ALL"]
JOINED_TRAFFIC_TYPES = '/'.join(ALLOWED_TRAFFIC_TYPES)
LOG_RETENTION_DEFAULT = 0
CLOUDWATCH_ROLE_NAME = "Role"
FLOW_LOG_GROUP_NAME = "LogGroup"
FLOW_LOG_STREAM_NAME = "LogStream"

def vpc_flow_log_cloudwatch_policy(log_group_arn):
    return Policy(
        Statement=[
            Statement(
                Effect="Allow",
                Action=[
                    awacs.logs.DescribeLogGroups
                ],
                Resource=["*"],
            ),
            Statement(
                Effect="Allow",
                Action=[
                    awacs.logs.CreateLogStream,
                    awacs.logs.DescribeLogStreams,
                    awacs.logs.PutLogEvents,
                ],
                Resource=[
                    log_group_arn,
                    Join('', [log_group_arn, ":*"]),
                ],
            ),
        ]
    )

def validate_traffic_type(traffic_type):
    if traffic_type not in ALLOWED_TRAFFIC_TYPES:
        raise ValueError(
            "Traffic type must be one of the following: " +
            "%s" % JOINED_TRAFFIC_TYPES
        )

    return traffic_type

class FlowLogs(Blueprint):
    VARIABLES = {
        "Retention": {
            "type": int,
            "description": "Time in days to retain Cloudwatch Logs. Accepted "
                           "values: %s. Default 0 - retain forever." % (
                               ', '.join(LOG_RETENTION_STRINGS)),
            "default": LOG_RETENTION_DEFAULT,
            "validator": validate_cloudwatch_log_retention,

        },
        "VpcId": {
            "type": str,
            "description": "ID of the VPC that flow logs will be enabled "
                           "for.",
        },
        "TrafficType": {
            "type": str,
            "description": "Type of traffic to log. Must be one of the "
                           "following: %s" % JOINED_TRAFFIC_TYPES,
            "validator": validate_traffic_type,
            "default": "ALL",
        },
    }

    def create_template(self):
        t = self.template
        variables = self.get_variables()

        self.log_group = t.add_resource(
            logs.LogGroup(
                FLOW_LOG_GROUP_NAME,
                RetentionInDays=variables["Retention"],
            )
        )

        t.add_output(
            Output(
                "%sName" % FLOW_LOG_GROUP_NAME,
                Value=Ref(self.log_group)
            )
        )
        t.add_output(
            Output(
                "%sArn" % FLOW_LOG_GROUP_NAME,
                Value=GetAtt(self.log_group, "Arn")
            )
        )

        self.role = t.add_resource(
            iam.Role(
                CLOUDWATCH_ROLE_NAME,
                AssumeRolePolicyDocument=flowlogs_assumerole_policy(),
                Path="/",
                Policies=[
                    TropoPolicy(
                        PolicyName="vpc_cloudwatch_flowlog_policy",
                        PolicyDocument=vpc_flow_log_cloudwatch_policy(
                            GetAtt(self.log_group, "Arn")
                        ),
                    ),
                ]
            )
        )

        t.add_output(
            Output(
                "%sName" % CLOUDWATCH_ROLE_NAME,
                Value=Ref(self.role)
            )
        )
        role_arn = GetAtt(self.role, "Arn")
        t.add_output(
            Output(
                "%sArn" % CLOUDWATCH_ROLE_NAME,
                Value=role_arn
            )
        )

        self.log_stream = t.add_resource(
            ec2.FlowLog(
                FLOW_LOG_STREAM_NAME,
                DeliverLogsPermissionArn=role_arn,
                LogGroupName=Ref(FLOW_LOG_GROUP_NAME),
                ResourceId=variables["VpcId"],
                ResourceType="VPC",
                TrafficType=variables["TrafficType"],
            )
        )

        t.add_output(
            Output(
                "%sName" % FLOW_LOG_STREAM_NAME,
                Value=Ref(self.log_stream)
            )
        )


text:
/**
 * User: Jomaras
 * Date: 13.08.13.
 * Time: 12:17
 */
function assert(value, message)
{
    if(!value)
    {
        console.log("Assert fail: " + message);
    }
}

var ALL_EQUAL = {};

function assertEqual(expected, actual, message)
{
    if(!areEqual(expected, actual))
    {
        console.log("AssertEqual failed: " + expected + "; " + actual + ":" + message);
    }
}

function assertNotEquals(expected, actual, message)
{
    if(areEqual(expected, actual))
    {
        console.log("AssertNotEquals failed: " + expected + "; " + actual + ":" + message);
    }
}

var assertEquals = assertEqual;

function areEqual(expected, actual)
{
    var result;

    if (expected == actual)
        return true;

    if (expected && typeof expected.equals === 'function')
        return expected.equals(actual);

    if (expected instanceof Function)
        return expected === actual;

    if (expected instanceof Array) {
        if (!(actual instanceof Array)) return false;
        for (var i = 0, n = expected.length; i < n; i++) {
            result = areEqual(expected[i], actual[i]);
            if (result === ALL_EQUAL) return true;
            if (!result) return false;
        }
        if (expected.length !== actual.length) return false;
        return true;
    }

    if (expected instanceof Date) {
        if (!(actual instanceof Date)) return false;
        if (expected.getTime() !== actual.getTime()) return false;
        return true;
    }

    if (expected instanceof Object) {
        if (!(actual instanceof Object)) return false;
        if (objectSize(expected) !== objectSize(actual)) return false;
        for (var key in expected) {
            if (!areEqual(expected[key], actual[key]))
                return false;
        }
        return true;
    }

    return false;
}

function objectSize(object) {
    return objectKeys(object).length;
}

function objectKeys(object, includeProto)
{
    var keys = [];
    for (var key in object) {
        if (object.hasOwnProperty(key) || includeProto !== false)
            keys.push(key);
    }
    return keys;
};

function assertNull(object, message)
{
    if(object != null)
    {
        console.log("assertNull fail: " + message);
    }
}

function assertNotNull(value, message)
{
    if(value === null)
    {
        console.log("AssertNotNull fail: " + message);
    }
}

function assertMatch(category, object)
{
    if(!match(category, object))
    {
        console.log("assertMatch fail:" + category + " ; " + object);
    }
}

function match(category, object)
{
    if (object === undefined) return false;

    return typeof category.test === 'function'
        ? category.test(object)
        : category.match(object)
}


text:
package com.scaleset.search.es.agg;

import com.scaleset.search.Aggregation;
import com.scaleset.search.AggregationResults;
import com.scaleset.search.Bucket;
import com.scaleset.search.es.QueryConverter;
import com.scaleset.search.es.ResultsConverter;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;

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

public class DateHistogramAggregationConverter extends AbstractCombinedConverter {

    @Override
    public AggregationBuilder convert(QueryConverter queryConverter, Aggregation aggregation) {

        DateHistogramBuilder result = AggregationBuilders.dateHistogram(getName(aggregation));
        String field = aggregation.getString("field");
        String interval = aggregation.getString("interval");
        String format = aggregation.getString("format");
        if (field != null) {
            result.field(field);
        }
        if (interval != null) {
            DateHistogram.Interval i = new DateHistogram.Interval(interval);
            result.interval(i);
        }
        if (format != null) {
            result.format(format);
        }
        // not sure we really want to support sub-aggs, but we will
        addSubAggs(queryConverter, aggregation, result);
        return result;
    }

    @Override
    public AggregationResults convertResult(ResultsConverter resultsConverter, Aggregation
            aggregation, Aggregations aggs) {
        String name = aggregation.getName();
        AggregationResults result = null;
        if (aggs.get(name) instanceof DateHistogram) {
            DateHistogram grid = (DateHistogram) (aggs.get(name));
            List<Bucket> buckets = new ArrayList<>();
            for (DateHistogram.Bucket bucket : grid.getBuckets()) {
                if (bucket.getDocCount() > 0) {
                    Bucket b = new Bucket(bucket.getKeyAsText().toString(), bucket.getDocCount());
                    buckets.add(b);
                    for (Aggregation subAgg : aggregation.getAggs().values()) {
                        AggregationResults subResults = resultsConverter.convertResults(subAgg, bucket.getAggregations());
                        if (subResults != null) {
                            b.getAggs().put(subAgg.getName(), subResults);
                        }
                    }
                }
            }
            result = new AggregationResults(name, buckets);
        }
        return result;
    }
}