text:
===============
python-tabulate
===============

Pretty-print tabular data in Python, a library and a command-line
utility.

The main use cases of the library are:

* printing small tables without hassle: just one function call,
  formatting is guided by the data itself

* authoring tabular data for lightweight plain-text markup: multiple
  output formats suitable for further editing or transformation

* readable presentation of mixed textual and numeric data: smart
  column alignment, configurable number formatting, alignment by a
  decimal point

Installation
------------

To install the Python library and the command line utility, run::

    pip install tabulate

The command line utility will be installed as ``tabulate`` to ``bin`` on Linux
(e.g. ``/usr/bin``); or as ``tabulate.exe`` to ``Scripts`` in your Python
installation on Windows (e.g. ``C:\Python27\Scripts\tabulate.exe``).

You may consider installing the library only for the current user::

    pip install tabulate --user

In this case the command line utility will be installed to ``~/.local/bin/tabulate``
on Linux and to ``%APPDATA%\Python\Scripts\tabulate.exe`` on Windows.

To install just the library on Unix-like operating systems::

    TABULATE_INSTALL=lib-only pip install tabulate

On Windows::

    set TABULATE_INSTALL=lib-only
    pip install tabulate

Build status
------------

.. image:: https://drone.io/bitbucket.org/astanin/python-tabulate/status.png
   :alt: Build status
   :target: https://drone.io/bitbucket.org/astanin/python-tabulate/latest

Library usage
-------------

The module provides just one function, ``tabulate``, which takes a
list of lists or another tabular data type as the first argument,
and outputs a nicely formatted plain-text table::

    >>> from tabulate import tabulate

    >>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
    ...          ["Moon",1737,73.5],["Mars",3390,641.85]]
    >>> print tabulate(table)
    -----  ------  -------------
    Sun    696000     1.9891e+09
    Earth    6371  5973.6
    Moon     1737    73.5
    Mars     3390   641.85
    -----  ------  -------------

The following tabular data types are supported:

* list of lists or another iterable of iterables
* list or another iterable of dicts (keys as columns)
* dict of iterables (keys as columns)
* two-dimensional NumPy array
* NumPy record arrays (names as columns)
* pandas.DataFrame

Examples in this file use Python2. Tabulate supports Python3 too.

Headers
~~~~~~~

The second optional argument named ``headers`` defines a list of
column headers to be used::

    >>> print tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"])
    Planet      R (km)    mass (x 10^29 kg)
    --------  --------  -------------------
    Sun         696000           1.9891e+09
    Earth         6371        5973.6
    Moon          1737          73.5
    Mars          3390         641.85

If ``headers="firstrow"``, then the first row of data is used::

    >>> print tabulate([["Name","Age"],["Alice",24],["Bob",19]],
    ...                headers="firstrow")
    Name      Age
    ------  -----
    Alice      24
    Bob        19

If ``headers="keys"``, then the keys of a dictionary/dataframe, or
column indices are used. It also works for NumPy record arrays and
lists of dictionaries or named tuples::

    >>> print tabulate({"Name": ["Alice", "Bob"],
    ...                 "Age": [24, 19]}, headers="keys")
      Age  Name
    -----  ------
       24  Alice
       19  Bob

Row Indices
~~~~~~~~~~~

By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass ``showindex="always"`` or ``showindex=True`` argument to
``tabulate()``. To suppress row indices for all types of data, pass
``showindex="never"`` or ``showindex=False``.  To add a custom row
index column, pass ``showindex=rowIDs``, where ``rowIDs`` is some
iterable::

    >>> print(tabulate([["F",24],["M",19]], showindex="always"))
    -  -  --
    0  F  24
    1  M  19
    -  -  --

Table format
~~~~~~~~~~~~

There is more than one way to format a table in plain text.
The third optional argument named ``tablefmt`` defines
how the table is formatted.

Supported table formats are:

- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "html"
- "latex"
- "latex_booktabs"
- "textile"

``plain`` tables do not use any pseudo-graphics to draw lines::

    >>> table = [["spam",42],["eggs",451],["bacon",0]]
    >>> headers = ["item", "qty"]
    >>> print tabulate(table, headers, tablefmt="plain")
    item      qty
    spam       42
    eggs      451
    bacon       0

``simple`` is the default format (the default may change in future
versions).  It corresponds to ``simple_tables`` in `Pandoc Markdown
extensions`_::

    >>> print tabulate(table, headers, tablefmt="simple")
    item      qty
    ------  -----
    spam       42
    eggs      451
    bacon       0

``grid`` is like tables formatted by Emacs' `table.el`_
package.  It corresponds to ``grid_tables`` in Pandoc Markdown
extensions::

    >>> print tabulate(table, headers, tablefmt="grid")
    +--------+-------+
    | item   |   qty |
    +========+=======+
    | spam   |    42 |
    +--------+-------+
    | eggs   |   451 |
    +--------+-------+
    | bacon  |     0 |
    +--------+-------+

``fancy_grid`` draws a grid using box-drawing characters::

    >>> print tabulate(table, headers, tablefmt="fancy_grid")
    ╒════════╤═══════╕
    │ item   │   qty │
    ╞════════╪═══════╡
    │ spam   │    42 │
    ├────────┼───────┤
    │ eggs   │   451 │
    ├────────┼───────┤
    │ bacon  │     0 │
    ╘════════╧═══════╛

``psql`` is like tables formatted by Postgres' psql cli::

    >>> print tabulate.tabulate()
    +--------+-------+
    | item   |   qty |
    |--------+-------|
    | spam   |    42 |
    | eggs   |   451 |
    | bacon  |     0 |
    +--------+-------+

``pipe`` follows the conventions of `PHP Markdown Extra`_ extension.  It
corresponds to ``pipe_tables`` in Pandoc. This format uses colons to
indicate column alignment::

    >>> print tabulate(table, headers, tablefmt="pipe")
    | item   |   qty |
    |:-------|------:|
    | spam   |    42 |
    | eggs   |   451 |
    | bacon  |     0 |

``orgtbl`` follows the conventions of Emacs `org-mode`_, and is editable
also in the minor `orgtbl-mode`. Hence its name::

    >>> print tabulate(table, headers, tablefmt="orgtbl")
    | item   |   qty |
    |--------+-------|
    | spam   |    42 |
    | eggs   |   451 |
    | bacon  |     0 |

``jira`` follows the conventions of Atlassian Jira markup language::

    >>> print tabulate(table, headers, tablefmt="jira")
    || item   ||   qty ||
    | spam   |    42 |
    | eggs   |   451 |
    | bacon  |     0 |

``rst`` formats data like a simple table of the `reStructuredText`_ format::

    >>> print tabulate(table, headers, tablefmt="rst")
    ======  =====
    item      qty
    ======  =====
    spam       42
    eggs      451
    bacon       0
    ======  =====

``mediawiki`` format produces a table markup used in `Wikipedia`_ and on
other MediaWiki-based sites::

    >>> print tabulate(table, headers, tablefmt="mediawiki")
    {| class="wikitable" style="text-align: left;"
    |+
    |-
    ! item   !! align="right"|   qty
    |-
    | spam   || align="right"|    42
    |-
    | eggs   || align="right"|   451
    |-
    | bacon  || align="right"|     0
    |}

``moinmoin`` format produces a table markup used in `MoinMoin`_
wikis::

    >>> print tabulate(d,headers,tablefmt="moinmoin")
    || ''' item   ''' || ''' quantity   ''' ||
    ||  spam    ||  41.999      ||
    ||  eggs    ||  451         ||
    ||  bacon   ||              ||

``textile`` format produces a table markup used in `Textile`_ format::

    >>> print tabulate(table, headers, tablefmt='textile')
    |_.  item   |_.   qty |
    |<. spam    |>.    42 |
    |<. eggs    |>.   451 |
    |<. bacon   |>.     0 |

``html`` produces standard HTML markup::

    >>> print tabulate(table, headers, tablefmt="html")

item  	  qty

spam  	   42

eggs  	  451

bacon 	    0

``latex`` format creates a ``tabular`` environment for LaTeX markup::

    >>> print tabulate(table, headers, tablefmt="latex")
    \begin{tabular}{lr}
    \hline
     item   &   qty \\
    \hline
     spam   &    42 \\
     eggs   &   451 \\
     bacon  &     0 \\
    \hline
    \end{tabular}

``latex_booktabs`` creates a ``tabular`` environment for LaTeX markup
using spacing and style from the ``booktabs`` package.

.. _Pandoc Markdown extensions: http://johnmacfarlane.net/pandoc/README.html#tables
.. _PHP Markdown Extra: http://michelf.ca/projects/php-markdown/extra/#table
.. _table.el: http://table.sourceforge.net/
.. _org-mode: http://orgmode.org/manual/Tables.html
.. _reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables
.. _Textile: http://redcloth.org/hobix.com/textile/
.. _Wikipedia: http://www.mediawiki.org/wiki/Help:Tables

Column alignment
~~~~~~~~~~~~~~~~

``tabulate`` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.

You can override the default alignment with ``numalign`` and
``stralign`` named arguments. Possible column alignments are:
``right``, ``center``, ``left``, ``decimal`` (only for numbers), and
``None`` (to disable alignment).

Aligning by a decimal point works best when you need to compare
numbers at a glance::

    >>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]])
    ----------
        1.2345
      123.45
       12.345
    12345
     1234.5
    ----------

Compare this with a more common right alignment::

    >>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right")
    ------
    1.2345
    123.45
    12.345
     12345
    1234.5
    ------

For ``tabulate``, anything which can be parsed as a number is a
number. Even numbers represented as strings are aligned properly. This
feature comes in handy when reading a mixed table of text and numbers
from a file:

::

    >>> import csv ; from StringIO import StringIO
    >>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n")))
    >>> table
    [['spam', ' 42'], ['eggs', ' 451']]
    >>> print tabulate(table)
    ----  ----
    spam    42
    eggs   451
    ----  ----

Number formatting
~~~~~~~~~~~~~~~~~

``tabulate`` allows to define custom number formatting applied to all
columns of decimal numbers. Use ``floatfmt`` named argument::

    >>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
    --  ------
    pi  3.1416
    e   2.7183
    --  ------

Wide (fullwidth CJK) symbols
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To properly align tables which contain wide characters (typically fullwidth
glyphs from Chinese, Japanese or Korean languages), the user should install
``wcwidth`` library. To install it together with ``tabulate``::

    pip install tabulate[widechars]

Wide character support is enabled automatically if ``wcwidth`` library is
already installed.  To disable wide characters support without uninstalling
``wcwidth``, set the global module-level flag ``WIDE_CHARS_MODE``::

    import tabulate
    tabulate.WIDE_CHARS_MODE = False

Usage of the command line utility
---------------------------------

::

    Usage: tabulate [options] [FILE ...]

    FILE                      a filename of the file with tabular data;
                              if "-" or missing, read data from stdin.

    Options:

    -h, --help                show this message
    -1, --header              use the first row of data as a table header
    -o FILE, --output FILE    print table to FILE (default: stdout)
    -s REGEXP, --sep REGEXP   use a custom column separator (default: whitespace)
    -F FPFMT, --float FPFMT   floating point number format (default: g)
    -f FMT, --format FMT      set output table format; supported formats:
                              plain, simple, grid, fancy_grid, pipe, orgtbl,
                              rst, mediawiki, html, latex, latex_booktabs, tsv
                              (default: simple)

Performance considerations
--------------------------

Such features as decimal point alignment and trying to parse everything
as a number imply that ``tabulate``:

* has to "guess" how to print a particular tabular data type
* needs to keep the entire table in-memory
* has to "transpose" the table twice
* does much more work than it may appear

It may not be suitable for serializing really big tables (but who's
going to do that, anyway?) or printing tables in performance sensitive
applications. ``tabulate`` is about two orders of magnitude slower
than simply joining lists of values with a tab, coma or other
separator.

In the same time ``tabulate`` is comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text
and numeric data, ``tabulate`` appears to be slower than
``asciitable``, and faster than ``PrettyTable`` and ``texttable``

::

    =====================================  ==========  ===========
    Table formatter                          time, μs    rel. time
    =====================================  ==========  ===========
    join with tabs and newlines                  27.0          1.0
    csv to StringIO                              38.5          1.4
    tabletext (0.1)                             529.4         19.6
    asciitable (0.8.0)                          877.2         32.5
    tabulate (0.7.6-dev)                       1549.7         57.5
    tabulate (0.7.6-dev, WIDE_CHARS_MODE)      2271.5         84.2
    PrettyTable (0.7.2)                        3986.1        147.8
    texttable (0.8.3)                          4412.8        163.6
    =====================================  ==========  ===========

Version history
---------------

- 0.8: FUTURE RELEASE
- 0.7.5: Bug fixes. ``--float`` format option for the command line utility.
- 0.7.4: Bug fixes. ``fancy_grid`` and ``html`` formats. Command line utility.
- 0.7.3: Bug fixes. Python 3.4 support. Iterables of dicts. ``latex_booktabs`` format.
- 0.7.2: Python 3.2 support.
- 0.7.1: Bug fixes. ``tsv`` format. Column alignment can be disabled.
- 0.7: ``latex`` tables. Printing lists of named tuples and NumPy
  record arrays. Fix printing date and time values. Python <= 2.6.4 is supported.
- 0.6: ``mediawiki`` tables, bug fixes.
- 0.5.1: Fix README.rst formatting. Optimize (performance similar to 0.4.4).
- 0.5: ANSI color sequences. Printing dicts of iterables and Pandas' dataframes.
- 0.4.4: Python 2.6 support.
- 0.4.3: Bug fix, None as a missing value.
- 0.4.2: Fix manifest file.
- 0.4.1: Update license and documentation.
- 0.4: Unicode support, Python3 support, ``rst`` tables.
- 0.3: Initial PyPI release. Table formats: ``simple``, ``plain``,
  ``grid``, ``pipe``, and ``orgtbl``.

How to contribute
-----------------

Contributions should include tests and an explanation for the changes they
propose. Documentation (examples, docstrings, README.rst) should be updated
accordingly.

This project uses `nose`_ testing framework and `tox`_ to automate testing in
different environments. Add tests to one of the files in the ``test/`` folder.

To run tests on all supported Python versions, make sure all Python
interpreters, ``nose`` and ``tox`` are installed, then run ``tox`` in
the root of the project source tree.

On Linux ``tox`` expects to find executables like ``python2.6``,
``python2.7``, ``python3.4`` etc. On Windows it looks for
``C:\Python26\python.exe``, ``C:\Python27\python.exe`` and
``C:\Python34\python.exe`` respectively.

To test only some Python environements, use ``-e`` option. For
example, to test only against Python 2.7 and Python 3.4, run::

    tox -e py27,py34

in the root of the project source tree.

To enable NumPy and Pandas tests, run::

    tox -e py27-extra,py34-extra

(this may take a long time the first time, because NumPy and Pandas
will have to be installed in the new virtual environments)

See ``tox.ini`` file to learn how to use ``nosetests`` directly to
test individual Python versions.

.. _nose: https://nose.readthedocs.org/
.. _tox: http://tox.testrun.org/

Contributors
------------

Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill Ryder,
Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg (anonymous),
Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, Amjith Ramanujam,
Jan Schulz, Simon Percivall, Javier Santacruz López-Cepero.


text:
package jsondb.tests;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import jsondb.JsonDBConfig;
import jsondb.JsonDBTemplate;
import jsondb.Util;
import java.io.File;
import java.util.UUID;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import jsondb.Pojos.DOBehoerde;
import jsondb.Pojos.DOHaushaltsjahr;

/**
 *
 * @author Andreas
 */
public class JoinTests {

  private String dbFilesLocation = "test/resources/Pojos/JoinTests";
  private File dbFilesFolder = new File(dbFilesLocation);
  private File behoerdejson = new File(dbFilesFolder, "behoerde.json");
  private File haushaltsjahrjson = new File(dbFilesFolder, "haushaltsjahr.json");
  private JsonDBTemplate jsontpl = null;
  private String bk = null;
  private String hk = null;
  private String neuesjahrkey = null;

    public JoinTests() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        dbFilesFolder.mkdir();
        JsonDBConfig c = new JsonDBConfig(dbFilesLocation, "resources/Pojos", "pre", null, true, null);
        jsontpl = new JsonDBTemplate(c);

        if (!jsontpl.collectionExists("behoerden"))
        jsontpl.createCollection("behoerden");

        if (!jsontpl.collectionExists("haushaltsjahre"))
        jsontpl.createCollection("haushaltsjahre");

        bk = UUID.randomUUID().toString();
        hk = UUID.randomUUID().toString();
        neuesjahrkey = UUID.randomUUID().toString();
    }

    @After
    public void tearDown() {
        Util.delete(dbFilesFolder);
    }

    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
    // @Test
    // public void hello() {}

    @Test
    public void jointest() {
        DOBehoerde b = new DOBehoerde();
        b.setBehoerdenname("PD Hannover");

        b.setKey(bk);

        DOHaushaltsjahr h = new DOHaushaltsjahr();
        h.setJahr("2017");
        hk = UUID.randomUUID().toString();
        h.setKey(hk);

        jsontpl.insert(b, "behoerden");
        jsontpl.insert(h, "haushaltsjahre");

        jsontpl.join(bk,"behoerden",hk,"haushaltsjahre");

        DOHaushaltsjahr neuesjahr = new DOHaushaltsjahr();
        neuesjahr.setJahr("2018");
        neuesjahr.setKey(neuesjahrkey);

        jsontpl.insert(neuesjahr);
        jsontpl.join(bk, "behoerden", neuesjahrkey, "haushaltsjahre");

    }

    @Test
    public void joinEinszuNTest() {
       UUID muid = UUID.nameUUIDFromBytes(("Korzinowski").getBytes());
        System.out.println("mostsigni ist: " + muid.getMostSignificantBits());
        System.out.println("least ist " + muid.getLeastSignificantBits());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.mojang.mario;

import java.io.*;

public class Recorder
{
    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
    private DataOutputStream dos = new DataOutputStream(baos);

    private byte lastTick = 0;
    private int tickCount = 0;

    public void addLong(long val)
    {
        try
        {
            dos.writeLong(val);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void addTick(byte tick)
    {
        try
        {
            if (tick == lastTick)
            {
                tickCount++;
            }
            else
            {
                dos.writeInt(tickCount);
                dos.write(tick);
                lastTick = tick;
                tickCount = 1;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public byte[] getBytes()
    {
        try
        {
            dos.writeInt(tickCount);
            dos.write(-1);
            dos.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }
}


text:
using System;
using System.Drawing;

namespace Alphora.Dataphor.DAE.Client.Controls
{
	/// <summary> Default colors for controls. </summary>
	public sealed class ControlColor
	{
		/// <summary> Background color of the control when it has no value. </summary>
		public static Color NoValueBackColor { get { return Color.FromArgb(240, 255, 240); } }
		/// <summary> Background color of the control when it has no value and it's read only. </summary>
		public static Color NoValueReadOnlyBackColor { get { return Color.FromArgb(200, 220, 200); } }
		/// <summary> Background color of an incremental search control when the input value fails to convert to the fields data type. </summary>
		public static Color ConversionFailBackColor { get { return Color.FromArgb(255, 255, 220); } }
	}
}


text:
package com.github.pockethub.android;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

import com.github.pockethub.android.core.commit.CommitStore;
import com.github.pockethub.android.core.gist.GistStore;
import com.github.pockethub.android.core.issue.IssueStore;
import com.github.pockethub.android.persistence.OrganizationRepositories;
import com.github.pockethub.android.sync.SyncCampaign;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Named;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Main module provide services and clients
 */
public class PocketHubModule extends AbstractModule {

    private WeakReference<IssueStore> issues;

    private WeakReference<GistStore> gists;

    private WeakReference<CommitStore> commits;

    @Override
    protected void configure() {
        install(new ServicesModule());
        install(new FactoryModuleBuilder().build(SyncCampaign.Factory.class));
        install(new FactoryModuleBuilder()
                .build(OrganizationRepositories.Factory.class));
    }

    @Provides
    Account account(Context context){
        AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        Account[] accounts = accountManager.getAccountsByType(context.getString(R.string.account_type));
        return accounts[0];
    }

    @Provides
    @Named("cacheDir")
    File cacheDir(Context context) {
        return new File(context.getFilesDir(), "cache");
    }

    @Provides
    IssueStore issueStore(Context context) {
        IssueStore store = issues != null ? issues.get() : null;
        if (store == null) {
            store = new IssueStore(context);
            issues = new WeakReference<>(store);
        }
        return store;
    }

    @Provides
    GistStore gistStore(Context context) {
        GistStore store = gists != null ? gists.get() : null;
        if (store == null) {
            store = new GistStore(context);
            gists = new WeakReference<>(store);
        }
        return store;
    }

    @Provides
    CommitStore commitStore(Context context) {
        CommitStore store = commits != null ? commits.get() : null;
        if (store == null) {
            store = new CommitStore(context);
            commits = new WeakReference<>(store);
        }
        return store;
    }
}


text:
using System;
using System.Data.Entity;
using VowTracker.Model;

namespace VowTracker.DataAccess
{
    public class VowTrackerInitializer : DropCreateDatabaseIfModelChanges<VowTrackerDbContext>
    {
        protected override void Seed(VowTrackerDbContext context)
        {
            Company company = new Company();
            company.Name = "Jorge Inc.";
            context.Companies.Add(company);
            context.SaveChanges();

            Vow vow = new Vow();
            vow.Company = company;
            vow.Statement = "I will make this app work";
            vow.StatementDate = DateTime.UtcNow;
            vow.StatementLink = "http://www.google.com/";
            vow.PromisedDate = DateTime.UtcNow.AddMonths(1);
            context.Vows.Add(vow);
            context.SaveChanges();
        }
    }
}


text:
static const NSString* kPlaybackFinishedUserInfoErrorKey=@"error";

typedef enum {
    VASTFirstQuartile,
    VASTSecondQuartile,
    VASTThirdQuartile,
    VASTFourtQuartile,
} CurrentVASTQuartile;

@interface SKVASTViewController() <UIGestureRecognizerDelegate>
{
    NSURL *mediaFileURL;
    NSArray *clickTracking;
    NSArray *vastErrors;
    NSArray *impressions;
    NSTimer *playbackTimer;
    NSTimer *initialDelayTimer;
    NSTimer *videoLoadTimeoutTimer;
    NSTimeInterval movieDuration;
    NSTimeInterval playedSeconds;

    SKVASTControls *controls;

    float currentPlayedPercentage;
    BOOL isPlaying;
    BOOL isViewOnScreen;
    BOOL hasPlayerStarted;
    BOOL isLoadCalled;
    BOOL vastReady;
    BOOL statusBarHidden;
    CurrentVASTQuartile currentQuartile;
    UIActivityIndicatorView *loadingIndicator;
    UIViewController *presentingViewController;

    SKReachability *reachabilityForVAST;
    NetworkReachable networkReachableBlock;
    NetworkUnreachable networkUnreachableBlock;
}

@property(nonatomic, strong) MPMoviePlayerController *moviePlayer;
@property(nonatomic, strong) UITapGestureRecognizer *touchGestureRecognizer;
@property(nonatomic, strong) SKVASTEventProcessor *eventProcessor;
@property(nonatomic, strong) NSMutableArray *videoHangTest;
@property(nonatomic, assign) BOOL networkCurrentlyReachable;

@end

@implementation SKVASTViewController

#pragma mark - Init & dealloc

- (id)init
{
    return [self initWithDelegate:nil withViewController:nil];
}

// designated initializer
- (id)initWithDelegate:(id<SKVASTViewControllerDelegate>)delegate withViewController:(UIViewController *)viewController
{
    self = [super init];
    if (self) {
        _delegate = delegate;
        presentingViewController = viewController;
        currentQuartile=VASTFirstQuartile;
        self.videoHangTest=[NSMutableArray arrayWithCapacity:20];
        [self setupReachability];

        [[NSNotificationCenter defaultCenter] addObserver: self
												 selector: @selector(applicationDidBecomeActive:)
													 name: UIApplicationDidBecomeActiveNotification
												   object: nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(movieDuration:)
                                                     name:MPMovieDurationAvailableNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayBackDidFinish:)
                                                     name:MPMoviePlayerPlaybackDidFinishNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playbackStateChangeNotification:)
                                                     name:MPMoviePlayerPlaybackStateDidChangeNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlayerLoadStateChanged:)
                                                     name:MPMoviePlayerLoadStateDidChangeNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(movieSourceType:)
                                                     name:MPMovieSourceTypeAvailableNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc
{
    [reachabilityForVAST stopNotifier];
    [self removeObservers];
}

#pragma mark - Load methods

- (void)loadVideoWithURL:(NSURL *)url
{
    [self loadVideoUsingSource:url];
}

- (void)loadVideoWithData:(NSData *)xmlContent
{
    [self loadVideoUsingSource:xmlContent];
}

- (void)loadVideoUsingSource:(id)source
{
    if ([source isKindOfClass:[NSURL class]])
    {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Starting loadVideoWithURL"];
    } else {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Starting loadVideoWithData"];
    }

    if (isLoadCalled) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Ignoring loadVideo because a load is in progress."];
        return;
    }
    isLoadCalled = YES;

    void (^parserCompletionBlock)(SKVASTModel *vastModel, SKVASTError vastError) = ^(SKVASTModel *vastModel, SKVASTError vastError) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"back from block in loadVideoFromData"];

        if (!vastModel) {
            [SKLogger error:@"VAST - View Controller" withMessage:@"parser error"];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {  // The VAST document was not readable, so no Error urls exist, thus none are sent.
                [self.delegate vastError:self error:vastError];
            }
            return;
        }

        self.eventProcessor = [[SKVASTEventProcessor alloc] initWithTrackingEvents:[vastModel trackingEvents] withDelegate:_delegate];
        impressions = [vastModel impressions];
        vastErrors = [vastModel errors];
        self.clickThrough = [[vastModel clickThrough] url];
        clickTracking = [vastModel clickTracking];
        mediaFileURL = [SKVASTMediaFilePicker pick:[vastModel mediaFiles]].url;

        if(!mediaFileURL) {
            [SKLogger error:@"VAST - View Controller" withMessage:@"Error - VASTMediaFilePicker did not find a compatible mediaFile - VASTViewcontroller will not be presented"];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorNoCompatibleMediaFile];
            }
            if (vastErrors) {
                [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
                [self.eventProcessor sendVASTUrlsWithId:vastErrors];
            }
            return;
        }

        // VAST document parsing OK, player ready to attempt play, so send vastReady
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending vastReady: callback"];
        vastReady = YES;
        [self.delegate vastReady:self];
    };

    SKVAST2Parser *parser = [[SKVAST2Parser alloc] init];
    if ([source isKindOfClass:[NSURL class]]) {
        if (!self.networkCurrentlyReachable) {
            [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"No network available - VASTViewcontroller will not be presented"]];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorNoInternetConnection];  // There is network so no requests can be sent, we don't queue errors, so no external Error event is sent.
            }
            return;
        }
        [parser parseWithUrl:(NSURL *)source completion:parserCompletionBlock];     // Load the and parse the VAST document at the supplied URL
    } else {
        [parser parseWithData:(NSData *)source completion:parserCompletionBlock];   // Parse a VAST document in supplied data
    }
}

#pragma mark - View lifecycle

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    isViewOnScreen=YES;
    if (!hasPlayerStarted) {
        loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") ) {
            loadingIndicator.frame = CGRectMake( (self.view.frame.size.width/2)-25.0, (self.view.frame.size.height/2)-25.0,50,50);
        }
        else {
            loadingIndicator.frame = CGRectMake( (self.view.frame.size.height/2)-25.0, (self.view.frame.size.width/2)-25.0,50,50);
        }
        [loadingIndicator startAnimating];
        [self.view addSubview:loadingIndicator];
    } else {
        // resuming from background or phone call, so resume if was playing, stay paused if manually paused
        [self handleResumeState];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    statusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden];
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        [[UIApplication sharedApplication] setStatusBarHidden:statusBarHidden withAnimation:UIStatusBarAnimationNone];
    }
}

#pragma mark - App lifecycle

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [SKLogger debug:@"VAST - View Controller" withMessage:@"applicationDidBecomeActive"];
    [self handleResumeState];
}

#pragma mark - MPMoviePlayerController notifications

- (void)playbackStateChangeNotification:(NSNotification *)notification
{
    @synchronized (self) {
        MPMoviePlaybackState state = [self.moviePlayer playbackState];
        [SKLogger debug:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"playback state change to %li", (long)state]];

        switch (state) {
            case MPMoviePlaybackStateStopped:  // 0
                [SKLogger debug:@"VAST - View Controller" withMessage:@"video stopped"];
                break;
            case MPMoviePlaybackStatePlaying:  // 1
                isPlaying=YES;
                if (loadingIndicator) {
                    [self stopVideoLoadTimeoutTimer];
                    [loadingIndicator stopAnimating];
                    [loadingIndicator removeFromSuperview];
                    loadingIndicator = nil;
                }
                if (isViewOnScreen) {
                    [SKLogger debug:@"VAST - View Controller" withMessage:@"video is playing"];
                    [self startPlaybackTimer];
                }
                break;
            case MPMoviePlaybackStatePaused:  // 2
                [self stopPlaybackTimer];
                [SKLogger debug:@"VAST - View Controller" withMessage:@"video paused"];
                isPlaying=NO;
                break;
            case MPMoviePlaybackStateInterrupted:  // 3
                [SKLogger debug:@"VAST - View Controller" withMessage:@"video interrupt"];
                break;
            case MPMoviePlaybackStateSeekingForward:  // 4
                [SKLogger debug:@"VAST - View Controller" withMessage:@"video seeking forward"];
                break;
            case MPMoviePlaybackStateSeekingBackward:  // 5
                [SKLogger debug:@"VAST - View Controller" withMessage:@"video seeking backward"];
                break;
            default:
                [SKLogger debug:@"VAST - View Controller" withMessage:@"undefined state change"];
                break;
        }
    }
}

- (void)moviePlayerLoadStateChanged:(NSNotification *)notification
{
    [SKLogger debug:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"movie player load state is %li", (long)self.moviePlayer.loadState]];

    if ((self.moviePlayer.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK )
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
        [self showAndPlayVideo];
    }
}

- (void)moviePlayBackDidFinish:(NSNotification *)notification
{
    @synchronized(self) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"playback did finish"];

        NSDictionary* userInfo=[notification userInfo];
        NSString* error= userInfo[kPlaybackFinishedUserInfoErrorKey];

        if (error) {
            [self stopVideoLoadTimeoutTimer];  // don't time out if there was a playback error
            [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"playback error:  %@", error]];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorPlaybackError];
            }
            if (vastErrors) {
                [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
                [self.eventProcessor sendVASTUrlsWithId:vastErrors];
            }
            [self close];
        } else {
            // no error, clean finish, so send track complete
            [self.eventProcessor trackEvent:VASTEventTrackComplete];
            [self updatePlayedSeconds];
            [self showControls];
            [controls toggleToPlayButton:YES];
        }
    }
}

- (void)movieDuration:(NSNotification *)notification
{
    @try {
        movieDuration = self.moviePlayer.duration;
    }
    @catch (NSException *e) {
        [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Exception - movieDuration: %@", e]];
        // The movie too short error will fire if movieDuration is < 0.5 or is a NaN value, so no need for further action here.
    }

    [SKLogger debug:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"playback duration is %f", movieDuration]];

    if (movieDuration < 0.5 || isnan(movieDuration)) {
        // movie too short - ignore it
        [self stopVideoLoadTimeoutTimer];  // don't time out in this case
        [SKLogger warning:@"VAST - View Controller" withMessage:@"Movie too short - will dismiss player"];
        if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
            [self.delegate vastError:self error:VASTErrorMovieTooShort];
        }
        if (vastErrors) {
            [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
            [self.eventProcessor sendVASTUrlsWithId:vastErrors];
        }
        [self close];
    }
}

- (void)movieSourceType:(NSNotification *)notification
{
    MPMovieSourceType sourceType;
    @try {
        sourceType = self.moviePlayer.movieSourceType;
    }
    @catch (NSException *e) {
        [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Exception - movieSourceType: %@", e]];
        // sourceType is used for info only - any player related error will be handled otherwise, ultimately by videoTimeout, so no other action needed here.
    }

    [SKLogger debug:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"movie source type is %li", (long)sourceType]];
}

#pragma mark - Orientation handling

// force to always play in Landscape
- (BOOL)shouldAutorotate
{
    NSArray *supportedOrientationsInPlist = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];
    BOOL isLandscapeLeftSupported = [supportedOrientationsInPlist containsObject:@"UIInterfaceOrientationLandscapeLeft"];
    BOOL isLandscapeRightSupported = [supportedOrientationsInPlist containsObject:@"UIInterfaceOrientationLandscapeRight"];
    return isLandscapeLeftSupported && isLandscapeRightSupported;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    UIInterfaceOrientation currentInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    return UIInterfaceOrientationIsLandscape(currentInterfaceOrientation) ? currentInterfaceOrientation : UIInterfaceOrientationLandscapeRight;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark - Timers

// playbackTimer - keeps track of currentPlayedPercentage
- (void)startPlaybackTimer
{
    @synchronized (self) {
        [self stopPlaybackTimer];
        [SKLogger debug:@"VAST - View Controller" withMessage:@"start playback timer"];
        playbackTimer = [NSTimer scheduledTimerWithTimeInterval:kPlayTimeCounterInterval
                                                         target:self
                                                       selector:@selector(updatePlayedSeconds)
                                                       userInfo:nil
                                                        repeats:YES];
    }
}

- (void)stopPlaybackTimer
{
    [SKLogger debug:@"VAST - View Controller" withMessage:@"stop playback timer"];
    [playbackTimer invalidate];
    playbackTimer = nil;
}

- (void)updatePlayedSeconds
{
    @try {
        playedSeconds = self.moviePlayer.currentPlaybackTime;
    }
    @catch (NSException *e) {
        [SKLogger warning:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Exception - updatePlayedSeconds: %@", e]];
        // The hang test below will fire if playedSeconds doesn't update (including a NaN value), so no need for further action here.
    }

    [self.videoHangTest addObject:@((int) (playedSeconds * 10.0))];     // add new number to end of hang test buffer

    if ([self.videoHangTest count]>20) {  // only check for hang if we have at least 20 elements or about 5 seconds of played video, to prevent false positives
        if ([[self.videoHangTest firstObject] integerValue]==[[self.videoHangTest lastObject] integerValue]) {
            [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Video error - video player hung at playedSeconds: %f", playedSeconds]];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorPlayerHung];
            }
            if (vastErrors) {
                [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
                [self.eventProcessor sendVASTUrlsWithId:vastErrors];
            }
            [self close];
        }
        [self.videoHangTest removeObjectAtIndex:0];   // remove oldest number from start of hang test buffer
    }

   	currentPlayedPercentage = (float)100.0*(playedSeconds/movieDuration);
    [controls updateProgressBar: currentPlayedPercentage/100.0 withPlayedSeconds:playedSeconds withTotalDuration:movieDuration];

    switch (currentQuartile) {

        case VASTFirstQuartile:
            if (currentPlayedPercentage>25.0) {
                [self.eventProcessor trackEvent:VASTEventTrackFirstQuartile];
                currentQuartile=VASTSecondQuartile;
            }
            break;

        case VASTSecondQuartile:
            if (currentPlayedPercentage>50.0) {
                [self.eventProcessor trackEvent:VASTEventTrackMidpoint];
                currentQuartile=VASTThirdQuartile;
            }
            break;

        case VASTThirdQuartile:
            if (currentPlayedPercentage>75.0) {
                [self.eventProcessor trackEvent:VASTEventTrackThirdQuartile];
                currentQuartile=VASTFourtQuartile;
            }
            break;

        default:
            break;
    }
}

// Reports error if vast video document times out while loading
- (void)startVideoLoadTimeoutTimer
{
    [SKLogger error:@"VAST - View Controller" withMessage:@"Start Video Load Timer"];
    videoLoadTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:[VASTSettings vastVideoLoadTimeout]
                                                             target:self
                                                           selector:@selector(videoLoadTimerFired)
                                                           userInfo:nil
                                                            repeats:NO];
}

- (void)stopVideoLoadTimeoutTimer
{
    [videoLoadTimeoutTimer invalidate];
    videoLoadTimeoutTimer = nil;
    [SKLogger error:@"VAST - View Controller" withMessage:@"Stop Video Load Timer"];
}

- (void)videoLoadTimerFired
{
    [SKLogger error:@"VAST - View Controller" withMessage:@"Video Load Timeout"];
    [self close];

    if (vastErrors) {
       [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
        [self.eventProcessor sendVASTUrlsWithId:vastErrors];
    }
    if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
        [self.delegate vastError:self error:VASTErrorLoadTimeout];
    }
}

- (void)killTimers
{
    [self stopPlaybackTimer];
    [self stopVideoLoadTimeoutTimer];
}

#pragma mark - Methods needed to support toolbar buttons

- (void)play
{
    @synchronized (self) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"playVideo"];

        if (!vastReady) {
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorPlayerNotReady];                  // This is not a VAST player error, so no external Error event is sent.
                [SKLogger warning:@"VAST - View Controller" withMessage:@"Ignoring call to playVideo before the player has sent vastReady."];
                return;
            }
        }

        if (isViewOnScreen) {
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorPlaybackAlreadyInProgress];       // This is not a VAST player error, so no external Error event is sent.
                [SKLogger warning:@"VAST - View Controller" withMessage:@"Ignoring call to playVideo while playback is already in progress"];
                return;
            }
        }

        if (!self.networkCurrentlyReachable) {
            [SKLogger error:@"VAST - View Controller" withMessage:@"No network available - VASTViewcontroller will not be presented"];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorNoInternetConnection];   // There is network so no requests can be sent, we don't queue errors, so no external Error event is sent.
            }
            return;
        }

        // Now we are ready to launch the player and start buffering the content
        // It will throw error if the url is invalid for any reason. In this case, we don't even need to open ViewController.
        [SKLogger debug:@"VAST - View Controller" withMessage:@"initializing player"];

        @try {
            playedSeconds = 0.0;
            currentPlayedPercentage = 0.0;

            // Create and prepare the player to confirm the video is playable (or not) as early as possible
            [self startVideoLoadTimeoutTimer];
            self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: mediaFileURL];
            self.moviePlayer.shouldAutoplay = NO; // YES by default - But we don't want to autoplay
            self.moviePlayer.controlStyle=MPMovieControlStyleNone;  // To use custom control toolbar
            [self.moviePlayer prepareToPlay];
            [self presentPlayer];
        }
        @catch (NSException *e) {
            [SKLogger error:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Exception - moviePlayer.prepareToPlay: %@", e]];
            if ([self.delegate respondsToSelector:@selector(vastError:error:)]) {
                [self.delegate vastError:self error:VASTErrorPlaybackError];
            }
            if (vastErrors) {
                [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Error requests"];
                [self.eventProcessor sendVASTUrlsWithId:vastErrors];
            }
            return;
        }
    }
}

- (void)pause
{
    [SKLogger debug:@"VAST - View Controller" withMessage:@"pause"];
    [self handlePauseState];
}

- (void)resume
{
    [SKLogger debug:@"VAST - View Controller" withMessage:@"resume"];
    [self handleResumeState];
}

- (void)info
{
    if (clickTracking) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending clickTracking requests"];
        [self.eventProcessor sendVASTUrlsWithId:clickTracking];
    }
    if ([self.delegate respondsToSelector:@selector(vastOpenBrowseWithUrl:)]) {
        [self.delegate vastOpenBrowseWithUrl:self.clickThrough];
    }
}

- (void)close
{
    @synchronized (self) {
        [self removeObservers];
        [self killTimers];
        [self.moviePlayer stop];

        self.moviePlayer=nil;

        if (isViewOnScreen) {
            // send close any time the player has been dismissed
            [self.eventProcessor trackEvent:VASTEventTrackClose];
            [SKLogger debug:@"VAST - View Controller" withMessage:@"Dismissing VASTViewController"];
            [self dismissViewControllerAnimated:NO completion:nil];

            if ([self.delegate respondsToSelector:@selector(vastDidDismissFullScreen:)]) {
                [self.delegate vastDidDismissFullScreen:self];
            }
        }
    }
}

//
// Handle touches
//
#pragma mark - Gesture setup & delegate

- (void)setUpTapGestureRecognizer
{
    self.touchGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTouches)];
    self.touchGestureRecognizer.delegate = self;
    [self.touchGestureRecognizer setNumberOfTouchesRequired:1];
    self.touchGestureRecognizer.cancelsTouchesInView=NO;  // required to enable controlToolbar buttons to receive touches
    [self.view addGestureRecognizer:self.touchGestureRecognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)handleTouches{
    if (!initialDelayTimer) {
        [self showControls];
    }
}

- (void)showControls
{
    initialDelayTimer = nil;
    [controls showControls];
}

#pragma mark - Reachability

- (void)setupReachability
{
    reachabilityForVAST = [SKReachability reachabilityForInternetConnection];
    reachabilityForVAST.reachableOnWWAN = YES;            // Do allow 3G/WWAN for reachablity

    __unsafe_unretained SKVASTViewController *self_ = self; // avoid block retain cycle

    networkReachableBlock  = ^(SKReachability*reachabilityForVAST){
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Network reachable"];
        self_.networkCurrentlyReachable = YES;
    };

    networkUnreachableBlock = ^(SKReachability*reachabilityForVAST){
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Network not reachable"];
        self_.networkCurrentlyReachable = NO;
    };

    reachabilityForVAST.reachableBlock = networkReachableBlock;
    reachabilityForVAST.unreachableBlock = networkUnreachableBlock;

    [reachabilityForVAST startNotifier];
    self.networkCurrentlyReachable = [reachabilityForVAST isReachable];
    [SKLogger debug:@"VAST - View Controller" withMessage:[NSString stringWithFormat:@"Network is reachable %d", self.networkCurrentlyReachable]];
}

#pragma mark - Other methods

- (BOOL)isPlaying
{
    return isPlaying;
}

- (void)showAndPlayVideo
{
    [SKLogger debug:@"VAST - View Controller" withMessage:@"adding player to on screen view and starting play sequence"];

    self.moviePlayer.view.frame=self.view.bounds;
    [self.view addSubview:self.moviePlayer.view];

    // N.B. The player has to be ready to play before controls may be added to the player's view
    [SKLogger debug:@"VAST - View Controller" withMessage:@"initializing player controls"];
    controls = [[SKVASTControls alloc] initWithVASTPlayer:self];
    [self.moviePlayer.view addSubview: controls];

    if (kFirstShowControlsDelay > 0) {
        [controls hideControls];
        initialDelayTimer = [NSTimer scheduledTimerWithTimeInterval:kFirstShowControlsDelay
                                                             target:self
                                                           selector:@selector(showControls)
                                                           userInfo:nil
                                                            repeats:NO];
    } else {
        [self showControls];
    }

    [self.moviePlayer play];
    hasPlayerStarted=YES;

    if (impressions) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"Sending Impressions requests"];
        [self.eventProcessor sendVASTUrlsWithId:impressions];
    }
    [self.eventProcessor trackEvent:VASTEventTrackStart];
    [self setUpTapGestureRecognizer];
}

- (void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieSourceTypeAvailableNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)handlePauseState
{
    @synchronized (self) {
    if (isPlaying) {
        [SKLogger debug:@"VAST - View Controller" withMessage:@"handle pausing player"];
        [self.moviePlayer pause];
        isPlaying = NO;
        [self.eventProcessor trackEvent:VASTEventTrackPause];
    }
    [self stopPlaybackTimer];
    }
}

- (void)handleResumeState
{
    @synchronized (self) {
    if (hasPlayerStarted) {
        if (![controls controlsPaused]) {
        // resuming from background or phone call, so resume if was playing, stay paused if manually paused by inspecting controls state
        [SKLogger debug:@"VAST - View Controller" withMessage:@"handleResumeState, resuming player"];
        [self.moviePlayer play];
        isPlaying = YES;
        [self.eventProcessor trackEvent:VASTEventTrackResume];
        [self startPlaybackTimer];
        }
    } else if (self.moviePlayer) {
        [self showAndPlayVideo];   // Edge case: loadState is playable but not playThroughOK and had resignedActive, so play immediately on resume
    }
    }
}

- (void)presentPlayer
{
    if ([self.delegate respondsToSelector:@selector(vastWillPresentFullScreen:)]) {
        [self.delegate vastWillPresentFullScreen:self];
    }

    if ([presentingViewController respondsToSelector:@selector(presentViewController:animated:completion:)]) {
        // used if running >= iOS 6
        [presentingViewController presentViewController:self animated:NO completion:nil];
    } else {
        // Turn off the warning about using a deprecated method.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [presentingViewController presentModalViewController:self animated:NO];
#pragma clang diagnostic pop
    }
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Placographa mexicana Rehm

### Remarks
null


text:
					  Repositórios

					  Configurações

Configurações

		<form method="POST" action="config">

				Localização dos repositórios
				<input type="text" value="<?=$ini->repodir ?>" id="repoLocal"   name="repodir" placeholder="" class="form-control" required>
				Localizacao dos repositórios ex: /var/www.

				Host
				<input type="text" id="host" name="host" value="<?=$ini->banco['host'] ?>" placeholder="" class="form-control" required>

				Usuário
				<input type="text" value="<?=$ini->banco['user'] ?>" id="user" name="user" class="form-control" required>
				Usuário do banco de dados.

				Senha
				<input type="password" value="<?=$ini->banco['senha'] ?>" id="senha" name="senha" class="form-control" >
				Senha do banco de dados.

				Banco
				<input type="text" id="bd" name="bd" value="<?=$ini->banco['bd'] ?>" placeholder="" class="form-control" required>

				<button class="btn btn-success">Salvar</button>

		</form>


text:
require "bootstrap_tools/version"

require 'bootstrap_tools/helpers'
require 'haml'
require 'jquery-ui-rails'

module BootstrapTools
  class Engine < ::Rails::Engine
    initializer "bootstrap_tools.initialize" do |app|
      ActionView::Base.send :include, BootstrapTools::Helpers
    end
  end
end


text:
@interface JCHATAlbumModel : NSObject
@property(strong, nonatomic)UIImage *albumImage;
@property(strong, nonatomic)NSString *albumTittle;
@property(assign, nonatomic)NSInteger albumCount;
//ios 8 photoAlbum
@property(strong, nonatomic)PHCollection *albumCollection;
@property(strong, nonatomic)PHFetchResult *albumFetchResult;
//ios 8 以前
@property (strong, nonatomic) ALAssetsGroup *assetsGroup;

- (void)setDataWithAssets:(ALAssetsGroup *)assetsGroup;

- (void)setDataWithAlbumCollection:(PHCollection *)albumCollection;
- (void)setDataWithAlbumResult:(PHFetchResult *)albumFetchResult;
@end


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using dashing.net.common;
using dashing.net.streaming;

namespace dashing.net.jobs
{
    [Export(typeof(IJob))]
    public class Sample : IJob
    {
        private readonly Random _rand;

        public int CurrentValuation { get; private set; }
        public int LastValuation { get; private set; }

        public Lazy<Timer> Timer { get; private set; }

        public Sample()
        {
            _rand = new Random();

            CurrentValuation = _rand.Next(100);

            Timer = new Lazy<Timer>(() => new Timer(SendMessage, null, TimeSpan.Zero, TimeSpan.FromSeconds(2)));
        }

        protected void SendMessage(object message)
        {
            LastValuation = CurrentValuation;

            CurrentValuation = _rand.Next(100);

            //Dashing.SendMessage(new {current = CurrentValuation, last = LastValuation, id = "sample"});
        }
    }
}


text:
#ifndef _SYSDEP_LINUX_H
#define _SYSDEP_LINUX_H

#include <bits/wordsize.h>
#include <kernel-features.h>
#include <endian.h>
#include <errno.h>

#undef INTERNAL_SYSCALL_ERROR_P
#define INTERNAL_SYSCALL_ERROR_P(val) \
  ((unsigned long int) (val) > -4096UL)

#ifndef SYSCALL_ERROR_LABEL
# define SYSCALL_ERROR_LABEL(sc_err)					\
  ({									\
    __set_errno (sc_err);						\
    -1L;								\
  })
#endif

/* Define a macro which expands into the inline wrapper code for a system
   call.  It sets the errno and returns -1 on a failure, or the syscall
   return value otherwise.  */
#undef INLINE_SYSCALL
#define INLINE_SYSCALL(name, nr, args...)				\
  ({									\
    long int sc_ret = INTERNAL_SYSCALL (name, nr, args);		\
    __glibc_unlikely (INTERNAL_SYSCALL_ERROR_P (sc_ret))		\
    ? SYSCALL_ERROR_LABEL (INTERNAL_SYSCALL_ERRNO (sc_ret))		\
    : sc_ret;								\
  })

#undef INTERNAL_SYSCALL_ERRNO
#define INTERNAL_SYSCALL_ERRNO(val)     (-(val))

/* Set error number and return -1.  A target may choose to return the
   internal function, __syscall_error, which sets errno and returns -1.
   We use -1l, instead of -1, so that it can be casted to (void *).  */
#define INLINE_SYSCALL_ERROR_RETURN_VALUE(err)  \
  ({						\
    __set_errno (err);				\
    -1l;					\
  })

/* Provide a dummy argument that can be used to force register
   alignment for register pairs if required by the syscall ABI.  */
#ifdef __ASSUME_ALIGNED_REGISTER_PAIRS
#define __ALIGNMENT_ARG 0,
#define __ALIGNMENT_COUNT(a,b) b
#else
#define __ALIGNMENT_ARG
#define __ALIGNMENT_COUNT(a,b) a
#endif

/* Provide a common macro to pass 64-bit value on syscalls.  */
#if __WORDSIZE == 64 || defined __ASSUME_WORDSIZE64_ILP32
# define SYSCALL_LL(val)   (val)
# define SYSCALL_LL64(val) (val)
#else
#define SYSCALL_LL(val)   \
  __LONG_LONG_PAIR ((val) >> 31, (val))
#define SYSCALL_LL64(val) \
  __LONG_LONG_PAIR ((long) ((val) >> 32), (long) ((val) & 0xffffffff))
#endif

/* Provide a common macro to pass 64-bit value on pread and pwrite
   syscalls.  */
#ifdef __ASSUME_PRW_DUMMY_ARG
# define SYSCALL_LL_PRW(val)   0, SYSCALL_LL (val)
# define SYSCALL_LL64_PRW(val) 0, SYSCALL_LL64 (val)
#else
# define SYSCALL_LL_PRW(val)   __ALIGNMENT_ARG SYSCALL_LL (val)
# define SYSCALL_LL64_PRW(val) __ALIGNMENT_ARG SYSCALL_LL64 (val)
#endif

/* Provide a macro to pass the off{64}_t argument on p{readv,writev}{64}.  */
#define LO_HI_LONG(val) \
 (long) (val), \
 (long) (((uint64_t) (val)) >> 32)

/* Export the ___brk_addr symbol on brk.c implementation (some ABIs export
   it due and old crtstuff.c code).  */
#define HAVE_INTERNAL_BRK_ADDR_SYMBOL   0

#endif /* _SYSDEP_LINUX_H  */


text:
require 'red_artisan/core_image/processor'

module Technoweenie # :nodoc:
  module AttachmentFu # :nodoc:
    module Processors
      module CoreImageProcessor
        def self.included(base)
          base.send :extend, ClassMethods
          base.alias_method_chain :process_attachment, :processing
        end

        module ClassMethods
          def with_image(file, &block)
            block.call OSX::CIImage.from(file)
          end
        end

        protected
          def process_attachment_with_processing
            return unless process_attachment_without_processing
            with_image do |img|
              self.width  = img.extent.size.width  if respond_to?(:width)
              self.height = img.extent.size.height if respond_to?(:height)
              resize_image_or_thumbnail! img
              callback_with_args :after_resize, img
            end if image?
          end

          # Performs the actual resizing operation for a thumbnail
          def resize_image(img, size)
            processor = ::RedArtisan::CoreImage::Processor.new(img)
            size = size.first if size.is_a?(Array) && size.length == 1
            if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
              if size.is_a?(Fixnum)
                processor.fit(size)
              else
                processor.resize(size[0], size[1])
              end
            else
              new_size = [img.extent.size.width, img.extent.size.height] / size.to_s
              processor.resize(new_size[0], new_size[1])
            end

            processor.render do |result|
              self.width  = result.extent.size.width  if respond_to?(:width)
              self.height = result.extent.size.height if respond_to?(:height)

              # Get a new temp_path for the image before saving
              temp_paths.unshift Tempfile.new(random_tempfile_filename, Technoweenie::AttachmentFu.tempfile_path).path
              result.save self.temp_path, OSX::NSJPEGFileType
              self.size = File.size(self.temp_path)
            end
          end
      end
    end
  end
end


text:
/**
 *
 */
package io.pkts.frame;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import io.pkts.PktsTestBase;
import io.pkts.buffer.Buffer;
import io.pkts.framer.PcapFramer;
import io.pkts.packet.PCapPacket;

import org.junit.Before;
import org.junit.Test;

/**
 * @author jonas@jonasborjesson.com
 *
 */
public class PcapFrameTest extends PktsTestBase {

    private PcapFramer framer;

    /**
     * @throws java.lang.Exception
     */
    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        // remember, the defaultByteOrder etc has already been parsed out by
        // the test base
        this.framer = new PcapFramer(this.defaultPcapHeader, this.framerManager);
    }

    /**
     * Make sure that the Packet that we get from {@link Frame#parse()} is
     * actually correct.
     *
     * @throws Exception
     */
    @Test
    public void testParsePacket() throws Exception {
        // remember, this is the first packet in the pcap and it has already
        // been framed by the test base class
        assertThat(this.defaultPcapPacket.getTotalLength(), is(547L));
        assertThat(this.defaultPcapPacket.getCapturedLength(), is(547L));
        assertThat(this.defaultPcapPacket.getArrivalTime(), is(1340495109792454L));

        // all times have been copied from wireshark so we know they are good
        verifyNextPacket(this.pcapStream, 348, 1340495109792862L);
        verifyNextPacket(this.pcapStream, 507, 1340495109793013L);
        verifyNextPacket(this.pcapStream, 398, 1340495109793443L);
        verifyNextPacket(this.pcapStream, 547, 1340495110791005L);
        verifyNextPacket(this.pcapStream, 348, 1340495110791405L);

        // there are a total of 30 frames in this pcap.
        // Read all but the last
        for (int i = 6; i < 29; ++i) {
            this.framer.frame(null, this.pcapStream);
        }

        // now verify this last one
        verifyNextPacket(this.pcapStream, 340, 1340495114795676L);
    }

    private void verifyNextPacket(final Buffer in, final int expectedLength, final long expectedArrivalTime)
            throws Exception {
        final PCapPacket p = this.framer.frame(null, in);
        assertThat(p.getTotalLength(), is((long) expectedLength));
        assertThat(p.getCapturedLength(), is((long) expectedLength));
        assertThat(p.getArrivalTime(), is(expectedArrivalTime));
    }

}


text:
#include "ConstraintImp.h"

namespace pss {

constraint::constraint(base_item *p, const expr_list &stmt) :
		base_item(new ConstraintImp(this, p, "", stmt)) { }

ConstraintImp::ConstraintImp(constraint *master, base_item *p, const expr_list &stmt) :
		NamedBaseItemImp(master, BaseItemImp::TypeConstraint, p), m_stmt(stmt) { }

constraint::constraint(base_item *p, const std::string &name, const expr_list &stmt) :
		base_item(new ConstraintImp(this, p, name, stmt)) { }

ConstraintImp::ConstraintImp(constraint *master, base_item *p, const std::string &name, const expr_list &stmt) :
		NamedBaseItemImp(master, BaseItemImp::TypeConstraint, p, name), m_stmt(stmt) { }

constraint::~constraint() {
	// TODO Auto-generated destructor stub
}

ConstraintImp::~ConstraintImp() {
	// TODO Auto-generated destructor stub
}

} /* namespace pss */


text:
title: Aug 1st after meeting review
category: General
---

Thank you to everyone that made it out. I really appreciate you showing interest and being a part of the group. Please RSVP for the next meetup.

If you want to know more about tonight's topic, please see my blog post on the topic that closely matches the format of tonight's presentation: https://kevinmarquette.github.io/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about

The scripts from tonight are posted here: https://github.com/SoCalPowerShell/HashtablePresentation

We talked about working with variables in strings and I mentioned this post for more information: https://kevinmarquette.github.io/2017-01-13-powershell-variable-substitution-in-strings

One more article that I talked about was this one my Mark Krous on line continuations: https://get-powershellblog.blogspot.com/2017/07/bye-bye-backtick-natural-line.html

I am most active on twitter @KevinMarquette and we have a website started at SoCalPowershell.org.

Thanks again, see you next time.

-Kevin Marquette


text:
layout   : post
title    : "Android KeyStore学习"
date     : 2017-05-22 23:24:00
author   : fxleyu
tags:
    - Android
---
Android KeyStore是Android系统对于Java安全架构的自定义实现。KeyStore是通过实现Provider接口的方式来实现的。

```java
// ~/system/security/keystore/key_store_service.cpp 是Android KeyStore具体逻辑的实现

// ~/frameworks/base/keystore 是KeyStore实现Java安全架构的接口。

// ~/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java 是把Android KeyStore配置到Android VM中。

// /data/misc/keystore/...  存储位置
```

- 安装证书/密钥

- 去除锁屏保护

**删除未加密密钥的调用堆栈**(从点击"YES,REMOVE",到未加密密钥删除)
```java
com.android.settings.ChrooseLockGeneric$ChrooseLockGenericFragment$FactoryResetProtectionWarningDialog
        .$1.DialogInterface.OnClickListener.onClick();
com.android.settings.ChrooseLockGeneric$ChrooseLockGenericFragment.setUnlockMethod();
com.android.settings.ChrooseLockGeneric$ChrooseLockGenericFragment.updateUnlockMethodAndFinish();
com.android.internal.widget.LockPatternUtils.clearLock();
com.android.service.LockSettingsService.setLockPassword();
com.android.service.LockSettingsService.setLockPasswordInternal();
com.android.service.LockSettingsService.setKeyStorePassword();
android.security.KeyStore.onUserPasswordChanged();
KeyStoreService.onUserPasswordChanged(); //key_store_service.cpp
KeyStore.resetUser(); //keystore.cpp
KeyStore.del(); //keystore.cpp
```

- 删除证书/密钥

# 什么是密钥库
密钥库系统由 KeyChain API 以及在 Android 4.3(API 级别 18)中引入的 Android 密钥库提
供程序功能使用。
Android 的加密系统,是独立与JDK的,其Java只是定义了spi而已。

```java
KeyPairGenerator
// frameworks/base/keystore
android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi

```

# 基本知识
1、加密模型

2、CA

# 简要理解

# 深入理解
## 1、 在设置中安装证书
Settings >> Security >> Install from SD card

```xml
<!-- 点击安装证书,实际上是启动如下Intent -->
<intent android:action="android.credentials.INSTALL"
        android:targetPackage="com.android.certinstaller"
        android:targetClass="com.android.certinstaller.CertInstallerMain"/>
```

启动后 certinstaller 应用的
```java

final String[] mimeTypes = MIME_MAPPINGS.keySet().toArray(new String[0]);
final Intent openIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
openIntent.setType("*/*");
openIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
openIntent.putExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, true);
startActivityForResult(openIntent, REQUEST_OPEN_DOCUMENT);

// 然后
if (requestCode == REQUEST_OPEN_DOCUMENT) {
    if (resultCode == RESULT_OK) {
        startInstallActivity(null, data.getData());
    } else {
        finish();
    }
}
```
如果数据检查无误,会使用如下`CertInstaller`来进行安装。
```java
if (mCredentials.hasCaCerts()) {
    KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
    Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
    if (intent == null) { // No screenlock
        onScreenlockOk();
    } else {
        // 重新确认安全密码
        startActivityForResult(intent, REQUEST_CONFIRM_CREDENTIALS);
    }
}
```
安装证书
```java
X509Certificate cert = mCredentials.getUserCertificate();
if (cert != null) {
    // find matched private key
    String key = Util.toMd5(cert.getPublicKey().getEncoded());
    Map<String, byte[]> map = getPkeyMap();
    byte[] privatekey = map.get(key);
    if (privatekey != null) {
        Log.d(TAG, "found matched key: " + privatekey);
        map.remove(key);
        savePkeyMap(map);

        mCredentials.setPrivateKey(privatekey);
    } else {
        Log.d(TAG, "didn't find matched private key: " + key);
    }
}
nameCredential();
```
安装Activity为
```java
Intent createSystemInstallIntent(final Context context) {
    Intent intent = new Intent("com.android.credentials.INSTALL");
    // To prevent the private key from being sniffed, we explicitly spell
    // out the intent receiver class.
    if (!isWear(context)) {
        intent.setClassName(Util.SETTINGS_PACKAGE, "com.android.settings.CredentialStorage");
    } else {
        intent.setClassName("com.google.android.apps.wearable.settings",
                "com.google.android.clockwork.settings.CredentialStorage");
    }
    intent.putExtra(Credentials.EXTRA_INSTALL_AS_UID, mUid);
    try {
        if (mUserKey != null) {
            intent.putExtra(Credentials.EXTRA_USER_PRIVATE_KEY_NAME,
                    Credentials.USER_PRIVATE_KEY + mName);
            intent.putExtra(Credentials.EXTRA_USER_PRIVATE_KEY_DATA,
                    mUserKey.getEncoded());
        }
        if (mUserCert != null) {
            intent.putExtra(Credentials.EXTRA_USER_CERTIFICATE_NAME,
                    Credentials.USER_CERTIFICATE + mName);
            intent.putExtra(Credentials.EXTRA_USER_CERTIFICATE_DATA,
                    Credentials.convertToPem(mUserCert));
        }
        if (!mCaCerts.isEmpty()) {
            intent.putExtra(Credentials.EXTRA_CA_CERTIFICATES_NAME,
                    Credentials.CA_CERTIFICATE + mName);
            X509Certificate[] caCerts
                    = mCaCerts.toArray(new X509Certificate[mCaCerts.size()]);
            intent.putExtra(Credentials.EXTRA_CA_CERTIFICATES_DATA,
                    Credentials.convertToPem(caCerts));
        }
        return intent;
    } catch (IOException e) {
        throw new AssertionError(e);
    } catch (CertificateEncodingException e) {
        throw new AssertionError(e);
    }
}
```

```java
android.security.KeyStore.put();
```
## 2、设置安全模式为 None

# 总结


text:
package gov.fubar.foo.bar;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Bar {
    private static Logger logger = LogManager.getLogger();
    public Bar() {
        logger.info("Instantiated");
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Apache.Arrow.Types;
using Xunit;

namespace Apache.Arrow.Tests
{
    public class DictionaryArrayTests
    {
        [Fact]
        public void CreateTest()
        {
            (StringArray originalDictionary, Int32Array originalIndicesArray, DictionaryArray dictionaryArray) =
                CreateSimpleTestData();

            Assert.Equal(dictionaryArray.Dictionary, originalDictionary);
            Assert.Equal(dictionaryArray.Indices, originalIndicesArray);
        }

        [Fact]
        public void SliceTest()
        {
            (StringArray originalDictionary, Int32Array originalIndicesArray, DictionaryArray dictionaryArray) =
                CreateSimpleTestData();

            int batchLength = originalIndicesArray.Length;
            for (int offset = 0; offset < batchLength; offset++)
            {
                for (int length = 1; offset + length <= batchLength; length++)
                {
                    var sliced = dictionaryArray.Slice(offset, length) as DictionaryArray;
                    var actualSlicedDictionary = sliced.Dictionary as StringArray;
                    var actualSlicedIndicesArray = sliced.Indices as Int32Array;

                    var expectedSlicedIndicesArray = originalIndicesArray.Slice(offset, length) as Int32Array;

                    //Dictionary is not sliced.
                    Assert.Equal(originalDictionary.Data, actualSlicedDictionary.Data);
                    Assert.Equal(expectedSlicedIndicesArray.ToList(), actualSlicedIndicesArray.ToList());
                }
            }
        }

        private Tuple<StringArray, Int32Array, DictionaryArray> CreateSimpleTestData()
        {
            StringArray originalDictionary = new StringArray.Builder().AppendRange(new[] { "a", "b", "c" }).Build();
            Int32Array originalIndicesArray = new Int32Array.Builder().AppendRange(new[] { 0, 0, 1, 1, 2, 2 }).Build();
            var dictionaryArray = new DictionaryArray(new DictionaryType(Int32Type.Default, StringType.Default, false), originalIndicesArray, originalDictionary);

            return Tuple.Create(originalDictionary, originalIndicesArray, dictionaryArray);
        }
    }
}


text:
/**
  `Ember.BackgroundImageView` loads a stateful image for its
  css background-image. Class names are updated according to the image state.

  Instances of `BackgroundImageView` can be created using the `background-image` Handlebars helper.
  ```handlebars
  {{background-image src="img/image1.jpg"}}
  ```

  @class BackgroundImageView
  @namespace Ember
  @extends Ember.View
  @uses Ember.ImageLoader
**/
Ember.BackgroundImageView = Ember.View.extend( Ember.ImageLoader, {
  attributeBindings: ['style'],
  classNames: ['background-image'],
  classNameBindings: ['loadingClass', 'errorClass'],

  /**
    Url to the image source.

    @property src
    @type String
    @default null
  */
  src: null,

  /**
    @private

    The final image url to load. A buffer to the src, which is
    useful for subclasses and mixins to modify the base src.

    @property finalSrc
    @default src
  */
  finalSrc: Ember.computed.oneWay('src'),

  /**
    Loading state class name. This can be overriden
    per instance or app wide using Ember.BackgroundImageView.reopen

    @property loadingClassName
    @type String
    @default 'loading'
  */
  loadingClassName: 'loading',

  /**
    Error state class name. This can be overriden
    per instance or app wide using Ember.BackgroundImageView.reopen

    @property errorClassName
    @type String
    @default 'error'
  */
  errorClassName: 'error',

  /**
    Computed style property string based on the src.

    @property style
    @type String
    @default null
  */
  style: Ember.computed(function() {
    var src = this.get('finalSrc');
    if(src) {
      return Ember.String.fmt('background-image:url("%@");', [src]);
    }
    return null;
  }).property('finalSrc'),

  /**
    @private

    Use the ImageLoader Mixin to load the image src on
    willInsertElement and whenever the src is changed.

    @method loadImageOnSrcSet
  */
  loadImageOnSrcSet: Ember.observer(function() {
    this.loadImage(this.get('finalSrc'));
  }, 'finalSrc').on('willInsertElement'),

  /**
    @private

    Computed property proxies for state classes
    so they can be easily overridden.

    @property loadingClass
    @property errorClass
  */
  loadingClass: Ember.computed(function() {
    if(this.get('isLoading')) { return this.get('loadingClassName'); }
  }).property('isLoading'),

  errorClass: Ember.computed(function() {
    if(this.get('isError')) { return this.get('errorClassName'); }
  }).property('isError')

});

/**
  `BackgroundImageView` `{{background-image}}` Handlebars helper.
*/
Ember.Handlebars.helper('background-image', Ember.BackgroundImageView);


text:
.. _raspberry_pi_luks:

=================================
Raspberry Pi LUKS Root Encryption
=================================

In this short guide I'll go over how I implemented full disk encryption using LUKS on my Raspberry Pi's root file system
**without needing a second Linux computer** to run commands on. All you need is your Raspberry Pi running Raspbian and a
USB flash drive.

An overview of the process:

1. Install software on your Raspberry Pi's Raspbian OS.
2. Build a custom and boot into the `initramfs <https://pi-ltsp.net/advanced/kernels.html#initramfs>`_.
3. Shrink your main file system.
4. Back up your main file system from the SD card to the USB drive.
5. Wipe SD card and create an empty encrypted partition.
6. Copy back your backed-up file system from USB on to your encrypted SD card.

.. warning::

    This guide involves backing up your data to a USB drive and destroying all data on your SD card. Though slim there
    is a possibility of failure. Be sure to have **proper backups of your Raspberry Pi** in case something goes wrong.
    Also note that **all data on your USB drive will be destroyed** during the process since it will temporarily hold
    all of your Raspberry Pi's data.

At the time of this writing I've tested this guide against *2017-01-11-raspbian-jessie.zip* and
*2017-01-11-raspbian-jessie-lite.zip* on a *Raspberry Pi 3 Model B V1.2* and a *Raspberry Pi Zero V1.3*.

Install Software
================

We'll begin by installing software and creating a new initramfs for your Raspberry Pi. This new initramfs will have the
``cryptsetup`` program needed to unlock the encrypted partition on every boot. We'll also include other tools to assist
in the initial encryption of your existing data.

First install some software:

.. code-block:: bash

    sudo apt-get install busybox cryptsetup initramfs-tools

Next we'll need to add a kernel post-install script. Since Raspbian doesn't normally use an initrd/initramfs it doesn't
auto-update the one we're about to create when a new kernel version comes out. Our initramfs holds kernel modules since
they're needed before the encrypted root file system can be mounted. When the kernel version changes it won't be able to
find its new modules. To fix this write the following to ``/etc/kernel/postinst.d/initramfs-rebuild``:

.. literalinclude:: _static/initramfs-rebuild.sh
    :language: bash

Now we want ``resize2fs`` and ``fdisk`` to be included in our initramfs so we'll need to create a hook file. Write the
following to ``/etc/initramfs-tools/hooks/resize2fs``:

.. literalinclude:: _static/resize2fs.sh
    :language: bash

.. note::

    Raspbian ships with two Linux kernels: one for the Raspberry Pi 1 (including Pi Zero), and another for the Raspberry
    Pi 2 and 3. In order to keep the ability of using one SD card on all Raspberry Pis the above script will include the
    other kernel's modules (the current kernel's modules are the only ones included by default). This will double the
    size of the ``initramfs.gz`` file. If you don't plan on using this SD card on a different Raspberry Pi you can set
    ``COMPATIBILITY`` to ``false`` and re-run ``mkinitramfs`` below.

Finally let's build the new initramfs and make sure our utilities have been installed. The ``mkinitramfs`` command may
print some WARNINGs from cryptsetup, but that should be fine since we're using ``CRYPTSETUP=y``. As long as cryptsetup
itself is present in the initramfs it won't be a problem.

.. code-block:: bash

    sudo chmod +x /etc/kernel/postinst.d/initramfs-rebuild
    sudo chmod +x /etc/initramfs-tools/hooks/resize2fs
    sudo -E CRYPTSETUP=y mkinitramfs -o /boot/initramfs.gz
    lsinitramfs /boot/initramfs.gz |grep -P "sbin/(cryptsetup|resize2fs|fdisk)"

Make sure you see ``sbin/resize2fs``, ``sbin/cryptsetup``, and ``sbin/fdisk`` in the output.

Prepare Boot Files
==================

Next step is to make some changes to some configuration files telling the Raspberry Pi to boot our soon-to-be-created
encrypted partition. We'll make these changes first since they're relatively easily reversible if you mount your SD card
on another computer, should you wish to abort this process. Edit these files with these changes:

.. describe:: /boot/config.txt

    Append ``initramfs initramfs.gz followkernel`` to the end of the file.

.. describe:: /boot/cmdline.txt

    1. Append ``cryptdevice=/dev/mmcblk0p2:sdcard`` to the end of the line.
    2. Replace ``root=/dev/mmcblk0p2`` with ``root=/dev/mapper/sdcard``

.. describe:: /etc/fstab

    Replace ``/dev/mmcblk0p2`` with ``/dev/mapper/sdcard``

.. describe:: /etc/crypttab

    Append ``sdcard  /dev/mmcblk0p2  none    luks`` to the end of the file.

Now run ``sudo reboot``. The Raspberry Pi will fail to boot and drop you into the initramfs shell.

Shrink and Encrypt
==================

To speed up this process we'll be shrinking the file system since all of this will be done on the Raspberry Pi. Long
running commands should take around 9 minutes each on a Raspberry Pi 3 with a clean Raspbian PIXEL OS and a fast SD
card.

.. note::

    When running ``resize2fs`` it will print out the new size of the file system. Keep track of the number of 4k blocks
    it tells you since you need to give that number to ``dd``. For reference my resize2fs said:

    .. code-block:: text

        The file system on /dev/mmcblk0p2 is now 1397823 (4k) blocks long.

    So "1397823" is my number of interest.

First we'll shrink and copy to the USB drive. **Insert your USB drive** and run these commands.

.. code-block:: bash

    e2fsck -f /dev/mmcblk0p2  # Check SD card for errors for safety.
    resize2fs -fM /dev/mmcblk0p2  # Shrink the file system on the SD card.
    # Write down the number of 4k blocks long in the resize2fs output.
    # Substitute "1397823" below with your number of interest.
    dd bs=4k count=1397823 if=/dev/mmcblk0p2 |sha1sum # Write down the SHA1.
    fdisk -l /dev/sda  # Make sure /dev/sda is your USB drive. If not check dmesg.
    dd bs=4k count=1397823 if=/dev/mmcblk0p2 of=/dev/sda  # Copy data to USB drive.
    dd bs=4k count=1397823 if=/dev/sda |sha1sum # Make sure it's the same value!

Now it's time to wipe your SD card's main partition and create an empty encrypted one in its place. The first
``cryptsetup`` command will prompt you for the password you want to use for your encrypted partition. Make sure it's a
strong one.

.. note::

    While copying data back to the SD card I got a bunch of these messages:

    .. code-block:: text

        [ 2280.148837] INFO: task kworker/u8:5:357 blocked for more than 120 seconds.
                             Not tainted 4.4.38-v7+ #938

    I ignored these since the ``sha1sum`` command I ran afterward assured me the data was copied over correctly.

.. code-block:: bash

    cryptsetup --cipher aes-cbc-essiv:sha256 luksFormat /dev/mmcblk0p2
    cryptsetup luksOpen /dev/mmcblk0p2 sdcard  # Mounts the encrypted file system.
    dd bs=4k count=1397823 if=/dev/sda of=/dev/mapper/sdcard # Copy back your data.
    dd bs=4k count=1397823 if=/dev/mapper/sdcard |sha1sum # Make sure it's the same!
    e2fsck -f /dev/mapper/sdcard  # Check encrypted SD card for errors.
    resize2fs -f /dev/mapper/sdcard  # Expand back to full size.
    # Remove USB drive, no longer needed.
    exit  # Continue to boot into your encrypted SD card.

Your Raspberry Pi should successfully boot into your desktop or command line (depending if you use Raspbian Lite or
PIXEL). Test everything out by rebooting. You'll need to run ``cryptsetup luksOpen /dev/mmcblk0p2 sdcard`` on every boot
from now on.

Pretty Password Prompt
======================

Everything should work fine now, except for the fact that every time the Raspberry Pi boots it drops you into the
initramfs shell and you need to remember to type in the luksOpen command since there is no bash history. It would be
nice to just have to enter your password.

It's actually really easy! The only drawback is that you'll need to disable the pretty PIXEL splash screen (if you're
not using the Raspbian Lite image) in order to see the prompt. If you're on the PIXEL image go ahead and disable the
splash screen:

.. describe:: /boot/cmdline.txt

    If you're on the PIXEL image edit this file and remove ``splash`` from the line.

Now build a new initramfs. This time there should be no WARNINGs at all. Again make sure our three programs are present
in our new initramfs:

.. code-block:: bash

    sudo mkinitramfs -o /tmp/initramfs.gz
    lsinitramfs /tmp/initramfs.gz |grep -P "sbin/(cryptsetup|resize2fs|fdisk)"
    sudo cp /tmp/initramfs.gz /boot/initramfs.gz
    sudo reboot

And that's it. It should prompt you with something like "Please unlock disk /dev/mmcblk0p2 (sdcard)". If you're running
Raspbian Lite the password prompt may be lost with other start-up messages. Just press the Enter key once it calms down
and you should see the prompt again.

References
==========

* http://paxswill.com/blog/2013/11/04/encrypted-raspberry-pi/
* https://github.com/NicoHood/NicoHood.github.io/wiki/Raspberry-Pi-Encrypt-Root-Partition-Tutorial

Comments
========

.. disqus::


text:
.. title:: rst2html5slides demo
.. meta::
    :generator: rst2html5slides 1.0 https://bitbucket.org/andre_felipe_dias/rst2html5slides
    :author: André Felipe Dias

:data-x: 0
:data-y: 0
:class: slide

The problem
===========

Making presentations is *boring*!
---------------------------------

:data-x: 1600
:data-y: 0
:class: slide

GUI tools are inflexible
========================

* It's hard to reorganize or import text
* Slow and memory hungry
* You get caught up in design early in the process

.. Here you have a view of the current slide, a preview of the next slide
   and your notes.

Use reStructuredText!
=====================

* You can use your favorite text-editor!
* Many tools available: Landslide, S5
* Convenient (and powerful!)

.. You also have a clock and a timer, so you know how much time you have left.

But then there was Prezi
========================

Sliding from left to right is no longer enough.
You need to be able to...

.. If you click on the timer it restarts from zero. This is handy when you
   are rehearsing the presentation and need to make sure it fits in the time
   allocated.

pan...
=========

.. If you have more notes than fit in the console, you can scroll down, but
   more handily, you can scroll the text up by pressing space bar.

rotate...
=========

.. If there isn't more text to scroll up, space bar will go to the next
   slide. Therefore you, as a presenter, just press space every time you run
   out of things to say!

:data-x: 4800
:data-y: 2500
:data-scale: 0.1
:data-rotate-z: 90

and zoom!
=========

.. Zooming is cool. But one day it will grow old as well. What will we do
   then to make presentations interesting?

:data-x: 4000
:data-y: 2500
:data-rotate-z: 90
:data-scale: 1

But Prezi is a GUI
==================

So we are back to square one.
(And it is closed source to boot)

.. It's probably back to making bad jokes again.

:data-x: 3200
:data-y: 2500
:data-scale: 1
:data-rotate-z: 90

What about impress.js?
======================

It's open source!

Supports pan, tilt and zoom!

:data-y: 3700
:data-rotate-x: 180
:data-x: 3200
:data-scale: 1
:data-rotate-z: 90

In three dimensions!
====================

*But...*

.. Wow! 3D! You didn't see that one coming, did you?

:data-x:3200
:data-y:4900
:data-scale:1
:data-rotate-z:90
:data-rotate-x:180

It's HTML...
============

Not a friendly format to edit

:data-x: 4000
:data-y: 4900
:data-scale: 1
:data-rotate-z: 90
:data-rotate-x: 180

\...and manual positioning
==========================

So inserting a slide means

repositioning all the following slides!

.. The endless repositioning of slides is what prompted me to write
   Hovercraft! in the first place.

:data-x: 4000
:data-y: 3700
:data-scale: 1
:data-rotate-z: 90
:data-rotate-x: 180

*Is there no solution?*
=======================

Of course there is!

.. What would be the point of this slide show if I didn't have a solution? Duh!

:data-rotate-y:180
:data-scale:3
:data-x:1500
:data-y:3700
:data-rotate-z:90
:data-rotate-x:180

Introducing **rst2html5slides**!
================================

:data-x:-1500
:data-scale:1
:data-y:3700
:data-rotate-z:90
:data-rotate-x:180
:data-rotate-y:180

reStructuredText

*plus*
impress.js *plus* impressConsole.js *plus* positioning!

:data-y:2500
:data-x:-1500
:data-scale:1
:data-rotate-z:90
:data-rotate-x:180
:data-rotate-y:180

Position slides
===============

* Automatically!
* Absolutely!
* Relative to the previous slide!
* Along an SVG path!

.. That SVG path support was a lot of work. And all I used it for was to
   position the slides in circles.

:data-x:-1500
:data-y:1300
:data-scale:1
:data-rotate-z:90
:data-rotate-x:180
:data-rotate-y:180

Presenter console!
==================

* A view of the current slide
* A view of the next slide
* Your notes
* A clock
* A timer

.. You found the presenter console already!

:data-x:-1500
:data-y:100
:data-scale:1
:data-rotate-z:90
:data-rotate-x:180
:data-rotate-y:180

**rst2html5slides**!
====================

.. image:: images/hovercraft_logo.png

The merge of convenience and cool!

.. A slogan: The ad-mans best friend!

:data-x:0
:data-y:2500
:data-z:4000
:data-rotate-x:90
:data-scale:1
:data-rotate-z:90
:data-rotate-y:180

**rst2html5slides!**
====================

On BitBucket:
https://bitbucket.org/andre_felipe_dias/rst2html5slides

.. Fork and contribute!


text:
import App from './app';
/**
 * Creates an Everflow Translator object. Adds the ability to translate langauges using keys
 * @class
 */
export default class Translator {
    /**
     * Returns a Language pack by key
     * @function loadData
     * @param {string} key - string name of language pack loaded by Language util class
     * @private
     * @static
     */
    private static loadData;
    /**
     * Returns an array of keys
     * @function listKey
     * @param {string} key - a string with dot keys (packageName.message)
     * @private
     * @static
     */
    private static listKey;
    /**
     * Translates using parsed dot.key from HTML code
     * @function convertProperty
     * @param {HTMLElement} element - HTMLElement
     * @param {string} property - property to convert
     * @private
     * @static
     */
    private static convertProperty;
    /**
     * Translate using a dot.key to access different language text
     * @function trans
     * @param {string} key - a string with dot keys (packageName.message)
     * @static
     */
    static trans(everflowApp: App, dotKey?: string): string;
    /**
     * Translate an entire page, if trans('dot.key') exists, it will load the language text
     * @function convertPage
     * @static
     */
    static convertPage(): void;
}


text:
package com.baidubce.services.tsdb.model;

import java.math.BigDecimal;
import java.util.Date;

import com.baidubce.model.AbstractBceResponse;
import com.baidubce.services.tsdb.TsdbConstants;
import com.fasterxml.jackson.annotation.JsonFormat;

/**
 * Represent the response for creating database.
 */
public class CreateDatabaseResponse extends AbstractBceResponse {

    private String databaseId;
    private BigDecimal charge;
    private String orderId;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = TsdbConstants.DATETIME_FORMAT, timezone = "UTC")
    private Date expiredTime;

    public String getDatabaseId() {
        return databaseId;
    }

    public void setDatabaseId(String databaseId) {
        this.databaseId = databaseId;
    }

    public BigDecimal getCharge() {
        return charge;
    }

    public void setCharge(BigDecimal charge) {
        this.charge = charge;
    }

    public Date getExpiredTime() {
        return expiredTime;
    }

    public void setExpiredTime(Date expiredTime) {
        this.expiredTime = expiredTime;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
}


text:
package schema

import (
	"time"
)

// Group models users groups and access permissions to user data.
type Group struct {
	ID          string    `gorethink:"id,omitempty"`
	Owner       string    `gorethink:"owner"`
	Name        string    `gorethink:"name"`
	Description string    `gorethink:"description"`
	Birthtime   time.Time `gorethink:"birthtime"`
	MTime       time.Time `gorethink:"mtime"`
	Access      string    `gorethink:"access"`
	Users       []string  `gorethink:"users"`
}

// NewGroup creates a new UserGroup instance.
func NewGroup(owner, name string) Group {
	now := time.Now()
	return Group{
		Owner:       owner,
		Name:        name,
		Description: name,
		Access:      "private",
		Birthtime:   now,
		MTime:       now,
	}
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_stream_socket::close (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../close.html" title="basic_stream_socket::close">
<link rel="prev" href="overload1.html" title="basic_stream_socket::close (1 of 2 overloads)">
<link rel="next" href="../connect.html" title="basic_stream_socket::connect">

Home
Libraries
People
FAQ
More

basic_stream_socket::close
          (2 of 2 overloads)

            Inherited from basic_socket.

            Close the socket.

boost::system::error_code close(
    boost::system::error_code & ec);

            This function is used to close the socket. Any asynchronous send, receive
            or connect operations will be cancelled immediately, and will complete
            with the boost::asio::error::operation_aborted error.

            Parameters

ec

                  Set to indicate what error occurred, if any. Note that, even if
                  the function indicates an error, the underlying descriptor is closed.

            Example

boost::asio::ip::tcp::socket socket(io_service);
...
boost::system::error_code ec;
socket.close(ec);
if (ec)
{
  // An error occurred.
}

            Remarks

            For portable behaviour with respect to graceful closure of a connected
            socket, call shutdown() before closing the socket.

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
_.extend(Spree.translations, {
  please_choose_language: "<%= Spree.t(:'i18n.choose_language') %>"
});

$(function () {
  $('#available_locales_').select2({
    placeholder: Spree.translations['please_choose_language']
  });
});


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Windows8Template
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    //public sealed partial class StandardStyles : Page
    //{
    //    public StandardStyles()
    //    {
    //        this.InitializeComponent();
    //    }
    //}
}