text:
"""
geojsonmerge
Merges multiple GeoJSON files into one.
Copyright 2014 Michael Farrell <http://micolous.id.au>

License: 3-clause BSD, see COPYING
"""

import geojson, argparse, glob, itertools

class GlobbingFileType(argparse.FileType):
	"""
	Emulate behaviour of UNIX shells on Win32 to allow wildcarded arguments to be passed (glob-expansion).

	This only works with files opened for reading, and globs will be ignored for files not opened for reading.

	This will have the side-effect of not allowing filenames to be passed that contain an asterisk (``*``).

	This means that every ``file`` object returned is in a list, even if there is only one entry.  As a result, some cleanup of the options returned may be required to "flatten" this list::

		options = parser.parse_args()
		input_files = list(itertools.chain.from_iterable(options.inputs))
	"""
	def __call__(self, string):
		if string != '-' and '*' in string and 'r' in self._mode:
			# There is a glob in here, and we're reading the file
			# Expand!
			return [super(GlobbingFileType, self).__call__(fn) for fn in glob.glob(string)]

		# Fall back to normal behaviour, but put it in a 1-item list
		return [super(GlobbingFileType, self).__call__(string)]

def mergeme(inputs, output, no_dupe_handling, id_field, id_property):
	if no_dupe_handling:
		assert (not id_field) and (not id_property)
	else:
		assert (not id_field) or (not id_property)
		assert not (id_field and id_property)

	known_ids = set()
	crs = None
	output_layer = geojson.FeatureCollection([])

	# Flatten the list of inputs
	inputs = list(itertools.chain.from_iterable(inputs))

	for i, layer_f in enumerate(inputs):
		print "Processing input file #%d..." % i
		layer = geojson.load(layer_f)
		# FIXME: this requires the CRS be specified on a "layer" level.  GeoJSON allows this to be ommitted, and this should include a check to ensure it is ommitted for all in this case.

		# Some broken GeoJSON files do weird things...
		if isinstance(layer.crs, list):
			layer.crs = layer.crs[0]
		if isinstance(layer.crs.properties, list):
			newprops = {}
			for x in range(len(layer.crs.properties)/2):
				newprops[layer.crs.properties[x*2]] = layer.crs.properties[(x*2) + 1]
			layer.crs.properties = newprops

		# We don't care about per-geometry CRS, these can mingle
		if i == 0:
			# first file sets the CRS!
			crs = layer.crs.properties['name']
			output_layer.crs = layer.crs
		else:
			assert layer.crs.properties['name'] == crs, ('CRS of files must match.  File has CRS %r, expected %r' % (layer.crs.properties['name'], crs))

		# We have a matching CRS, start merging geometries.
		for geometry in layer.features:
			if not no_dupe_handling:
				if id_property and geometry.properties[id_property] in known_ids:
					# Geometry is already present, skip
					continue
				elif id_field and geometry.id in known_ids:
					# Geometry is already present, skip
					continue

			# Geometry is new, add to list
			output_layer.features.append(geometry)
			if id_property:
				known_ids.add(geometry.properties[id_property])
			elif id_field:
				known_ids.add(geometry.id)

		print "OK! (%d total geometries written, %d read from this file)" % (len(output_layer.features), len(layer.features))

	# all files complete
	geojson.dump(output_layer, output)
	print "Files merged!"

def main():
	parser = argparse.ArgumentParser()

	parser.add_argument('inputs', nargs='+',
		type=GlobbingFileType('rb'),
		help='Input GeoJSON file(s) to merge'
	)

	parser.add_argument('-o', '--output',
		required=True,
		type=argparse.FileType('wb'),
		help='Output GeoJSON file'
	)

	group = parser.add_mutually_exclusive_group()

	group.add_argument('-n', '--no-dupe-handling',
		action='store_true',
		help='Do not attempt to handle duplicate geometries specially.'
	)

	group.add_argument('-i', '--id-field',
		action='store_true',
		help='Match duplicate geometries by their id field.'
	)

	group.add_argument('-p', '--id-property',
		help='Field to use when merging features in order to drop duplicate geometries.'
	)

	options = parser.parse_args()

	mergeme(options.inputs, options.output, options.no_dupe_handling, options.id_field, options.id_property)

if __name__ == '__main__':
	main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using LinqToTwitter.Security;
using LinqToTwitter.Net;
using System.Text;

namespace LinqToTwitter
{
    public class AuthorizerBase
    {
        /// <summary>
        /// URL for OAuth Request Tokens
        /// </summary>
        public string OAuthRequestTokenUrl { get; set; }

        /// <summary>
        /// URL for OAuth authorization
        /// </summary>
        public string OAuthAuthorizeUrl { get; set; }

        /// <summary>
        /// URL for OAuth Access Tokens
        /// </summary>
        public string OAuthAccessTokenUrl { get; set; }

        /// <summary>
        /// Get/Set Credentials
        /// </summary>
        public ICredentialStore CredentialStore { get; set; }

        /// <summary>
        /// Force the user to enter their name/password when authorizing
        /// </summary>
        public bool ForceLogin { get; set; }

        /// <summary>
        /// Overrides read/write settings for application registered with Twitter
        /// </summary>
        public AuthAccessType AccessType { get; set; }

        /// <summary>
        /// Optional name to prefill when user visits the Twitter authorization screen
        /// </summary>
        public string PreFillScreenName { get; set; }

        /// <summary>
        /// User-Agent header string sent to Twitter to represent your application. Defaults to LINQ to Twitter.
        /// </summary>
        public string UserAgent { get; set; }

        /// <summary>
        /// Url that Twitter redirects to after user authorizes your app.
        /// </summary>
        public string Callback { get; set; }

        public IWebProxy Proxy { get; set; }

        public bool SupportsCompression { get; set; }

        protected string ParseVerifierFromResponseUrl(string responseUrl)
        {
            string[] keyValPairs = new Uri(responseUrl).Query.TrimStart('?').Split('&');

            string verifier =
                (from keyValPair in keyValPairs
                 let pair = keyValPair.Split('=')
                 let key = pair[0]
                 let val = pair.Length == 2 ? pair[1] : string.Empty
                 where key == "oauth_verifier"
                 select val)
                .SingleOrDefault();

            return verifier;
        }

        IDictionary<string, string> parameters;
        public IDictionary<string, string> Parameters
        {
            get
            {
                if (parameters == null)
                {
                    parameters = new Dictionary<string, string>();
                    parameters.Add("oauth_consumer_key", CredentialStore.ConsumerKey);
                    parameters.Add("oauth_token", CredentialStore.OAuthToken);
                }

                return parameters;
            }
        }

        public AuthorizerBase() : this(false, AuthAccessType.NoChange, string.Empty) { }

        public AuthorizerBase(bool forceLogin, AuthAccessType accessType, string prefillScreenName)
        {
            ForceLogin = forceLogin;
            AccessType = accessType;
            PreFillScreenName = prefillScreenName;
            SupportsCompression = true;

            if (string.IsNullOrWhiteSpace(UserAgent))
                UserAgent = TwitterContext.DefaultUserAgent;

            OAuthRequestTokenUrl = "https://api.twitter.com/oauth/request_token";
            OAuthAuthorizeUrl = "https://api.twitter.com/oauth/authorize";
            OAuthAccessTokenUrl = "https://api.twitter.com/oauth/access_token";
        }

        public async Task GetRequestTokenAsync(string callback)
        {
            if (string.IsNullOrWhiteSpace(callback))
                throw new ArgumentNullException("callback", "callback is required.");

            Parameters.Add("oauth_callback", EncodeToProtectMultiByteCharUrls(callback));
            Parameters.Remove("oauth_token");

            if (AccessType != AuthAccessType.NoChange)
                Parameters.Add("x_auth_access_type", AccessType.ToString().ToLower());

            string response = await HttpGetAsync(OAuthRequestTokenUrl, Parameters);

            if (string.IsNullOrWhiteSpace(response))
                throw new ArgumentNullException("Empty response to request token response from Twitter.");

            UpdateCredentialsFromRequestTokenResponse(response);
        }

        string EncodeToProtectMultiByteCharUrls(string callback)
        {
            return callback == "oob" ? "oob" : new Uri(callback).AbsoluteUri;
        }

        public string PrepareAuthorizeUrl(bool forceLogin)
        {
            if (CredentialStore.OAuthToken == null)
                throw new InvalidOperationException("OAuthToken not set. Call GetRequestTokenAsync first and verify that OAuthToken is set.");

            string forceLoginParamString = forceLogin ? "&force_login=true" : "";

            string preFillScreenNameParamString =
                !string.IsNullOrWhiteSpace(PreFillScreenName) ? "&screen_name=" + PreFillScreenName : "";

            return string.Format(
                "{0}?oauth_token={1}{2}{3}",
                OAuthAuthorizeUrl, CredentialStore.OAuthToken,
                forceLoginParamString, preFillScreenNameParamString);
        }

        public async Task GetAccessTokenAsync(IDictionary<string, string> accessTokenParams)
        {
            if (!accessTokenParams.ContainsKey("oauth_verifier"))
                throw new ArgumentException("oauth_verifier is required.");

            foreach (var key in accessTokenParams.Keys)
                Parameters.Add(key, accessTokenParams[key]);

            Parameters.Remove("oauth_callback");

            string response = await HttpGetAsync(OAuthAccessTokenUrl, Parameters).ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(response))
                throw new ArgumentNullException("Empty response to access token response from Twitter.");

            UpdateCredentialsWithAccessTokenResponse(response);
        }

        public async Task PostAccessTokenAsync(IDictionary<string, string> accessTokenParams)
        {
            if (!accessTokenParams.ContainsKey("x_auth_mode") && !accessTokenParams.ContainsKey("oauth_verifier"))
                throw new ArgumentException("oauth_verifier is required, unless using xAuth.");

            foreach (var key in accessTokenParams.Keys)
                Parameters.Add(key, accessTokenParams[key]);

            Parameters.Remove("oauth_callback");

            string response = await HttpPostAsync(OAuthAccessTokenUrl, Parameters).ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(response))
                throw new ArgumentNullException("Empty response to access token response from Twitter.");

            UpdateCredentialsWithAccessTokenResponse(response);
        }

        void UpdateCredentialsFromRequestTokenResponse(string response)
        {
            CredentialStore.OAuthToken =
                (from nameValPair in response.Split('&')
                 let pair = nameValPair.Split('=')
                 where pair[0] == "oauth_token"
                 select pair[1])
                .SingleOrDefault();

            Parameters.Add("oauth_token", CredentialStore.OAuthToken);
        }

        void UpdateCredentialsWithAccessTokenResponse(string response)
        {
            var responseParams =
                (from nameValPair in response.Split('&')
                 let pair = nameValPair.Split('=')
                 select new
                 {
                     Key = pair[0],
                     Value = pair[1]
                 })
                .ToDictionary(
                    pair => pair.Key,
                    pair => pair.Value);

            if (responseParams["oauth_token"] != null)
                CredentialStore.OAuthToken = responseParams["oauth_token"];

            if (responseParams["oauth_token_secret"] != null)
                CredentialStore.OAuthTokenSecret = responseParams["oauth_token_secret"];

            if (responseParams["screen_name"] != null)
                CredentialStore.ScreenName = responseParams["screen_name"];

            if (responseParams["user_id"] != null)
            {
                ulong userID = 0;
                ulong.TryParse(responseParams["user_id"], out userID);
                CredentialStore.UserID = userID;
            }
        }

        internal async Task<string> HttpGetAsync(string oauthUrl, IDictionary<string, string> parameters)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, oauthUrl);
            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Get, oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            if (Proxy != null && handler.SupportsProxy)
                handler.Proxy = Proxy;

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return await msg.Content.ReadAsStringAsync().ConfigureAwait(false);
        }

        internal async Task<string> HttpPostAsync(string oauthUrl, IDictionary<string, string> parameters)
        {
            var postData =
                (from keyValPair in parameters
                 where !keyValPair.Key.StartsWith("oauth")
                 select keyValPair)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

            var req = new HttpRequestMessage(HttpMethod.Post, oauthUrl);
            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Post, oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var paramString =
                string.Join("&",
                    (from parm in postData
                     select parm.Key + "=" + Url.PercentEncode(parm.Value))
                    .ToList());
            var content = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded");
            req.Content = content;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            if (Proxy != null && handler.SupportsProxy)
                handler.Proxy = Proxy;

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return await msg.Content.ReadAsStringAsync().ConfigureAwait(false);
        }

        public virtual string GetAuthorizationString(HttpMethod method, string oauthUrl, IDictionary<string, string> parameters)
        {
            string consumerSecret = CredentialStore.ConsumerSecret ?? "";
            string oAuthTokenSecret = CredentialStore.OAuthTokenSecret ?? "";
            string authorizationString =
                new OAuth().GetAuthorizationString(
                    method.ToString(), oauthUrl, parameters, consumerSecret, oAuthTokenSecret);
            return authorizationString;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>angle_to_direction — MetPy 0.12</title>

    <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>

    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.angle_to_direction.html"/>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/theme_override.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/gallery-binder.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/gallery-dataframe.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="MetPy 0.12" href="../../index.html"/>
        <link rel="up" title="calc" href="metpy.calc.html"/>
        <link rel="next" title="find_bounding_indices" href="metpy.calc.find_bounding_indices.html"/>
        <link rel="prev" title="pressure_to_height_std" href="metpy.calc.pressure_to_height_std.html"/>

             MetPy

                    <select class="version-list" id="version-list">
                      <option value=''>0.12</option>

                          <option value="../latest">latest</option>

                          <option value="../dev">dev</option>

                    </select>

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Installation Guide

Getting Started with MetPy

Unit Support

Examples

Python Gallery (separate site)

Tutorials

Reference Guide

constants

units

io

calc

Dry Thermodynamics

Moist Thermodynamics

Soundings

Dynamic/Kinematic

Boundary Layer/Turbulence

Mathematical Functions

Apparent Temperature

Standard Atmosphere

Other

angle_to_direction

find_bounding_indices

find_intersections

get_layer

get_layer_heights

get_perturbation

isentropic_interpolation

nearest_intersection_idx

parse_angle

reduce_point_density

resample_nn_1d

smooth_gaussian

smooth_n_point

Deprecated

plots

ctables

interpolate

xarray

MetPy Roadmap

GEMPAK Conversion Guide

Support

Contributors Guide

Infrastructure Guide

Citing MetPy

References

          MetPy

Docs »

Reference Guide »

calc »

angle_to_direction

                 Improve this page

angle_to_direction¶

metpy.calc.angle_to_direction(input_angle, full=False, level=3)[source]¶

Convert the meteorological angle to directional text.

Works for angles greater than or equal to 360 (360 -> N | 405 -> NE)
and rounds to the nearest angle (355 -> N | 404 -> NNE)

Parameters

input_angle (numeric or array-like numeric) – Angles such as 0, 25, 45, 360, 410, etc

full (boolean) – True returns full text (South), False returns abbrieviated text (S)

level (int) – Level of detail (3 = N/NNE/NE/ENE/E… 2 = N/NE/E/SE… 1 = N/E/S/W)

Returns

direction – The directional text

Examples using metpy.calc.angle_to_direction¶

Angle to Direction¶

        Next

         Previous

        © Copyright 2019, MetPy Developers. Development supported by National Science Foundation grants AGS-1344155, OAC-1740315, and AGS-1901712..
      Last updated on Aug 06, 2020 at 20:22:57.

  Built with Sphinx using a theme provided by Read the Docs.


text:
.. _userguide_plotting:

Plotting with Basic Glyphs
==========================

.. _userguide_plotting_figures:

Creating Figures
----------------

Note that Bokeh plots created using the |bokeh.plotting| interface come with
a default set of tools, and default visual styles. See :ref:`userguide_styling`
for information about how to customize the visual style of plots, and
:ref:`userguide_tools` for information about changing or specifying tools.

.. _userguide_plotting_scatter_markers:

Scatter Markers
~~~~~~~~~~~~~~~

To scatter circle markers on a plot, use the |circle| method of |Figure|:

.. bokeh-plot:: docs/user_guide/examples/plotting_scatter_circle.py
    :source-position: above

Similarly, to scatter square markers, use the |square| method of |Figure|:

.. bokeh-plot:: docs/user_guide/examples/plotting_scatter_square.py
    :source-position: above

There are lots of marker types available in Bokeh, you can see details and
example plots for all of them by clicking on entries in the list below:

.. hlist::
    :columns: 3

    * |asterisk|
    * |circle|
    * |circle_cross|
    * |circle_x|
    * |cross|
    * |diamond|
    * |diamond_cross|
    * |inverted_triangle|
    * |square|
    * |square_cross|
    * |square_x|
    * |triangle|
    * |x|

All the markers have the same set of properties: ``x``, ``y``, ``size`` (in
:ref:`screen units <userguide_styling_units>`), and ``angle`` (radians by
default). Additionally, |circle| has a ``radius`` property that can be used to
specify :ref:`data-space units <userguide_styling_units>`.

.. _userguide_plotting_line_glyphs:

Line Glyphs
~~~~~~~~~~~

Single Lines
''''''''''''

Below is an example that shows how to generate a single line glyph from
one dimensional sequences of *x* and *y* points using the |line| glyph
method:

.. bokeh-plot:: docs/user_guide/examples/plotting_line_single.py
    :source-position: above

Multiple Lines
''''''''''''''

Sometimes it is useful to plot multiple lines all at once. This can be
accomplished with the |multi_line| glyph method:

.. bokeh-plot:: docs/user_guide/examples/plotting_line_multiple.py
    :source-position: above

.. note::
    This glyph is unlike most other glyphs. Instead of accepting a one
    dimensional list or array of scalar values, it accepts a "list of lists".

Missing Points
''''''''''''''

``NaN`` values can be passed to |line| and |multi_line| glyphs. In this case,
you end up with single logical line objects, that have multiple disjoint
components when rendered:

.. bokeh-plot:: docs/user_guide/examples/plotting_line_missing_points.py
    :source-position: above

.. _userguide_plotting_bars_rects:

Bars and Rectangles
~~~~~~~~~~~~~~~~~~~

Rectangles
''''''''''

To draw *axis aligned* rectangles ("quads") by specifying the ``left``,
``right``, ``top``, and ``bottom`` positions, use the |quad| glyph function:

.. bokeh-plot:: docs/user_guide/examples/plotting_rectangles.py
    :source-position: above

To draw arbitrary rectangles by specifying a center point, width, height,
and angle, use the |rect| glyph function:

.. bokeh-plot:: docs/user_guide/examples/plotting_rectangles_rotated.py
    :source-position: above

Bars
''''

When drawing rectangular bars (often representing intervals) it is often
more convenient to have coordinates that are a hybrid of the two systems
above. Bokeh provides the |hbar| and |vbar| glyphs function for this
purpose.

To draw vertical bars by specifying a (center) x-coordinate, width, and
top and bottom endpoints, use the |vbar| glyph function:

.. bokeh-plot:: docs/user_guide/examples/plotting_vbar.py
    :source-position: above

To draw horizontal bars by specifying a (center) y-coordinate, height,
and left and right endpoints, use the |hbar| glyph function:

.. bokeh-plot:: docs/user_guide/examples/plotting_hbar.py
    :source-position: above

.. _userguide_plotting_patch_glyphs:

Patch Glyphs
~~~~~~~~~~~~

Single Patches
''''''''''''''

Below is an example that shows how to generate a single polygonal patch
glyph from one dimensional sequences of *x* and *y* points using the
|patch| glyph method:

.. bokeh-plot:: docs/user_guide/examples/plotting_patch_single.py
    :source-position: above

Multiple Patches
''''''''''''''''

Sometimes it is useful to plot multiple lines all at once. This can be
accomplished with the |patches| glyph method:

.. bokeh-plot:: docs/user_guide/examples/plotting_patch_multiple.py
    :source-position: above

.. note::
    This glyph is unlike most other glyphs. Instead of accepting a one
    dimensional list or array of scalar values, it accepts a "list of lists".

Missing Points
''''''''''''''

Just as with |line| and |multi_line|, ``NaN`` values can be passed to
|patch| and |patches| glyphs. In this case, you end up with single logical
patch objects, that have multiple disjoint components when rendered:

.. bokeh-plot:: docs/user_guide/examples/plotting_patch_missing_points.py
    :source-position: above

.. warning::
    Hit testing on patch objects with ``NaN`` values is not currently
    supported.

.. _userguide_plotting_ovals_ellipses:

Ovals and Ellipses
~~~~~~~~~~~~~~~~~~

The |oval| glyph method accepts the same properties as |rect|, but renders
oval shapes:

.. bokeh-plot:: docs/user_guide/examples/plotting_ovals.py
    :source-position: above

The |ellipse| glyph accepts the same properties as |oval| and |rect| but
renders ellipse shapes, which are different from oval ones. In particular,
the same value for width and height will render a circle using the |ellipse|
glyph but not the |oval| one:

.. bokeh-plot:: docs/user_guide/examples/plotting_ellipses.py
    :source-position: above

.. _userguide_plotting_images:

Images
~~~~~~

You can display images on Bokeh plots using the |image|, |image_rgba|, and
|image_url| glyph methods.

The first example here shows how to display images in Bokeh plots from
raw RGBA data using |image_rgba|:

.. note::
    This example depends on the open source NumPy library in order to more
    easily generate an array of RGBA data.

.. bokeh-plot:: docs/user_guide/examples/plotting_image.py
    :source-position: above

.. _userguide_plotting_segments_rays:

Segments and Rays
~~~~~~~~~~~~~~~~~

Sometimes it is useful to be able to draw many individual line segments at
once. Bokeh provides the |segment| and |ray| glyph methods to render these.

The |segment| function accepts start points ``x0``, ``y0`` and end points
``x1`` and ``y1`` and renders segments between these:

.. bokeh-plot:: docs/user_guide/examples/plotting_segments.py
    :source-position: above

The |ray| function accepts start points ``x``, ``y`` with a ``length``
(in :ref:`screen units <userguide_styling_units>`) and an ``angle``. The default
``angle_units`` are ``"rad"`` but can also be changed to ``"deg"``. To have an
"infinite" ray, that always extends to the edge of the plot, specify ``0`` for
the length:

.. bokeh-plot:: docs/user_guide/examples/plotting_ray.py
    :source-position: above

.. _userguide_plotting_wedges_arcs:

Wedges and Arcs
~~~~~~~~~~~~~~~

To draw a simple line arc, Bokeh provides the |arc| glyph method, which
accepts ``radius``, ``start_angle``, and ``end_angle`` to determine position.
Additionally, the ``direction`` property determines whether to render
clockwise (``"clock"``) or anti-clockwise (``"anticlock"``) between the start
and end angles.

.. bokeh-plot:: docs/user_guide/examples/plotting_arcs.py
    :source-position: above

The |wedge| glyph method accepts the same properties as |arc|, but renders a
filled wedge instead:

.. bokeh-plot:: docs/user_guide/examples/plotting_wedge.py
    :source-position: above

The |annular_wedge| glyph method is similar to |arc|, but draws a filled area.
It accepts a ``inner_radius`` and ``outer_radius`` instead of just ``radius``:

.. bokeh-plot:: docs/user_guide/examples/plotting_annular_wedge.py
    :source-position: above

Finally, the |annulus| glyph methods, which accepts ``inner_radius`` and
``outer_radius``, can be used to draw filled rings:

.. bokeh-plot:: docs/user_guide/examples/plotting_annulus.py
    :source-position: above

.. _userguide_plotting_quadratic_cubic_curves:

Specialized Curves
~~~~~~~~~~~~~~~~~~

Bokeh also provides |quadratic| and |bezier| glyph methods for drawing
parameterized quadratic and cubic curves. These are somewhat uncommon;
please refer to the :ref:`reference documentation <bokeh.plotting>` for details.

.. _userguide_plotting_multiple_glyphs:

Combining Multiple Glyphs
-------------------------

Combining multiple glyphs on a single plot is a matter of calling more than
one glyph method on a single |Figure|:

.. bokeh-plot:: docs/user_guide/examples/plotting_multiple_glyphs.py
    :source-position: above

This principle holds in general for all the glyph methods in
|bokeh.plotting|. Any number of glyphs may be added to a Bokeh
plot.

.. _userguide_plotting_setting_ranges:

Setting Ranges
--------------

By default, Bokeh will attempt to automatically set the data bounds
of plots to fit snugly around the data. Sometimes you may need to
set a plot's range explicitly. This can be accomplished by setting the
``x_range`` or ``y_range`` properties using a ``Range1d`` object that
gives the *start* and *end* points of the range you want:

.. code-block:: python

    p.x_range = Range1d(0, 100)

As a convenience, the |figure| function can also accept tuples of
*(start, end)* as values for the ``x_range`` or ``y_range`` parameters.
Below is a an example that shows both methods of setting the range:

.. bokeh-plot:: docs/user_guide/examples/plotting_figure_range.py
    :source-position: above

Ranges can also accept a min and max property that allow you to specify the
edges of the plot that you do not want the user to be able to pan/zoom beyond.

.. _userguide_plotting_axis_types:

Specifying Axis Types
---------------------

All the examples above use the default linear axis. This axis is suitable
for many plots that need to show numerical data on a linear scale. In other
cases you may have categorical data, or need to display numerical data on
a datetime or log scale. This section shows how to specify the axis type
when using |bokeh.plotting| interface.

.. _userguide_plotting_categorical_axes:

Categorical Axes
~~~~~~~~~~~~~~~~

.. bokeh-plot:: docs/user_guide/examples/plotting_categorical_axis.py
    :source-position: above

.. _userguide_plotting_datetime_axes:

Datetime Axes
~~~~~~~~~~~~~

When dealing with timeseries data, or any data that involves dates or
times, it is desirable to have an axis that can display labels that
are appropriate to different date and time scales.

.. note::
    This example requires a network connection, and depends on the
    open source Pandas library in order to more easily present realistic
    timeseries data.

We have seen how to use the |figure| function to create plots using the
|bokeh.plotting| interface. This function accepts  ``x_axis_type`` and
``y_axis_type`` as arguments. To specify a datetime axis, pass ``"datetime"``
for the value of either of these parameters.

.. bokeh-plot:: docs/user_guide/examples/plotting_datetime_axis.py
    :source-position: above

.. note::
    Future versions of Bokeh will attempt to auto-detect situations when
    datetime axes are appropriate, and add them automatically by default.

.. _userguide_plotting_log_axes:

Log Scale Axes
~~~~~~~~~~~~~~

When dealing with data that grows exponentially or is of many orders of magnitude,
it is often necessary to have one axis on a log scale. Another scenario involves
plotting data that has a power law relationship, when it is desirable to use log
scales on both axes.

As we saw above, the |figure| function accepts ``x_axis_type`` and
``y_axis_type`` as arguments. To specify a log axis, pass ``"log"`` for
the value of either of these parameters.

By default, log axis ranges are calculated to fit around positive valued data. To
set your own ranges, see the section on :ref:`userguide_plotting_setting_ranges`.

.. bokeh-plot:: docs/user_guide/examples/plotting_log_scale_axis.py
    :source-position: above

.. _userguide_plotting_twin_axes:

Twin Axes
~~~~~~~~~

It is possible to add multiple axes representing different ranges to a single
plot. To do this, configure the plot with "extra" named ranges in the
``extra_x_range`` and ``extra_y_range`` properties. Then these named ranges
can be referred to when adding new glyph methods, and also to add new axes
objects using the ``add_layout`` method on |Plot|. An example is given
below:

.. bokeh-plot:: docs/user_guide/examples/plotting_twin_axes.py
    :source-position: above

.. _userguide_plotting_annotations:

Adding Annotations
------------------

The section on adding annotations to plots has moved.  Please see
:ref:`userguide_annotations`

.. |bokeh.plotting| replace:: :ref:`bokeh.plotting <bokeh.plotting>`
.. |Figure| replace:: :class:`~bokeh.plotting.figure.Figure`
.. |figure| replace:: :func:`~bokeh.plotting.figure`
.. |Plot| replace:: :class:`~bokeh.models.plots.Plot`

.. |annular_wedge|     replace:: :func:`~bokeh.plotting.figure.Figure.annular_wedge`
.. |annulus|           replace:: :func:`~bokeh.plotting.figure.Figure.annulus`
.. |arc|               replace:: :func:`~bokeh.plotting.figure.Figure.arc`
.. |asterisk|          replace:: :func:`~bokeh.plotting.figure.Figure.asterisk`
.. |bezier|            replace:: :func:`~bokeh.plotting.figure.Figure.bezier`
.. |circle|            replace:: :func:`~bokeh.plotting.figure.Figure.circle`
.. |circle_cross|      replace:: :func:`~bokeh.plotting.figure.Figure.circle_cross`
.. |circle_x|          replace:: :func:`~bokeh.plotting.figure.Figure.circle_x`
.. |cross|             replace:: :func:`~bokeh.plotting.figure.Figure.cross`
.. |diamond|           replace:: :func:`~bokeh.plotting.figure.Figure.diamond`
.. |diamond_cross|     replace:: :func:`~bokeh.plotting.figure.Figure.diamond_cross`
.. |ellipse|           replace:: :func:`~bokeh.plotting.figure.Figure.ellipse`
.. |hbar|              replace:: :func:`~bokeh.plotting.figure.Figure.hbar`
.. |inverted_triangle| replace:: :func:`~bokeh.plotting.figure.Figure.inverted_triangle`
.. |image|             replace:: :func:`~bokeh.plotting.figure.Figure.image`
.. |image_rgba|        replace:: :func:`~bokeh.plotting.figure.Figure.image_rgba`
.. |image_url|         replace:: :func:`~bokeh.plotting.figure.Figure.image_url`
.. |line|              replace:: :func:`~bokeh.plotting.figure.Figure.line`
.. |multi_line|        replace:: :func:`~bokeh.plotting.figure.Figure.multi_line`
.. |oval|              replace:: :func:`~bokeh.plotting.figure.Figure.oval`
.. |patch|             replace:: :func:`~bokeh.plotting.figure.Figure.patch`
.. |patches|           replace:: :func:`~bokeh.plotting.figure.Figure.patches`
.. |quad|              replace:: :func:`~bokeh.plotting.figure.Figure.quad`
.. |quadratic|         replace:: :func:`~bokeh.plotting.figure.Figure.quadratic`
.. |ray|               replace:: :func:`~bokeh.plotting.figure.Figure.ray`
.. |rect|              replace:: :func:`~bokeh.plotting.figure.Figure.rect`
.. |segment|           replace:: :func:`~bokeh.plotting.figure.Figure.segment`
.. |square|            replace:: :func:`~bokeh.plotting.figure.Figure.square`
.. |square_cross|      replace:: :func:`~bokeh.plotting.figure.Figure.square_cross`
.. |square_x|          replace:: :func:`~bokeh.plotting.figure.Figure.square_x`
.. |triangle|          replace:: :func:`~bokeh.plotting.figure.Figure.triangle`
.. |vbar|              replace:: :func:`~bokeh.plotting.figure.Figure.rect`
.. |wedge|             replace:: :func:`~bokeh.plotting.figure.Figure.wedge`
.. |x|                 replace:: :func:`~bokeh.plotting.figure.Figure.x`


text:
package io.github.andreybgm.gigreminder.screen.editartist.uievent;

import android.support.annotation.NonNull;

import io.github.andreybgm.gigreminder.screen.base.Result;
import io.github.andreybgm.gigreminder.screen.base.UiEvent;

public class DiscardEvent implements UiEvent, Result {
    @NonNull
    private final String name;
    private final boolean forceClose;

    public static DiscardEvent create(@NonNull String name, boolean forceClose) {
        return new DiscardEvent(name, forceClose);
    }

    private DiscardEvent(@NonNull String name, boolean forceClose) {
        this.name = name;
        this.forceClose = forceClose;
    }

    @NonNull
    public String getName() {
        return name;
    }

    public boolean isForceClose() {
        return forceClose;
    }
}


text:
#pragma once

#include <QtCore/QMap>

#include <qrtext/lua/ast/node.h>
#include <qrtext/core/types/typeExpression.h>

#include "generatorBase/lua/reservedFunctionsConverter.h"
#include "generatorBase/lua/precedenceConverterInterface.h"
#include "generatorBase/templateParametrizedEntity.h"
#include "generatorBase/simpleGenerators/binding.h"

namespace qrtext {
class LanguageToolboxInterface;
}

namespace generatorBase {
namespace lua {

class LuaPrinter : public qrtext::lua::LuaAstVisitorInterface
		, public TemplateParametrizedEntity
{
public:
	/// Takes ownership on converters.
	LuaPrinter(const QStringList &pathsToTemplates
			, const qrtext::LanguageToolboxInterface &textLanguage
			, PrecedenceConverterInterface &precedeceTable
			, const simple::Binding::ConverterInterface *reservedVariablesConverter);

	~LuaPrinter() override;

	/// Prints the given AST to the code using a set of templates placed in the given in the constructor directory.
	virtual QString print(const QSharedPointer<qrtext::lua::ast::Node> &node);

	/// Prints the given AST to the code on the target language and casts it to the given types.
	virtual QString castTo(const QSharedPointer<qrtext::core::types::TypeExpression> &type
			, const QSharedPointer<qrtext::lua::ast::Node> &node);

private:
	void visit(const QSharedPointer<qrtext::lua::ast::Number> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::UnaryMinus> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Not> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseNegation> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Length> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::LogicalAnd> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::LogicalOr> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Addition> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Subtraction> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Multiplication> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Division> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::IntegerDivision> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Modulo> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Exponentiation> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseAnd> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseOr> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseXor> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseLeftShift> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::BitwiseRightShift> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Concatenation> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Equality> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::LessThan> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::LessOrEqual> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Inequality> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::GreaterThan> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::GreaterOrEqual> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::IntegerNumber> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::FloatNumber> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::FieldInitialization> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::TableConstructor> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::String> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::True> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::False> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Nil> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Identifier> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::FunctionCall> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::MethodCall> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Assignment> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::Block> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;
	void visit(const QSharedPointer<qrtext::lua::ast::IndexingExpression> &node
			, const QSharedPointer<qrtext::core::ast::Node> &parent) override;

	/// Returns true if child expression must be wrapped into the brackets.
	/// The default implementation returns true if the parent operation has greater precedence or
	/// equal precedence and child is situated on the opposite side to operator`s associativity.
	/// May be redefined by printers to concrete language.
	virtual bool needBrackets(const QSharedPointer<qrtext::lua::ast::Node> &parent
			, const QSharedPointer<qrtext::lua::ast::Node> &child
			, qrtext::core::Associativity childAssociativity = qrtext::core::Associativity::right) const;

	void processUnary(const QSharedPointer<qrtext::core::ast::UnaryOperator> &node, const QString &templateFileName);
	void processBinary(const QSharedPointer<qrtext::core::ast::BinaryOperator> &node, const QString &templateFileName);
	void processTemplate(const QSharedPointer<qrtext::lua::ast::Node> &node, const QString &templateFileName
			, QMap<QString, QSharedPointer<qrtext::lua::ast::Node>> const &bindings);

	void pushResult(const QSharedPointer<qrtext::lua::ast::Node> &node, const QString &generatedCode);
	QString popResult(const QSharedPointer<qrtext::lua::ast::Node> &node, bool wrapIntoBrackets = false);
	QStringList popResults(const QList<QSharedPointer<qrtext::lua::ast::Node>> &nodes);

	bool printWithoutPop(const QSharedPointer<qrtext::lua::ast::Node> &node);
	QString to(const QSharedPointer<qrtext::core::types::TypeExpression> &type
			, const QSharedPointer<qrtext::lua::ast::Node> &node);
	QString toString(const QSharedPointer<qrtext::lua::ast::Node> &node);

	QStringList addSuffix(const QStringList &list);

	const qrtext::LanguageToolboxInterface &mTextLanguage;
	QMap<qrtext::lua::ast::Node *, QString> mGeneratedCode;
	PrecedenceConverterInterface &mPrecedenceTable;
	const simple::Binding::ConverterInterface *mReservedVariablesConverter; // Does not have ownership
	ReservedFunctionsConverter mReservedFunctionsConverter;
};

}
}


text:
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE CPP #-}

module Data.Comparaptor.Eq.Tests (tests) where

#define TEST(TYPE) testProperty "=.= TYPE" (testEq :: TYPE -> TYPE -> Bool)

import qualified Data.ByteString as StrictByteString

import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck (Arbitrary(..))

import Data.Comparaptor.Eq (SafeEq(..))

type StrictByteString = StrictByteString.ByteString

instance Arbitrary StrictByteString where
    arbitrary = fmap StrictByteString.pack arbitrary

testEq :: (SafeEq a, Eq a) => a -> a -> Bool
testEq a b = expected == res
  where
    expected = a == b
    res = a =.= b

tests :: Test
tests = testGroup "Data.Comparaptor.Eq.Tests"
    [ TEST(())
    , TEST(Bool)
    , TEST((Bool, Bool))
    , TEST((Bool, (), Bool))
    , TEST(StrictByteString)
    , TEST(Integer)
    ]


text:
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Route | session/index', function (hooks) {
  setupTest(hooks);

  test('it exists', function (assert) {
    const route = this.owner.lookup('route:session/index');
    assert.ok(route);
  });
});


text:
using System;
using System.Data;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Globalization;

namespace Serenity.Data
{
    public class StringField : GenericClassField<String>, IIdField
    {
        public StringField(ICollection<Field> collection, string name, LocalText caption = null, int size = 0, FieldFlags flags = FieldFlags.Default,
            Func<Row, String> getValue = null, Action<Row, String> setValue = null)
            : base(collection, FieldType.String, name, caption, size, flags, getValue, setValue)
        {
        }

        public static StringField Factory(ICollection<Field> collection, string name, LocalText caption, int size, FieldFlags flags,
            Func<Row, String> getValue, Action<Row, String> setValue)
        {
            return new StringField(collection, name, caption, size, flags, getValue, setValue);
        }

        public override void GetFromReader(IDataReader reader, int index, Row row)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader.IsDBNull(index))
                _setValue(row, null);
            else
                _setValue(row, reader.GetString(index));

            if (row.tracking)
                row.FieldAssignedValue(this);
        }

        public override int IndexCompare(Row row1, Row row2)
        {
            var value1 = _getValue(row1);
            var value2 = _getValue(row2);

            bool null1 = value1 == null;
            bool null2 = value2 == null;
            if (null1 || null2)
            {
                if (null1 && null2)
                    return 0;
                else if (null1)
                    return -1;
                else
                    return 1;
            }
            else
                return value1.CompareTo(value2);
        }

        public override void ValueToJson(JsonWriter writer, Row row, JsonSerializer serializer)
        {
            writer.WriteValue(_getValue(row));
        }

        public override void ValueFromJson(JsonReader reader, Row row, JsonSerializer serializer)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            switch (reader.TokenType)
            {
                case JsonToken.Null:
                case JsonToken.Undefined:
                    _setValue(row, null);
                    break;
                case JsonToken.String:
                    _setValue(row, (string)reader.Value);
                    break;
                case JsonToken.Integer:
                case JsonToken.Float:
                case JsonToken.Boolean:
                    _setValue(row, Convert.ToString(reader.Value, CultureInfo.InvariantCulture));
                    break;
                default:
                    throw JsonUnexpectedToken(reader);
            }

            if (row.tracking)
                row.FieldAssignedValue(this);
        }

        bool IIdField.IsIntegerType
        {
            get
            {
                return false;
            }
        }

        long? IIdField.this[Row row]
        {
            get
            {
                throw new NotImplementedException();
            }

            set
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
package eu.se_bastiaan.tvnl.ui.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadata;
import android.media.session.MediaController;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.devbrackets.android.exomedia.type.MediaSourceType;
import com.devbrackets.android.exomedia.util.MediaSourceUtil;
import com.devbrackets.android.exomedia.util.MediaUtil;
import com.squareup.otto.Subscribe;

import java.lang.ref.WeakReference;

import javax.inject.Inject;

import eu.se_bastiaan.tvnl.AppInjectionComponent;
import eu.se_bastiaan.tvnl.R;
import eu.se_bastiaan.tvnl.content.EventBus;
import eu.se_bastiaan.tvnl.event.PausePlaybackEvent;
import eu.se_bastiaan.tvnl.event.PlaybackProgressChangedEvent;
import eu.se_bastiaan.tvnl.event.SeekBackwardEvent;
import eu.se_bastiaan.tvnl.event.SeekForwardEvent;
import eu.se_bastiaan.tvnl.event.StartPlaybackEvent;
import eu.se_bastiaan.tvnl.event.UpdatePlaybackStateEvent;
import eu.se_bastiaan.tvnl.exomedia.TVNLVideoView;
import eu.se_bastiaan.tvnl.model.OverviewGridItem;
import eu.se_bastiaan.tvnl.model.StreamInfo;
import eu.se_bastiaan.tvnl.ui.activity.DetailsActivity;
import eu.se_bastiaan.tvnl.ui.fragment.DetailsFragment;
import eu.se_bastiaan.tvnl.ui.fragment.VideoPlayerFragment;
import eu.se_bastiaan.tvnl.ui.presenter.base.BasePresenter;
import rx.functions.Action1;

public class VideoPlayerFragPresenter extends BasePresenter<VideoPlayerFragment> {

    private static final String MEDIASESSION_TAG = "TVNLMediaSession";
    private static final String STATE_CURRENTTIME = "state_currenttime";

    @Inject
    Context context;
    @Inject
    EventBus eventBus;
    MediaSession mediaSession;

    long duration = 0;
    int currentTime = -1;

    boolean ended = false;
    boolean seeking = false;
    boolean mediaSessionMetadataApplied = false;

    StreamInfo streamInfo;

    /* Lifecycle Section */

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        try {
            eventBus.register(this);
        } catch (IllegalArgumentException exception) {
            // Object already registered.
        }

        if(savedState != null) {
            currentTime = savedState.getInt(STATE_CURRENTTIME);
        }
    }

    @Override
    protected void onSave(Bundle state) {
        super.onSave(state);
        state.putInt(STATE_CURRENTTIME, currentTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            eventBus.unregister(this);
        } catch (IllegalArgumentException exception) {
            // Object not registered.
        }

        if(mediaSession != null) {
            mediaSession.setActive(false);
            mediaSession.release();
        }
    }

    @Override
    protected void onTakeView(VideoPlayerFragment fragment) {
        super.onTakeView(fragment);

        streamInfo = fragment.getStreamInfo();

        TVNLVideoView videoView = fragment.getVideoView();
        videoView.setKeepScreenOn(true);

        if(duration == 0 || !videoView.isPlaying()) {
            loadMedia(fragment);
        } else {
            fragment.setProgressVisible(false);
        }
    }

    /* MediaPlayer section */

    public void loadMedia(VideoPlayerFragment fragment) {
        String videoLocation;
        if (TextUtils.isEmpty(streamInfo.getVideoLocation())) {
            fragment.showPlayerInfo("Error loading media");
            fragment.getActivity().finish();
            return;
        } else {
            videoLocation = streamInfo.getVideoLocation();
            if (!videoLocation.startsWith("file://") && !videoLocation.startsWith("http://") && !videoLocation.startsWith("https://")) {
                videoLocation = "file://" + videoLocation;
            }
        }

        TVNLVideoView videoView = fragment.getVideoView();

        if(currentTime == -1 && streamInfo.getStartPosition() > 0 && streamInfo.getStartPosition() > currentTime) {
            currentTime = streamInfo.getStartPosition().intValue();
        } else if (currentTime == -1) {
            currentTime = 0;
        }

        videoView.setVideoURI(Uri.parse(videoLocation));
        ended = false;

        activateMediaSession();
    }

    private Boolean isPlaying(VideoPlayerFragment fragment) {
        return fragment.getVideoView().isPlaying();
    }

    public void setCurrentTime(final long time) {
        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                fragment.getVideoView().seekTo((int) time);
            }
        });
    }

    private long getCurrentTime(VideoPlayerFragment fragment) {
        return fragment.getVideoView().getCurrentPosition();
    }

    private long getDuration() {
        return duration;
    }

    public void seek(final int delta) {
        if (duration <= 0 && !seeking) return;

        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                long position = getCurrentTime(fragment) + delta;
                if (position < 0) position = 0;
                setCurrentTime(position);
                updateProgress(getCurrentTime(fragment), getDuration());
            }
        });
    }

    public void isReady(VideoPlayerFragment fragment, TVNLVideoView videoView) {
        videoView.seekTo(currentTime);
        videoView.start();
        duration = videoView.getDuration();
        updatePlayPauseState();
        fragment.setProgressVisible(false);
    }

    public void isCompleted(TVNLVideoView videoView) {
        ended = true;
        currentTime = 0;

        updatePlayPauseState();
        videoView.setKeepScreenOn(false);

        mediaSession.setActive(false);
        mediaSession.release();
    }

    public void encounteredError(VideoPlayerFragment fragment, TVNLVideoView videoView) {
        updatePlayPauseState();
        fragment.showErrorDialog(context.getString(R.string.encountered_error_title), context.getString(R.string.encountered_error));
    }

    public void updateProgress(final long currentTime, final long duration) {
        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                VideoPlayerFragPresenter.this.currentTime = (int) currentTime;
                eventBus.postOnMain(new PlaybackProgressChangedEvent(currentTime, duration));

                if (mediaSession != null && duration > 0) {
                    PlaybackState.Builder builder = new PlaybackState.Builder();
                    builder.setActions(isPlaying(fragment)
                            ? PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PAUSE
                            : PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PLAY);
                    builder.setState(
                            isPlaying(fragment)
                                    ? PlaybackState.STATE_PLAYING
                                    : PlaybackState.STATE_PAUSED,
                            getCurrentTime(fragment),
                            1.0f);
                    mediaSession.setPlaybackState(builder.build());

                    if (!mediaSessionMetadataApplied) {
                        setupMediaMetadata();
                    }
                }
            }
        });
    }

    public void play(VideoPlayerFragment fragment) {
        TVNLVideoView videoView = fragment.getVideoView();
        videoView.seekTo(currentTime);
        videoView.start();
        videoView.setKeepScreenOn(true);

        updatePlayPauseState();
    }

    public void pause(VideoPlayerFragment fragment) {
        TVNLVideoView videoView = fragment.getVideoView();
        videoView.pause();
        videoView.setKeepScreenOn(false);

        updatePlayPauseState();
    }

    public void togglePlayPause() {
        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                if(fragment.getVideoView().isPlaying()) {
                    pause(fragment);
                } else {
                    loadMedia(fragment);
                    play(fragment);
                }
            }
        });
    }

    public void updatePlayPauseState() {
        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                eventBus.postOnMain(new UpdatePlaybackStateEvent(isPlaying(fragment)));

                if (mediaSession != null) {
                    PlaybackState.Builder builder = new PlaybackState.Builder();
                    builder.setActions(isPlaying(fragment)
                            ? PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PAUSE
                            : PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_PLAY);
                    builder.setState(
                            isPlaying(fragment) ? PlaybackState.STATE_PLAYING : PlaybackState.STATE_PAUSED,
                            getCurrentTime(fragment),
                            1.0f);
                    mediaSession.setPlaybackState(builder.build());
                }
            }
        });
    }

    /* Eventbus Events section */

    @SuppressWarnings("unused")
    @Subscribe
    public void onEvent(StartPlaybackEvent event) {
        togglePlayPause();

        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                if (mediaSession != null) {
                    PlaybackState.Builder builder = new PlaybackState.Builder();
                    builder.setActions(PlaybackState.ACTION_PAUSE | PlaybackState.ACTION_PLAY_PAUSE);
                    builder.setState(PlaybackState.STATE_PLAYING, getCurrentTime(fragment), 1.0f);
                    mediaSession.setPlaybackState(builder.build());
                }
            }
        });
    }

    @SuppressWarnings("unused")
    @Subscribe
    public void onEvent(PausePlaybackEvent event) {
        togglePlayPause();

        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                if (mediaSession != null) {
                    PlaybackState.Builder builder = new PlaybackState.Builder();
                    builder.setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE);
                    builder.setState(PlaybackState.STATE_PAUSED, getCurrentTime(fragment), 1.0f);
                    mediaSession.setPlaybackState(builder.build());
                }
            }
        });
    }

    @SuppressWarnings("unused")
    @Subscribe
    public void onEvent(SeekBackwardEvent event) {
        if (!seeking) {
            seeking = true;
            seek(event.getSeek());
            seeking = false;
        }
    }

    @SuppressWarnings("unused")
    @Subscribe
    public void onEvent(SeekForwardEvent event) {
        if (!seeking) {
            seeking = true;
            seek(event.getSeek());
            seeking = false;
        }
    }

    /* MediaSession section */

    private void activateMediaSession() {
        viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
            @Override
            public void call(VideoPlayerFragment fragment) {
                Activity activity = fragment.getActivity();
                mediaSession = new MediaSession(activity, MEDIASESSION_TAG);
                mediaSession.setCallback(new MediaSessionCallback(activity));
                mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
                mediaSession.setActive(true);
                activity.setMediaController(new MediaController(activity, mediaSession.getSessionToken()));
            }
        });
    }

    private void setupMediaMetadata() {
        mediaSessionMetadataApplied = false;

        final MediaMetadata.Builder metadataBuilder = new MediaMetadata.Builder();
        metadataBuilder.putString(MediaMetadata.METADATA_KEY_MEDIA_ID, streamInfo.getId());
        metadataBuilder.putLong(MediaMetadata.METADATA_KEY_DURATION, getDuration());

        metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, streamInfo.getTitle());
        metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_SUBTITLE, streamInfo.getSubtitle());
        metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, streamInfo.getTitle());

        String imageUrl = streamInfo.getImage();
        if (imageUrl != null && !imageUrl.equals("")) {
            metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, imageUrl);
            metadataBuilder.putString(MediaMetadata.METADATA_KEY_ART_URI, imageUrl);

            Target target = new SimpleTarget<GlideBitmapDrawable>() {
                @Override
                public void onResourceReady(GlideBitmapDrawable drawable, GlideAnimation glideAnimation) {
                    metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, drawable.getBitmap());
                    mediaSession.setMetadata(metadataBuilder.build());
                    mediaSessionMetadataApplied = true;
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    mediaSession.setMetadata(metadataBuilder.build());
                    mediaSessionMetadataApplied = true;
                }
            };

            Glide.with(context).load(imageUrl).into(target);
        } else {
            mediaSession.setMetadata(metadataBuilder.build());
            mediaSessionMetadataApplied = true;
        }
    }

    @Override
    protected void injectComponent(AppInjectionComponent component) {
        component.inject(this);
    }

    private class MediaSessionCallback extends MediaSession.Callback {
        private final WeakReference<Context> contextReference;

        public MediaSessionCallback(Context context) {
            contextReference = new WeakReference<>(context);
        }

        @Override
        public void onPlay() {
            eventBus.postOnMain(new StartPlaybackEvent());
        }

        @Override
        public void onPause() {
            eventBus.postOnMain(new PausePlaybackEvent());
        }

        @Override
        public void onFastForward() {
            eventBus.postOnMain(new SeekForwardEvent());
        }

        @Override
        public void onRewind() {
            eventBus.postOnMain(new SeekForwardEvent());
        }

        @Override
        public void onPlayFromMediaId(@NonNull String mediaId, @NonNull Bundle extras) {
            super.onPlayFromMediaId(mediaId, extras);
            if (contextReference.get() == null) return;
            Context context = contextReference.get();
            OverviewGridItem item = extras.getParcelable(DetailsFragment.ITEM_ARG);
            if (item == null) return;
            Intent detailIntent = DetailsActivity.buildIntent(context, item, DetailsFragPresenter.NO_NOTIFICATION);
            context.startActivity(detailIntent);
        }

        @Override
        public boolean onMediaButtonEvent(@NonNull Intent intent) {
            if (!intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) return false;
            KeyEvent keyEvent = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) return false;

            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE) {
                eventBus.post(new PausePlaybackEvent());
                return true;
            }
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                viewFiltered().first().subscribe(new Action1<VideoPlayerFragment>() {
                    @Override
                    public void call(VideoPlayerFragment fragment) {
                        if (isPlaying(fragment)) {
                            eventBus.post(new PausePlaybackEvent());
                        } else {
                            eventBus.post(new StartPlaybackEvent());
                        }
                    }
                });
                return true;
            }

            return false;
        }
    }

}


text:
/**
 * @class Ext.selection.CheckboxModel
 * @extends Ext.selection.RowModel
 *
 * A selection model that renders a column of checkboxes that can be toggled to
 * select or deselect rows. The default mode for this selection model is MULTI.
 *
 * The selection model will inject a header for the checkboxes in the first view
 * and according to the 'injectCheckbox' configuration.
 */
Ext.define('Ext.selection.CheckboxModel', {
    alias: 'selection.checkboxmodel',
    extend: 'Ext.selection.RowModel',

    /**
     * @cfg {String} mode
     * Modes of selection.
     * Valid values are SINGLE, SIMPLE, and MULTI. Defaults to 'MULTI'
     */
    mode: 'MULTI',

    /**
     * @cfg {Number/Boolean/String} injectCheckbox
     * Instructs the SelectionModel whether or not to inject the checkbox header
     * automatically or not. (Note: By not placing the checkbox in manually, the
     * grid view will need to be rendered 2x on initial render.)
     * Supported values are a Number index, false and the strings 'first' and 'last'.
     */
    injectCheckbox: 0,

    /**
     * @cfg {Boolean} checkOnly <tt>true</tt> if rows can only be selected by clicking on the
     * checkbox column.
     */
    checkOnly: false,

    headerWidth: 24,

    // private
    checkerOnCls: Ext.baseCSSPrefix + 'grid-hd-checker-on',

    bindComponent: function(view) {
        var me = this;

        me.sortable = false;
        me.callParent(arguments);
        if (!me.hasLockedHeader() || view.headerCt.lockedCt) {
            // if we have a locked header, only hook up to the first
            view.headerCt.on('headerclick', me.onHeaderClick, me);
            me.addCheckbox(true);
            me.mon(view.ownerCt, 'reconfigure', me.addCheckbox, me);
        }
    },

    hasLockedHeader: function(){
        var hasLocked = false;
        Ext.each(this.views, function(view){
            if (view.headerCt.lockedCt) {
                hasLocked = true;
                return false;
            }
        });
        return hasLocked;
    },

    /**
     * Add the header checkbox to the header row
     * @private
     * @param {Boolean} initial True if we're binding for the first time.
     */
    addCheckbox: function(initial){
        var me = this,
            checkbox = me.injectCheckbox,
            view = me.views[0],
            headerCt = view.headerCt;

        if (checkbox !== false) {
            if (checkbox == 'first') {
                checkbox = 0;
            } else if (checkbox == 'last') {
                checkbox = headerCt.getColumnCount();
            }
            headerCt.add(checkbox,  me.getHeaderConfig());
        }

        if (initial !== true) {
            view.refresh();
        }
    },

    /**
     * Toggle the ui header between checked and unchecked state.
     * @param {Boolean} isChecked
     * @private
     */
    toggleUiHeader: function(isChecked) {
        var view     = this.views[0],
            headerCt = view.headerCt,
            checkHd  = headerCt.child('gridcolumn[isCheckerHd]');

        if (checkHd) {
            if (isChecked) {
                checkHd.el.addCls(this.checkerOnCls);
            } else {
                checkHd.el.removeCls(this.checkerOnCls);
            }
        }
    },

    /**
     * Toggle between selecting all and deselecting all when clicking on
     * a checkbox header.
     */
    onHeaderClick: function(headerCt, header, e) {
        if (header.isCheckerHd) {
            e.stopEvent();
            var isChecked = header.el.hasCls(Ext.baseCSSPrefix + 'grid-hd-checker-on');
            if (isChecked) {
                // We have to supress the event or it will scrollTo the change
                this.deselectAll(true);
            } else {
                // We have to supress the event or it will scrollTo the change
                this.selectAll(true);
            }
        }
    },

    /**
     * Retrieve a configuration to be used in a HeaderContainer.
     * This should be used when injectCheckbox is set to false.
     */
    getHeaderConfig: function() {
        var me = this;

        return {
            isCheckerHd: true,
            text : ' ',
            width: me.headerWidth,
            sortable: false,
            draggable: false,
            resizable: false,
            hideable: false,
            menuDisabled: true,
            dataIndex: '',
            cls: Ext.baseCSSPrefix + 'column-header-checkbox ',
            renderer: Ext.Function.bind(me.renderer, me),
            locked: me.hasLockedHeader()
        };
    },

    /**
     * Generates the HTML to be rendered in the injected checkbox column for each row.
     * Creates the standard checkbox markup by default; can be overridden to provide custom rendering.
     * See {@link Ext.grid.column.Column#renderer} for description of allowed parameters.
     */
    renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
        metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
        return '

';
    },

    // override
    onRowMouseDown: function(view, record, item, index, e) {
        view.el.focus();
        var me = this,
            checker = e.getTarget('.' + Ext.baseCSSPrefix + 'grid-row-checker');

        if (!me.allowRightMouseSelection(e)) {
            return;
        }

        // checkOnly set, but we didn't click on a checker.
        if (me.checkOnly && !checker) {
            return;
        }

        if (checker) {
            var mode = me.getSelectionMode();
            // dont change the mode if its single otherwise
            // we would get multiple selection
            if (mode !== 'SINGLE') {
                me.setSelectionMode('SIMPLE');
            }
            me.selectWithEvent(record, e);
            me.setSelectionMode(mode);
        } else {
            me.selectWithEvent(record, e);
        }
    },

    /**
     * Synchronize header checker value as selection changes.
     * @private
     */
    onSelectChange: function() {
        this.callParent(arguments);

        // check to see if all records are selected
        var hdSelectStatus = this.selected.getCount() === this.store.getCount();
        this.toggleUiHeader(hdSelectStatus);
    }
});


text:
<?php
/**
 * Definition of the ArrayOfCalendarEvent type
 *
 * @package php-ews
 * @subpackage Types
 */

/**
 * Definition of the ArrayOfCalendarEvent type
 */
class EWSType_ArrayOfCalendarEvent extends EWSType
{
    /**
     * CalendarEvent property
     *
     * @var EWSType_CalendarEvent
     */
    public $CalendarEvent;
}


text:
<?php

// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
	'name'=>'My Console Application',

	// preloading 'log' component
	'preload'=>array('log'),

	// application components
	'components'=>array(
        'db' => array(
            'emulatePrepare' => true,
            'charset' => 'utf8',
            'tablePrefix' => '',
            'class'=>'CDbConnection',
        ),
		'log'=>array(
			'class'=>'CLogRouter',
			'routes'=>array(
				array(
					'class'=>'CFileLogRoute',
					'levels'=>'error, warning',
				),
			),
		),
	),
);


text:
package com.fsryan.forsuredb.annotationprocessor.generator.code;

import com.fsryan.forsuredb.annotationprocessor.TableContext;
import com.fsryan.forsuredb.annotationprocessor.generator.GeneratorTest;
import com.fsryan.forsuredb.annotationprocessor.generator.BaseGenerator;
import com.fsryan.forsuredb.TestData;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import javax.tools.JavaFileObject;
import java.util.Arrays;

@RunWith(Parameterized.class)
public class ForSureGeneratorTest extends GeneratorTest<JavaFileObject> {

    private ForSureGenerator gut;

    private String packageName;
    private TableContext inputTargetContext;

    public ForSureGeneratorTest(String classCode, String packageName, TableContext inputTargetContext) {
        super(
                classCode,
                ForSureGeneratorTest.class.getName(),
                true
        );
        this.packageName = packageName;
        this.inputTargetContext = inputTargetContext;
    }

    @Parameterized.Parameters
    public static Iterable<Object[]> data() throws Exception {
        return Arrays.asList(new Object[][] {
                {
                        TestData.resourceText("example_forsure.txt"),
                        "com.fsryan.annotationprocessor.generator.code",
                        TestData.testTargetContext()
                }
        });
    }

    @Before
    public void setUp() {
        gut = new ForSureGenerator(mockProcessingEnv, packageName, inputTargetContext);
    }

    @Override
    protected BaseGenerator<JavaFileObject> generatorUnderTest() {
        return gut;
    }
}


text:
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

List MakeEmpty();
int IsEmpty();
int IsLast();
Position Find()


text:
package main

import (
	"flag"
	"fmt"
	"io"
	"math"
	"os"

	"github.com/ajstarks/svgo"
)

// rawdata defines data as float64 x,y coordinates
type rawdata struct {
	x float64
	y float64
}

type options map[string]bool
type attributes map[string]string
type measures map[string]int

// plotset defines plot metadata
type plotset struct {
	opt  options
	attr attributes
	size measures
}

var (
	canvas                                                       = svg.New(os.Stdout)
	plotopt                                                      = options{}
	plotattr                                                     = attributes{}
	plotnum                                                      = measures{}
	ps                                                           = plotset{plotopt, plotattr, plotnum}
	plotw, ploth, plotc, gwidth, gheight, gutter, beginx, beginy int
)

const (
	globalfmt = "font-family:%s;font-size:%dpt;stroke-width:%dpx"
	linestyle = "fill:none;stroke:"
	linefmt   = "fill:none;stroke:%s"
	barfmt    = linefmt + ";stroke-width:%dpx"
	ticfmt    = "stroke:rgb(200,200,200);stroke-width:1px"
	labelfmt  = ticfmt + ";text-anchor:end;fill:black"
	textfmt   = "stroke:none;baseline-shift:-33.3%"
)

// init initializes command flags and sets default options
func init() {

	// boolean options
	showx := flag.Bool("showx", false, "show the xaxis")
	showy := flag.Bool("showy", false, "show the yaxis")
	showbar := flag.Bool("showbar", false, "show data bars")
	area := flag.Bool("area", false, "area chart")
	connect := flag.Bool("connect", true, "connect data points")
	showdot := flag.Bool("showdot", false, "show dots")
	showbg := flag.Bool("showbg", true, "show the background color")
	showfile := flag.Bool("showfile", false, "show the filename")
	sameplot := flag.Bool("sameplot", false, "plot on the same frame")

	// attributes
	bgcolor := flag.String("bgcolor", "rgb(240,240,240)", "plot background color")
	barcolor := flag.String("barcolor", "gray", "bar color")
	dotcolor := flag.String("dotcolor", "black", "dot color")
	linecolor := flag.String("linecolor", "gray", "line color")
	areacolor := flag.String("areacolor", "gray", "area color")
	font := flag.String("font", "Calibri,sans", "font")
	labelcolor := flag.String("labelcolor", "black", "label color")
	plotlabel := flag.String("label", "", "plot label")

	// sizes
	dotsize := flag.Int("dotsize", 2, "dot size")
	linesize := flag.Int("linesize", 2, "line size")
	barsize := flag.Int("barsize", 2, "bar size")
	fontsize := flag.Int("fontsize", 11, "font size")
	xinterval := flag.Int("xint", 10, "x axis interval")
	yinterval := flag.Int("yint", 4, "y axis interval")

	// meta options
	flag.IntVar(&beginx, "bx", 100, "initial x")
	flag.IntVar(&beginy, "by", 50, "initial y")
	flag.IntVar(&plotw, "pw", 500, "plot width")
	flag.IntVar(&ploth, "ph", 500, "plot height")
	flag.IntVar(&plotc, "pc", 2, "plot columns")
	flag.IntVar(&gutter, "gutter", ploth/10, "gutter")
	flag.IntVar(&gwidth, "width", 1024, "canvas width")
	flag.IntVar(&gheight, "height", 768, "canvas height")

	flag.Parse()

	// fill in the plotset -- all options, attributes, and sizes
	plotopt["showx"] = *showx
	plotopt["showy"] = *showy
	plotopt["showbar"] = *showbar
	plotopt["area"] = *area
	plotopt["connect"] = *connect
	plotopt["showdot"] = *showdot
	plotopt["showbg"] = *showbg
	plotopt["showfile"] = *showfile
	plotopt["sameplot"] = *sameplot

	plotattr["bgcolor"] = *bgcolor
	plotattr["barcolor"] = *barcolor
	plotattr["linecolor"] = *linecolor
	plotattr["dotcolor"] = *dotcolor
	plotattr["areacolor"] = *areacolor
	plotattr["font"] = *font
	plotattr["label"] = *plotlabel
	plotattr["labelcolor"] = *labelcolor

	plotnum["dotsize"] = *dotsize
	plotnum["linesize"] = *linesize
	plotnum["fontsize"] = *fontsize
	plotnum["xinterval"] = *xinterval
	plotnum["yinterval"] = *yinterval
	plotnum["barsize"] = *barsize
}

// fmap maps world data to document coordinates
func fmap(value float64, low1 float64, high1 float64, low2 float64, high2 float64) float64 {
	return low2 + (high2-low2)*(value-low1)/(high1-low1)
}

// doplot opens a file and makes a plot
func doplot(x, y int, location string) {
	var f *os.File
	var err error
	if len(location) > 0 {
		if plotopt["showfile"] {
			plotattr["label"] = location
		}
		f, err = os.Open(location)
	} else {
		f = os.Stdin
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}
	nd, data := readxy(f)
	f.Close()

	if nd >= 2 {
		plot(x, y, plotw, ploth, ps, data)
	}
}

// plot places a plot at the specified location with the specified dimemsions
// usinng the specified settings, using the specified data
func plot(x, y, w, h int, settings plotset, d []rawdata) {
	nd := len(d)
	if nd < 2 {
		fmt.Fprintf(os.Stderr, "%d is not enough points to plot\n", len(d))
		return
	}
	// Compute the minima and maxima
	maxx, minx := d[0].x, d[0].x
	maxy, miny := d[0].y, d[0].y
	for _, v := range d {

		if v.x > maxx {
			maxx = v.x
		}
		if v.y > maxy {
			maxy = v.y
		}
		if v.x < minx {
			minx = v.x
		}
		if v.y < miny {
			miny = v.y
		}
	}
	// Prepare for a area or line chart by allocating
	// polygon coordinates; for the hrizon plot, you need two extra coordinates
	// for the extrema.
	needpoly := settings.opt["area"] || settings.opt["connect"]
	var xpoly, ypoly []int
	if needpoly {
		xpoly = make([]int, nd+2)
		ypoly = make([]int, nd+2)
		// preload the extrema of the polygon,
		// the bottom left and bottom right of the plot's rectangle
		xpoly[0] = x
		ypoly[0] = y + h
		xpoly[nd+1] = x + w
		ypoly[nd+1] = y + h
	}
	// Draw the plot's bounding rectangle
	if settings.opt["showbg"] && !settings.opt["sameplot"] {
		canvas.Rect(x, y, w, h, "fill:"+settings.attr["bgcolor"])
	}
	// Loop through the data, drawing items as specified
	spacer := 10
	canvas.Gstyle(fmt.Sprintf(globalfmt,
		settings.attr["font"], settings.size["fontsize"], settings.size["linesize"]))
	for i, v := range d {
		xp := int(fmap(v.x, minx, maxx, float64(x), float64(x+w)))
		yp := int(fmap(v.y, miny, maxy, float64(y), float64(y-h)))

		if needpoly {
			xpoly[i+1] = xp
			ypoly[i+1] = yp + h
		}
		if settings.opt["showbar"] {
			canvas.Line(xp, yp+h, xp, y+h,
				fmt.Sprintf(barfmt, settings.attr["barcolor"], settings.size["barsize"]))
		}
		if settings.opt["showdot"] {
			canvas.Circle(xp, yp+h, settings.size["dotsize"], "fill:"+settings.attr["dotcolor"])
		}
		if settings.opt["showx"] {
			if i%settings.size["xinterval"] == 0 {
				canvas.Text(xp, (y+h)+(spacer*2), fmt.Sprintf("%d", int(v.x)), "text-anchor:middle")
				canvas.Line(xp, (y + h), xp, (y+h)+spacer, ticfmt)
			}
		}
	}
	// Done constructing the points for the area or line plots, display them in one shot
	if settings.opt["area"] {
		canvas.Polygon(xpoly, ypoly, "fill:"+settings.attr["areacolor"])
	}

	if settings.opt["connect"] {
		canvas.Polyline(xpoly[1:nd+1], ypoly[1:nd+1], linestyle+settings.attr["linecolor"])
	}
	// Put on the y axis labels, if specified
	if settings.opt["showy"] {
		bot := math.Floor(miny)
		top := math.Ceil(maxy)
		yrange := top - bot
		interval := yrange / float64(settings.size["yinterval"])
		canvas.Gstyle(labelfmt)
		for yax := bot; yax <= top; yax += interval {
			yaxp := fmap(yax, bot, top, float64(y), float64(y-h))
			canvas.Text(x-spacer, int(yaxp)+h, fmt.Sprintf("%.1f", yax), textfmt)
			canvas.Line(x-spacer, int(yaxp)+h, x, int(yaxp)+h)
		}
		canvas.Gend()
	}
	// Finally, tack on the label, if specified
	if len(settings.attr["label"]) > 0 {
		canvas.Text(x, y+spacer, settings.attr["label"], "font-size:120%;fill:"+settings.attr["labelcolor"])
	}

	canvas.Gend()
}

// readxy reads coordinates (x,y float64 values) from a io.Reader
func readxy(f io.Reader) (int, []rawdata) {
	var (
		r     rawdata
		err   error
		n, nf int
	)
	data := make([]rawdata, 1)
	for ; err == nil; n++ {
		if n > 0 {
			data = append(data, r)
		}
		nf, err = fmt.Fscan(f, &data[n].x, &data[n].y)
		if nf != 2 {
			continue
		}
	}
	return n - 1, data[0 : n-1]
}

// plotgrid places plots on a grid, governed by a number of columns.
func plotgrid(x, y int, files []string) {
	px := x
	for i, f := range files {
		if i > 0 && i%plotc == 0 && !plotopt["sameplot"] {
			px = x
			y += (ploth + gutter)
		}
		doplot(px, y, f)
		if !plotopt["sameplot"] {
			px += (plotw + gutter)
		}
	}
}

// main plots data from specified files or standard input in a
// grid where plotc specifies the number of columns.
func main() {
	canvas.Start(gwidth, gheight)
	canvas.Rect(0, 0, gwidth, gheight, "fill:white")
	filenames := flag.Args()
	if len(filenames) == 0 {
		doplot(beginx, beginy, "")
	} else {
		plotgrid(beginx, beginy, filenames)
	}
	canvas.End()
}


text:
namespace Microsoft.Azure.Management.ApiManagement.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.ApiManagement;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Request Report data.
    /// </summary>
    public partial class RequestReportRecordContract
    {
        /// <summary>
        /// Initializes a new instance of the RequestReportRecordContract
        /// class.
        /// </summary>
        public RequestReportRecordContract()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the RequestReportRecordContract
        /// class.
        /// </summary>
        /// <param name="apiId">API identifier path. /apis/{apiId}</param>
        /// <param name="operationId">Operation identifier path.
        /// /apis/{apiId}/operations/{operationId}</param>
        /// <param name="productId">Product identifier path.
        /// /products/{productId}</param>
        /// <param name="userId">User identifier path. /users/{userId}</param>
        /// <param name="method">The HTTP method associated with this
        /// request..</param>
        /// <param name="url">The full URL associated with this
        /// request.</param>
        /// <param name="ipAddress">The client IP address associated with this
        /// request.</param>
        /// <param name="backendResponseCode">The HTTP status code received by
        /// the gateway as a result of forwarding this request to the
        /// backend.</param>
        /// <param name="responseCode">The HTTP status code returned by the
        /// gateway.</param>
        /// <param name="responseSize">The size of the response returned by the
        /// gateway.</param>
        /// <param name="timestamp">The date and time when this request was
        /// received by the gateway in ISO 8601 format.</param>
        /// <param name="cache">Specifies if response cache was involved in
        /// generating the response. If the value is none, the cache was not
        /// used. If the value is hit, cached response was returned. If the
        /// value is miss, the cache was used but lookup resulted in a miss and
        /// request was fullfilled by the backend.</param>
        /// <param name="apiTime">The total time it took to process this
        /// request.</param>
        /// <param name="serviceTime">he time it took to forward this request
        /// to the backend and get the response back.</param>
        /// <param name="apiRegion">Azure region where the gateway that
        /// processed this request is located.</param>
        /// <param name="subscriptionId">Subscription identifier path.
        /// /subscriptions/{subscriptionId}</param>
        /// <param name="requestId">Request Identifier.</param>
        /// <param name="requestSize">The size of this request..</param>
        public RequestReportRecordContract(string apiId = default(string), string operationId = default(string), string productId = default(string), string userId = default(string), string method = default(string), string url = default(string), string ipAddress = default(string), string backendResponseCode = default(string), int? responseCode = default(int?), int? responseSize = default(int?), System.DateTime? timestamp = default(System.DateTime?), string cache = default(string), double? apiTime = default(double?), double? serviceTime = default(double?), string apiRegion = default(string), string subscriptionId = default(string), string requestId = default(string), int? requestSize = default(int?))
        {
            ApiId = apiId;
            OperationId = operationId;
            ProductId = productId;
            UserId = userId;
            Method = method;
            Url = url;
            IpAddress = ipAddress;
            BackendResponseCode = backendResponseCode;
            ResponseCode = responseCode;
            ResponseSize = responseSize;
            Timestamp = timestamp;
            Cache = cache;
            ApiTime = apiTime;
            ServiceTime = serviceTime;
            ApiRegion = apiRegion;
            SubscriptionId = subscriptionId;
            RequestId = requestId;
            RequestSize = requestSize;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets API identifier path. /apis/{apiId}
        /// </summary>
        [JsonProperty(PropertyName = "apiId")]
        public string ApiId { get; set; }

        /// <summary>
        /// Gets or sets operation identifier path.
        /// /apis/{apiId}/operations/{operationId}
        /// </summary>
        [JsonProperty(PropertyName = "operationId")]
        public string OperationId { get; set; }

        /// <summary>
        /// Gets product identifier path. /products/{productId}
        /// </summary>
        [JsonProperty(PropertyName = "productId")]
        public string ProductId { get; private set; }

        /// <summary>
        /// Gets user identifier path. /users/{userId}
        /// </summary>
        [JsonProperty(PropertyName = "userId")]
        public string UserId { get; private set; }

        /// <summary>
        /// Gets or sets the HTTP method associated with this request..
        /// </summary>
        [JsonProperty(PropertyName = "method")]
        public string Method { get; set; }

        /// <summary>
        /// Gets or sets the full URL associated with this request.
        /// </summary>
        [JsonProperty(PropertyName = "url")]
        public string Url { get; set; }

        /// <summary>
        /// Gets or sets the client IP address associated with this request.
        /// </summary>
        [JsonProperty(PropertyName = "ipAddress")]
        public string IpAddress { get; set; }

        /// <summary>
        /// Gets or sets the HTTP status code received by the gateway as a
        /// result of forwarding this request to the backend.
        /// </summary>
        [JsonProperty(PropertyName = "backendResponseCode")]
        public string BackendResponseCode { get; set; }

        /// <summary>
        /// Gets or sets the HTTP status code returned by the gateway.
        /// </summary>
        [JsonProperty(PropertyName = "responseCode")]
        public int? ResponseCode { get; set; }

        /// <summary>
        /// Gets or sets the size of the response returned by the gateway.
        /// </summary>
        [JsonProperty(PropertyName = "responseSize")]
        public int? ResponseSize { get; set; }

        /// <summary>
        /// Gets or sets the date and time when this request was received by
        /// the gateway in ISO 8601 format.
        /// </summary>
        [JsonProperty(PropertyName = "timestamp")]
        public System.DateTime? Timestamp { get; set; }

        /// <summary>
        /// Gets or sets specifies if response cache was involved in generating
        /// the response. If the value is none, the cache was not used. If the
        /// value is hit, cached response was returned. If the value is miss,
        /// the cache was used but lookup resulted in a miss and request was
        /// fullfilled by the backend.
        /// </summary>
        [JsonProperty(PropertyName = "cache")]
        public string Cache { get; set; }

        /// <summary>
        /// Gets or sets the total time it took to process this request.
        /// </summary>
        [JsonProperty(PropertyName = "apiTime")]
        public double? ApiTime { get; set; }

        /// <summary>
        /// Gets or sets he time it took to forward this request to the backend
        /// and get the response back.
        /// </summary>
        [JsonProperty(PropertyName = "serviceTime")]
        public double? ServiceTime { get; set; }

        /// <summary>
        /// Gets or sets azure region where the gateway that processed this
        /// request is located.
        /// </summary>
        [JsonProperty(PropertyName = "apiRegion")]
        public string ApiRegion { get; set; }

        /// <summary>
        /// Gets or sets subscription identifier path.
        /// /subscriptions/{subscriptionId}
        /// </summary>
        [JsonProperty(PropertyName = "subscriptionId")]
        public string SubscriptionId { get; set; }

        /// <summary>
        /// Gets or sets request Identifier.
        /// </summary>
        [JsonProperty(PropertyName = "requestId")]
        public string RequestId { get; set; }

        /// <summary>
        /// Gets or sets the size of this request..
        /// </summary>
        [JsonProperty(PropertyName = "requestSize")]
        public int? RequestSize { get; set; }

    }
}


text:
function [mg] = lbm2mg(lbm)
% Convert mass from pounds-mass to milligrams
% Chad Greene 2012
mg = lbm*453592.37;


text:
import Input from "./input"

export { Input }


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CoordinateManager : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

    // TODO: Implement a system whereby "ThePlanetoid" gets set to
    // whatever planet/moon/etc... you are actually closest to.
    public GameObject ThePlanetoid;
    public GameObject TheTerrain;
    public Transform TheShip;

    bool isTerrain = false;

    public void SwitchToTerrain()
    {
        if(isTerrain)
        {
            Debug.LogError("Already in terrain mode.");
            return;
        }

        // We are in space mode, but have to switch to terrain mode.
        isTerrain = true;

        // What are the coordinates of the ship relative to the planetoid
        SphericalCoord sphereCoord = CoordHelper.TransformToSphericalCoord( TheShip.position, ThePlanetoid.transform.position );
        string s = string.Format("Landing ship at coordinates: {0}\n", sphereCoord.ToString());
        Debug.Log(s);

        ThePlanetoid.SetActive(false);
        TheTerrain.SetActive(true);

        // NOTE: This will freeze the game for a few seconds depending on processor speed.
        // Consider solutions like CoRoutines or Threading.
        TheTerrain.GetComponent<DynamicTerrainMaster>().BuildFromLandingSpot( sphereCoord );

        // Now that the terrain exists, move the ship to be in the same reference system.
        // Rotate the ship -90 around the X axis
        TheShip.transform.RotateAround( Vector3.zero, Vector3.right, -90 );

        Vector3 pos = TheShip.transform.position;
        float planetRadius = ThePlanetoid.transform.localScale.x / 2f; // Pick any one axis of the scale

        // Subtract the radius of the planetoid
        pos = pos.normalized * (pos.magnitude - planetRadius);

        // In space, 1 unit = 1km. On ground, 1 unit = 1m. So mult scales/distance by 1000.
        TheShip.transform.position = pos * 1000f;
        Vector3 scale = TheShip.transform.localScale * 1000f;
        TheShip.transform.localScale = scale;

    }

    public void SwitchToSpace()
    {
        if(isTerrain == false)
        {
            Debug.LogError("Already in space mode.");
            return;
        }

        // We are in terrain mode, but have to switch to space mode.
        isTerrain = false;

        // What are the coordinates of the ship relative to the planetoid
        SphericalCoord sphereCoord = TheTerrain.GetComponent<DynamicTerrainMaster>().WorldToSpherical( TheShip.transform.position );
        string s = string.Format("Taking off from coordinates: {0}\n", sphereCoord.ToString());
        Debug.Log(s);

        TheTerrain.GetComponent<DynamicTerrainMaster>().DestroyChunks();

        ThePlanetoid.SetActive(true);
        TheTerrain.SetActive(false);

        // Now that the terrain exists, move the ship to be in the same reference system.
        // Rotate the ship -90 around the X axis
        TheShip.transform.RotateAround( Vector3.zero, Vector3.right, 90 );

        Vector3 pos = TheShip.transform.position;
        float planetRadius = ThePlanetoid.transform.localScale.x / 2f; // Pick any one axis of the scale

        // In space, 1 unit = 1km. On ground, 1 unit = 1m. So DIVIDE scales/distance by 1000.
        pos /= 1000f;
        // Re-add the radius of the planetoid
        pos = pos.normalized * (pos.magnitude + planetRadius);
        TheShip.transform.position = pos;

        Vector3 scale = TheShip.transform.localScale / 1000f;
        TheShip.transform.localScale = scale;

    }
}


text:
This code works with [phpcs](http://pear.php.net/manual/en/package.php.php-codesniffer.php)
and checks code against a modified version of the coding standards used in CakePHP.

NEW: Now it also has auto-fixing for almost all sniffs using the `phpcs-fixer` branch.

## Installation

### Usage

After installation you can check code compliance to the standard using
`phpcs`:

	phpcs --standard=MyCakePHP /path/to/code

### Changes to the CakePHP core one

* Cast sniff
* Detect Yoda conditions
* IsNull sniff
* IsInt/IsWritable sniff
* FunctionName sniff
* ControlStructureSpacing
* LanguageConstructSpacing
* DocBlockEnding sniff
* LanguageConstructSpacing sniff
* Ternary (incl. short ternary) sniff
* @return doc block sniff
* Indentation correct (same level as methods and attributes for classes)
* LF on Windows are allowed to be \r\n

### TODO

* No private methods or attributes (error instead of warning)
* More whitespace sniffs
* Sniff for deprecations