text:
(* ::Package:: *)

(* Authors:
   Karolis Misiunas (km558@cam.ac.uk)
   Kenta Takagaki (github: ktakagaki)
 *)

(* ::Text:: *)
(**)

(*The package provides methods for importing/exporting video using ffmpeg library.
  Problem with Mathematica's Import function is artefacts it produced using QuickTime.
  The aim of the library is to be as compatible as possible with original Mathematica's
  functions with prefix of FF...

  Designed for B&W videos.
  *)
(*Version 1   (2014-05-07) - initial release. *)
(*Version 2   (2014-08-21) - ffprobe and performace mode *)
(*Version 3   (2015-03-09) - ffprobe no longer requires temporary files *)
(*Version 4   (2015-11-20) - fix for mac os x, because streams used to break (in touch with Wolfram)  *)
(*Version 5   (2015-12-04) - ffmpeg with fast and accurate seek; ffprobe check with FFmpeg[]  *)
(*Version 5.1 (2016-01-08) - Added "ImageList" support as with Import  *)
(*Version 5.2 (2018-10-27) - Made method FFprobe public *)

(* ::Section:: *)
(* Package Declarations*)

BeginPackage["FFmpeg`"];

FFImport::usage =
	"FFImport[\"file\", elements] loads the parameters necessary for the Import.
   If supplied with {\"Frames\", 1} or {\"Frames\", Range[]} it will use ffmpeg
   to fetch frames. Optimised for loading consecutive frames."

FFmpeg::usage =
  "FFmpeg[] returns status of the plug-in.
  If text argument is supplied it is assumed to be path to ffmpeg."

FFprobe::usage =
  "FFprobe[] returns status of ffprobe config. If string is passed, it will set the path."

FFInputStreamAt::usage =
  "FFInputStreamAt[file_String, at_Integer, noOfFrames_Integer] returns {data stream, dimensions}
  where \"file\" is the file to be read, \"at\" specifies first frame to read,
  and \"noOfFrames\" gives number of frames to read (you can pass All command)."

FFGetNextFrame::usage =
  "FFGetNextFrame[stream_, dim_] gives image of next frame for specified stream and dimensions."

FFSkipFrame::usage =
  "FFSkipFrame[stream_, dim_, n_Integer:1] skips n frame of specified ffmpeg stream."

FFImport::notSupported = "Command not supported by FFImport[], faling back to Import[]";

(* options associated*)
Options[FFmpeg] = {
  "Colors" -> 3 (*number of color channels*),
  "ColorCommand" -> "rgb24" (*indicator for "-pix_fmt" parameter: gray/rgb24*)
}

(* ::Section:: *)
(*Package Implementations*)

Begin["`Private`"]

(* ::Subsection::Closed:: *)
(*FFmpeg Function*)

(*set the path to ffmpeg*)
FFmpeg[path_String] := (ffmpeg = path;)

(*returns status of ffmpeg.*)
(*todo: on windows it responds, but does not checkout.*)
FFmpeg[] :=
    (
      If[ !StringQ@ffmpeg,
        Print @ "The path to ffmpeg is unknown. Use FFmpeg[\"path\"] to set it.",
        (*second option - test if working*)
        If[ StringMatchQ[
            ToString @ ReadLine @ OpenRead["!" ~~ ffmpeg ~~ " -version", BinaryFormat -> True],
            "ffmpeg version*"],
          Print @ "ffmpeg was found and is functional",
          Print @ ("ffmpeg does not respond correctly. Please check the path: " <> ToString@ffmpeg)
        ]
      ]; FFprobe[]; )

(*run on loading - default path*)
Switch[ $OperatingSystem,
  "MacOSX",  FFmpeg @ "/usr/local/bin/ffmpeg", (*homebrew*)
  "Windows", FFmpeg @ "ffmpeg.exe",
  "Linux",   FFmpeg @ "ffmpeg" ];

(* ::Subsection::Closed:: *)
(*FFmpeg Implementation*)

(*reads stream for next frame*)
FFGetNextFrame[stream_, dim_] :=
  Image[
    Partition[
      Partition[
        BinaryReadList[stream, "Byte", OptionValue[FFmpeg, "Colors"]*dim[[1]]*dim[[2]] ]
        , OptionValue[FFmpeg, "Colors"] ]
      , dim[[1]] ]
  , "Byte"]

(*skip frame*)
FFSkipFrame[stream_, dim_, n_Integer:1] :=
  Skip[ stream, Byte, OptionValue[FFmpeg, "Colors"]*n*dim[[1]]*dim[[2]] ]

(*makes a stream*)
(* special handler for MAC because there is an error for M9+ with pipes*)
If[ $OperatingSystem == "MacOSX" && $VersionNumber >= 9,
  (*MAC OS X version*)
  (*most likely does not handle multiple files at the same time!!*)
  (*leaves pipe in /tmp/ folder *)
  (* TODO: still not working stability! *)
  Print["Warring! FFmpeg does not work well on Mathematica 9+ for Mac, because of pipe issues."];
]

(*makes a stream*)
FFInputStreamAt[file_String, at_Integer, noOfFrames_Integer] :=
  Module[{fps, startAtSec, st, dim, formatedFile},
  formatedFile =  "\"" ~~ file ~~ "\"";
  fps = FFImport[file, "FrameRate"];
  dim = FFImport[file, "ImageSize"];
  startAtSec = (at-1) / fps;
  st = OpenRead["!" ~~ ffmpeg ~~
      " -ss " ~~ ToString[startAtSec] ~~
      " -i " ~~ formatedFile ~~
      " -frames:v " ~~ ToString@noOfFrames ~~
      " -loglevel quiet" ~~
      " -f image2pipe " ~~
      " -pix_fmt " ~~ OptionValue[FFmpeg, "ColorCommand"] ~~
      " -vcodec rawvideo" ~~
      " - " ,
    BinaryFormat -> True];
  {st, dim}
]

(*makes a stream with all the frames*)
FFInputStreamAt[file_String, at_Integer, All] :=
  FFInputStreamAt[file, at, FFImport[file, "FrameCount"]];

(*read one frame*)
FFGetOneFrame[path_String, frame_Integer] := Module[ {st, dim, img},
  {st, dim} = FFInputStreamAt[path, frame, 1];
  img = FFGetNextFrame[st, dim];
  Close[st];
  img
]

(*read multiple frames*)
FFGetOneFrame[path_String, frames_List] := Module[ {order, st, dim, res, ReadFrames},
  order = Sort @ frames;
  {st, dim} = FFInputStreamAt[path, First@order, Last@order - First@order+1];
  ReadFrames[] := Reap@Do[
    If[ MemberQ[order,f],
      Sow @ FFGetNextFrame[st, dim] ,
      FFSkipFrame[st, dim]
    ]
    , {f, First@order, Last@order}
  ];
  res = Check[ ReadFrames[],
                Close[st];
                Print@"Failed loading frames. try again.";
                Return@FFGetOneFrame[path, frames]];
  Close[st];
  res[[2, 1]] (*extract result from reap*)
]

(*read multiple frames - experimental*)
FFGetOneFrameTest[path_String, frames_List] := Module[ {order, st,  dim, res},
  order = Sort @ frames;
  {st, dim} = FFInputStreamAtTest[path, First@order, Last@order - First@order+1];
  res = Reap@Do[
    If[ MemberQ[order,f],
      Sow @ FFGetNextFrame[st, dim] ,
      FFGetNextFrame[st, dim]
    ]
    , {f, First@order, Last@order}
  ];
  Print@"experimental frame grabber - ffmpeg";
  Close[st];
  res[[2, 1]] (*extract result from reap*)
]

(* ::Subsection:: *)
(*FFprobe Function/Implementation*)

(*set the path to ffmpeg*)
FFprobe[path_String] := (ffprobe = path;);

(*returns status of ffmpeg.*)
(*todo: on windows it responds, but does not checkout.*)
FFprobe[] :=
  If[ !StringQ@ffprobe,
    Print @ "The path to ffprobe is unknown. Use FFprobe[\"path\"] to set it.",
    (*second option - test if working*)
    If[ StringMatchQ[
        ToString @ ReadLine @ OpenRead["!" ~~ ffprobe ~~ " -version", BinaryFormat -> True],
        "ffprobe version*"],
      Print @ "ffprobe was found and is functional",
      Print @ ("ffprobe does not respond correctly. Please check the path: " <> ToString@ffprobe)
    ]
  ];

(*run on loading - default path*)
Switch[ $OperatingSystem,
  "MacOSX",  FFprobe @ "/usr/local/bin/ffprobe",
  "Windows", FFprobe @ "ffprobe.exe",
  "Linux",   FFprobe @ "ffprobe"];

FFProbe[file_String, streamCodec_String, targetVariable_String] :=
		FFProbe[file, streamCodec, {targetVariable}][[1]];

FFProbe[file_String, streamCodec_String, {targetVariables__String}] :=
Module[ {tempFile, tempOutput},
  tempOutput = Import["!" <> ffprobe <>
    " -loglevel panic -print_format json -show_format -show_streams \"" <>
      file <> "\"", "JSON"];
	tempOutput = Cases[("streams" /. tempOutput),{___, "codec_type"->streamCodec, ___}];
	If[ Length[tempOutput] >= 1,
		ToExpression[{targetVariables} /. tempOutput[[1]]],
		Message[FFGetFrameRate::noStream, streamCodec, file]; {}
	]
];

FFProbe::noStream = "Could not find `1` stream in file `2`.";

FFGetFrameRate[file_String] := N @ FFProbe[file, "video", "r_frame_rate"];

FFGetDuration[file_String] := N @ FFProbe[file, "video", "duration"];

FFGetImageSize[file_String] := FFProbe[file, "video", {"width","height"}];

(* ::Subsection:: *)
(*FFImport Function (putting everything together)*)

(* Importing function*)
FFImport[path_String, elements_] := Switch[ elements,
  {"Frames", _Integer}, FFGetOneFrame[ path, elements[[2]] ],
  {"Frames", _List}, FFGetOneFrame[path, elements[[2]] ],
  {"Frames", _List, True}, FFGetOneFrameTest[path, elements[[2]] ], (*experimental*)
  {"ImageList", _Integer}, FFGetOneFrame[ path, elements[[2]] ],
  {"ImageList", _List}, FFGetOneFrame[path, elements[[2]] ],
  "FrameRate", FFGetFrameRate[path],
  "ImageSize", FFGetImageSize[path],
  "Duration", FFGetDuration[path],
  {"FrameRate"}, FFGetFrameRate[path],
  {"ImageSize"}, FFGetImageSize[path],
  {"Duration"}, FFGetDuration[path],

  _, Message[FFImport::notSupported, elements]; Import[path, elements]
];

(* todo in the future *)
FFExport[path_String, expr_] := Print @ "not implemented";

(* ::Section:: *)
(*Package Close*)

End[ ]

EndPackage[ ]


text:
- General code rewrite.
- Makes second set of DNS options not required.
- Makes more use of functions.
- New log format.
- Much smaller script.
- Removes top line of log when it is greater than 5,000 lines.
- Better output information.
- Retries for IP once every 10 seconds for 30 seconds before giving up.
- IPv6 Support.
- Move to GitHub.
-

### v0.1.1

- Adds the ability to turn off Pushover.
- Fixes a wrong variable.

### v0.1

- Initial release.

redpajama_set_name: RedPajamaGithub


text:
"""
PyChromecast: remote control your Chromecast
"""
from __future__ import print_function

import logging

# pylint: disable=wildcard-import
from .config import *  # noqa
from .error import *  # noqa
from . import socket_client
from .discovery import discover_chromecasts
from .dial import get_device_status, reboot
from .controllers.media import STREAM_TYPE_BUFFERED  # noqa

def _get_all_chromecasts(tries=None):
    """
    Returns a list of all chromecasts on the network as PyChromecast
    objects.
    """
    hosts = discover_chromecasts()
    cc_list = []
    for ip_address, port in hosts:
        try:
            cc_list.append(Chromecast(host=ip_address, tries=tries))
        except ChromecastConnectionError:
            pass
    return cc_list

def get_chromecasts(tries=None, **filters):
    """
    Searches the network and returns a list of Chromecast objects.
    Filter is a list of options to filter the chromecasts by.

    ex: get_chromecasts(friendly_name="Living Room")

    May return an empty list if no chromecasts were found matching
    the filter criteria

    Filters include DeviceStatus items:
        friendly_name, model_name, manufacturer, api_version
    Or AppStatus items:
        app_id, description, state, service_url, service_protocols (list)
    Or ip address:
        ip

    Tries is specified if you want to limit the number of times the
    underlying socket associated with your Chromecast objects will
    retry connecting if connection is lost or it fails to connect
    in the first place.
    """
    logger = logging.getLogger(__name__)

    cc_list = set(_get_all_chromecasts(tries=tries))
    excluded_cc = set()

    if not filters:
        return list(cc_list)

    if 'ip' in filters:
        for chromecast in cc_list:
            if chromecast.host != filters['ip']:
                excluded_cc.add(chromecast)
        filters.pop('ip')

    for key, val in filters.items():
        for chromecast in cc_list:
            for tup in [chromecast.device, chromecast.status]:
                if hasattr(tup, key) and val != getattr(tup, key):
                    excluded_cc.add(chromecast)

    filtered_cc = cc_list - excluded_cc

    for cast in excluded_cc:
        logger.debug("Stopping excluded chromecast {}".format(cast))
        cast.socket_client.stop.set()

    return list(filtered_cc)

def get_chromecasts_as_dict(tries=None, **filters):
    """
    Returns a dictionary of chromecasts with the friendly name as
    the key.  The value is the pychromecast object itself.

    Tries is specified if you want to limit the number of times the
    underlying socket associated with your Chromecast objects will
    retry connecting if connection is lost or it fails to connect
    in the first place.
    """
    # pylint: disable=star-args
    return {cc.device.friendly_name: cc
            for cc in get_chromecasts(tries=tries, **filters)}

def get_chromecast(strict=False, tries=None, **filters):
    """
    Same as get_chromecasts but only if filter matches exactly one
    ChromeCast.

    Returns a Chromecast matching exactly the fitler specified.

    If strict, return one and only one chromecast

    Tries is specified if you want to limit the number of times the
    underlying socket associated with your Chromecast objects will
    retry connecting if connection is lost or it fails to connect
    in the first place.
    """

    # If we have filters or are operating in strict mode we have to scan
    # for all Chromecasts to ensure there is only 1 matching chromecast.
    # If no filters given and not strict just use the first dicsovered one.
    if filters or strict:
        results = get_chromecasts(tries=tries, **filters)
    else:
        results = _get_all_chromecasts(tries)

    if len(results) > 1:
        if strict:
            raise MultipleChromecastsFoundError(
                'More than one Chromecast was found specifying '
                'the filter criteria: {}'.format(filters))
        else:
            return results[0]

    elif not results:
        if strict:
            raise NoChromecastFoundError(
                'No Chromecasts matching filter critera were found:'
                ' {}'.format(filters))
        else:
            return None

    else:
        return results[0]

# pylint: disable=too-many-instance-attributes
class Chromecast(object):
    """ Class to interface with a ChromeCast. """

    def __init__(self, host, tries=None):
        self.logger = logging.getLogger(__name__)

        # Resolve host to IP address
        self.host = host

        self.logger.info("Querying device status")
        self.device = get_device_status(self.host)

        if not self.device:
            raise ChromecastConnectionError(
                "Could not connect to {}".format(self.host))

        self.status = None
        self.media_status = None

        self.socket_client = socket_client.SocketClient(host, tries)

        self.socket_client.receiver_controller.register_status_listener(self)

        # Forward these methods
        self.set_volume = self.socket_client.receiver_controller.set_volume
        self.play_media = self.socket_client.media_controller.play_media
        self.register_handler = self.socket_client.register_handler

        self.socket_client.start()

    @property
    def is_idle(self):
        """ Returns if there is currently an app running. """
        return self.status is None or self.status.is_stand_by

    @property
    def app_id(self):
        """ Returns the current app_id. """
        return self.status.app_id if self.status else None

    @property
    def app_display_name(self):
        """ Returns the name of the current running app. """
        return self.status.display_name if self.status else None

    @property
    def media_controller(self):
        """ Returns the media controller. """
        return self.socket_client.media_controller

    def new_cast_status(self, status):
        """ Called when a new status received from the Chromecast. """
        self.status = status

    def start_app(self, app_id):
        """ Start an app on the Chromecast. """
        self.logger.info("Starting app {}".format(app_id))

        self.socket_client.receiver_controller.launch_app(app_id)

    def quit_app(self):
        """ Tells the Chromecast to quit current app_id. """
        self.logger.info("Quiting current app")

        self.socket_client.receiver_controller.stop_app()

    def reboot(self):
        """ Reboots the Chromecast. """
        reboot(self.host)

    def volume_up(self):
        """ Increment volume by 0.1 unless it is already maxed.
        Returns the new volume.

        """
        volume = round(self.status.volume_level, 1)
        return self.set_volume(volume + 0.1)

    def volume_down(self):
        """ Decrement the volume by 0.1 unless it is already 0.
        Returns the new volume.
        """
        volume = round(self.status.volume_level, 1)
        return self.set_volume(volume - 0.1)

    def __del__(self):
        self.socket_client.stop.set()

    def __repr__(self):
        return "Chromecast({}, {}, {}, {}, api={}.{})".format(
            self.host, self.device.friendly_name, self.device.model_name,
            self.device.manufacturer, self.device.api_version[0],
            self.device.api_version[1])


text:
layout: post
cover: 'assets/images/cover5.jpg'
title: First post
date: 2016-04-09 10:18:00
tags: test content
subclass: 'post tag-first tag-content'
categories: 'sotolf'
navigation: True
logo: 'assets/images/sotolf.jpg'
---

# How it all started

Well, I've been looking around for some place to write and I have been
interested in static site generators for a while. Well, I've been mostly
reading about them, and I haven't been doing much in them, other than
small tests.

I saw that [github](http://github.com) hosts pages on their
[github.io](http://github.io) site, and that they are using
[jekyll](http://jekyllrb.com) and I was thinking I just go for the standard.
So here I am, I find a nice theme to build on. And now I'll try to make something.


text:
layout: page
title: River Inc. Party
date: 2016-05-24
author: Kathleen Jimenez
tags: weekly links, java
status: published
summary: Aliquam luctus ante nec nulla egestas accumsan. Nulla tortor.
banner: images/banner/people.jpg
booking:
  startDate: 02/29/2016
  endDate: 03/05/2016
  ctyhocn: DALMYHX
  groupCode: RIP
published: true
---
Duis et ligula commodo, tincidunt erat rhoncus, rhoncus sem. Phasellus in enim eros. Ut cursus dapibus ante, sit amet eleifend diam vestibulum id. In hac habitasse platea dictumst. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus et pellentesque mi, in iaculis ipsum. Curabitur efficitur non nulla sit amet aliquam. Suspendisse quis varius lectus. Cras nunc dolor, vehicula in molestie at, ultricies ac odio. Donec commodo eros ut massa semper, quis mollis sem tempor. Cras quis libero non leo malesuada accumsan. Morbi auctor, ex eget auctor cursus, arcu tellus imperdiet felis, nec bibendum libero magna non justo.

* Sed in turpis at felis sagittis viverra
* Vivamus volutpat libero eget dui porttitor, id blandit nisi consequat
* Donec quis ipsum porta urna vestibulum porttitor non eu odio
* Ut vitae sem euismod quam lobortis pellentesque eu at ex
* Mauris suscipit est eget fringilla pulvinar.

Etiam dignissim tristique nisl, eget congue metus aliquet in. Nunc dapibus urna nec odio iaculis, in varius arcu mattis. Nunc dictum sapien sit amet lacus sollicitudin pretium. Aenean ac dolor quis tortor faucibus interdum eget nec purus. Duis congue dui non purus varius sollicitudin. Fusce felis metus, fermentum vitae ornare non, rhoncus ut nibh. Vivamus dapibus erat ac erat condimentum, sed malesuada ligula ullamcorper. Nam sed purus efficitur, fringilla metus nec, tincidunt lectus.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.Mvvm;

namespace PitchDemo
{
	class PointViewModel : BindableBase
	{
		public PointViewModel(string id, double x, double y, Teams team)
		{
			this.Id = id;
			this.X = x;
			this.Y = y;
			this.Team = team;
		}

		public string Id { get; private set; }

		double _x;
		public double X
		{
			get { return _x; }
			private set { SetProperty(ref _x, value); }
		}

		double _y;
		public double Y
		{
			get { return _y; }
			private set { SetProperty(ref _y, value); }
		}

		Teams _team;
		public Teams Team
		{
			get { return _team; }
			set { SetProperty(ref _team, value); }
		}

		public void SwitchDirection()
		{
			X = 1 - X;
		}
	}
}


text:
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);

# CGI
my $q = CGI->new;

# Redirect
print $q->redirect("http://".$ENV{SERVER_NAME}.":16001");


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

namespace MemorizeYC.ViewModels
{
    public class ForPlayPageSettings : INotifyPropertyChanged
    {
        public enum PlayTypeEnum
        {
            hint, syn, rec
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private bool _isHelpMode = false;
        public bool isHelpMode
        {
            get { return _isHelpMode; }
            set { _isHelpMode = value; NotifyPropertyChanged(); }
        }

        private bool _isAllCardsMoveable = false;
        public bool isAllCardsMoveable
        {
            get { return _isAllCardsMoveable; }
            set { _isAllCardsMoveable = value; NotifyPropertyChanged(); }
        }

        private bool _isArrangeAfterMove = true;
        public bool isArrangeAfterMove
        {
            get { return _isArrangeAfterMove; }
            set { _isArrangeAfterMove = value; NotifyPropertyChanged(); }
        }

        private double _speechRatio = 1;
        public double speechRatio
        {
            get { return _speechRatio; }
            set { _speechRatio = value; NotifyPropertyChanged(); }
        }

        private bool _isIgnoreNewLinesWhenSynthesizing = false;
        public bool isIgnoreNewLinesWhenSynthesizing
        {
            get { return _isIgnoreNewLinesWhenSynthesizing; }
            set { _isIgnoreNewLinesWhenSynthesizing = value; NotifyPropertyChanged(); }
        }

        private string _Link="";
        public string Link
        {
            get { return _Link; }
            set { _Link = value; NotifyPropertyChanged(); }
        }

        private StorageFolder _categoryFolder=null;
        public StorageFolder categoryFolder
        {
            get { return _categoryFolder; }
            set { _categoryFolder = value; NotifyPropertyChanged(); }
        }

        private Image _ImgBackground;
        public Image ImgBackground
        {
            get { return _ImgBackground; }
            set { _ImgBackground = value; NotifyPropertyChanged(); }
        }

        private PlayTypeEnum _playType = PlayTypeEnum.syn;
        public PlayTypeEnum playType
        {
            get { return _playType; }
            set { _playType = value; NotifyPropertyChanged(); }
        }

        private bool _isPickWCardsRandomly = true;
        public bool isPickWCardsRandomly
        {
            get { return _isPickWCardsRandomly; }
            set { _isPickWCardsRandomly = value; NotifyPropertyChanged(); }
        }

        private bool _isBGAlsoChange = true;
        public bool isBGAlsoChange
        {
            get { return _isBGAlsoChange; }
            set { _isBGAlsoChange = value; NotifyPropertyChanged(); }
        }

        private int _numWCardShown = 8;
        public int numWCardShown
        {
            get { return _numWCardShown; }
            set { _numWCardShown = value; NotifyPropertyChanged(); }
        }

        private int _numOfRestCards = 0;
        public int numOfRestCards
        {
            get { return _numOfRestCards; }
            set { _numOfRestCards = value; NotifyPropertyChanged(); }
        }

        private int _numOfAllCards = 0;
        public int numOfAllCards
        {
            get { return _numOfAllCards; }
            set { _numOfAllCards = value; NotifyPropertyChanged(); }
        }

        private string _SynLang = "en-US";
        public string SynLang
        {
            get { return _SynLang; }
            set { _SynLang = value; NotifyPropertyChanged(); }
        }

        private string _BackgroundPath="";
        public string BackgroundPath
        {
            get { return _BackgroundPath; }
            set { _BackgroundPath = value; NotifyPropertyChanged(); }
        }

        #region     [2016-10-27 10:50] IsShownAsList & IsDictateTextContentInHint
        private bool _IsShownAsList = false;
        public bool IsShownAsList
        {
            get { return _IsShownAsList; }
            set { _IsShownAsList = value; NotifyPropertyChanged(); }
        }

        private double _GlobalFontSize = 12;
        public double GlobalFontSize
        {
            get { return _GlobalFontSize; }
            set { _GlobalFontSize = value; NotifyPropertyChanged(); }
        }

        private bool _IsDictateTextContentInHint = false;
        public bool IsDictateTextContentInHint
        {
            get { return _IsDictateTextContentInHint; }
            set {
                if (value == false && IsDictateAnsInHint == false)
                    IsDictateAnsInHint = true;
                _IsDictateTextContentInHint = value; NotifyPropertyChanged(); }
        }

        private bool _IsDictateAnsInHint = true;
        public bool IsDictateAnsInHint
        {
            get { return _IsDictateAnsInHint; }
            set {
                _IsDictateAnsInHint = value;
                if (value == false && IsDictateTextContentInHint == false)
                {
                    IsDictateTextContentInHint = true; //By this way, its binding xaml might know that I change its value.
                }
                NotifyPropertyChanged();
            }
        }

        #endregion  IsShownAsList & IsDictateTextContentInHint

        #region    [2017-06-15 14:53] IsAnsFirst & ContentSynLang
        private bool _isAnsFirst = false;
        public bool isAnsFirst
        {
            get { return _isAnsFirst; }
            set { _isAnsFirst = value; NotifyPropertyChanged(); }
        }

        private string _ContentSynLang ="";
        public string ContentSynLang
        {
            get { return _ContentSynLang; }
            set { _ContentSynLang = value; NotifyPropertyChanged(); }
        }

        #endregion [2017-06-15 14:53] IsAnsFirst & ContentSynLang

        private bool _IsIgnoreDueDate = false;
        public bool IsIgnoreDueDate
        {
            get { return _IsIgnoreDueDate; }
            set { _IsIgnoreDueDate = value; NotifyPropertyChanged(); }
        }

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>How to build a test package</title>
   <link rel="stylesheet" href="utplsql.css" type="text/css" />
   <meta name="keywords" content="utPLSQL, PL\SQL, Unit Testing, Framework, Oracle" />
   <meta name="description" content="Unit Testing PL\SQL" />
   <meta name="title" content="How to build a test package" />
   <meta name="author" content="Steven Feuerstein, Chris Rimmer, Patrick Barel and the utPLSQL Project" />
   <meta name="copyright" content="(C) 2000-2005, 2014-2015 Steven Feuerstein, Chris Rimmer, Patrick Barel and the utPLSQL Project" />

[ Home
 | Getting Started
 | Build Test Packages
 | Examples
 | User Guide
 | Release Notes
 | Document Map ]

< Previous Section: Build Test Packages | Next Section: A 'Test Run' with utPLSQL >

How to build a test package

Instructions

      To use utPLSQL, you will build a test package containing your unit tests.
      This test package must conform to the API (application programmatic interface)
      rules of utPLSQL, so that utPLSQL can run your tests automatically.

Every test package must have:

         A setup procedure - register your unit test and set
         up any data structures needed for testing.

         A teardown procedure - remove any data structures
         created for testing.

         One or more unit test procedures - perform the
         unit tests.

      The names you give to your test package, setup, teardown and unit test
      proceedures must also follow the utPLSQL Naming Conventions.

Setup Procedure

      The utPLSQL.test and utPLSQL.testsuite programs
      will call the setup procedure of your test package before it runs any unit
      tests. Use this procedure to define your unit tests and also initialize
      any data structures needed for your units. The package specification header
      for this procedure must be of this form:

CREATE OR REPLACE PACKAGE <prefix><package>
IS
   PROCEDURE <prefix>setup;

      where <prefix> is the unit test prefix and <package>
      is the name of the package (or stand alone program) to be tested. The default
      naming convention is that your test package and all utPLSQL programs, including
      the setup procedure, have a prefix of "ut_", as in:

CREATE OR REPLACE PACKAGE ut_<program>
IS
   PROCEDURE ut_setup;

      Note: if you are using manual
      registration of unit tests (which is not the default setting
      and is not recommeded), see Naming Conventions
      for details on when and how to apply prefixes to your package and procedure
      names.

      Now let's take a look at the body/implementation
      of the setup procedure and how you can use it to define test data structures
      and, optionally, register unit tests.

Define test data structures

      You should  use the setup procedure to define data structures you
      need in one or more of your tests. You might, for example, want to create
      a temporary table to hold information for comparison. You might populate
      a collection or a record a scalar global variable.

      Here is an example of such a procedure (see the file ut_te_employee.pkb
      in the Examples directory of the utPLSQL distribution for the full implementation):

PROCEDURE ut_setup
IS
BEGIN
   ut_teardown;

   EXECUTE IMMEDIATE 'CREATE TABLE ut_employee AS
         SELECT * FROM employee';

   EXECUTE IMMEDIATE 'CREATE TABLE ut_DEL1 AS
         SELECT * FROM employee';

   EXECUTE IMMEDIATE 'CREATE TABLE ut_DELBY_EMP_DEPT_LOOKUP AS
         SELECT * FROM employee';
END;

      For each of my tests, I create a separate table to modify and then use
      in my utAssert comparison.

      You could place these statements in each of the individual unit test
      procedures. The advantage of storing them all in the single setup procedure
      is that they are easier to manage -- and also easier to tear down or destroy
      when you are done.

Manual registration of unit tests

      If you have decided to choose manual
      registration of your unit test procedures, then you will need to register
      each procedure with a call to utPLSQL.registertest
      in the setup procedure. This is not recommended. But if you insist...

      Here is an example of a setup procedure for the
      PLVdate package:

CREATE OR REPLACE PACKAGE BODY ut_plvdate
IS
   PROCEDURE ut_setup
   IS
   BEGIN
      utplsql.addtest ('ut_to_date');
      utplsql.addtest ('ut_to_char');
   END;

      The names passed to the utPLSQL.addtest procedure
      must match the interface of the defined unit test procedures
      with the following interface. So the above two calls to addtest tell utPLSQL
      to look for two unit test procedures named ut_to_date and ut_to_char.

Teardown Procedure

      The utPLSQL.test and utPLSQL.testsuite programs
      will call the teardown procedure of your test package after it runs all
      unit tests. Use this procedure to destroy or remove any data structures
      that were needed for your units. The contents of this procedure should,
      in general, be the logical reverse of the contents of the setup
      procedure. The package specification header for this procedure must
      be of this form:

CREATE OR REPLACE PACKAGE <prefix><package>
IS
   PROCEDURE <prefix>teardown;

      where <prefix> is the unit test prefix and <package>
      is the name of the package (or stand alone program) to be tested.

      The default naming convention is that your test
      package and all utPLSQL programs, including the teardown procedure, have
      a prefix of "ut_", as in:

CREATE OR REPLACE PACKAGE ut_<program>
IS
   PROCEDURE ut_teardown;

      Note: if you are using manual
      registration of unit tests (which is not the default setting
      and is not recommeded), see Naming Conventions
      for details on when and how to apply prefixes to your package and procedure
      names.

      Now let's take a look at the body/implementation
      of the teardown procedure and how you can use it to remove test data structures.

      Here is an example of the most common type of teardown
      procedure -- it does nothing:

CREATE OR REPLACE PACKAGE ut_sales_pkg
IS
   PROCEDURE teardown
   IS
   BEGIN
      NULL;
   END;

      This is what your teardown procedure will look like
      when you do not need to create any special data structures for your tests.
      If I were testing a simple string utility, for example, I do not need a
      database table or collection to run my tests. Note that even if your teardown
      procedure does nothing, it still must be present in the package specification
      and body. utPLSQL will look for and try to execute the procedure as
      part of its S.O.P. (standard operating procedure).

      Now, if your setup procedure creates something,
      you should probably destroy it in teardown. You might drop or truncate
      tables, do a ROLLBACK or simply make sure files and cursors are closed.
      Here is an example of such a procedure:

PROCEDURE teardown
IS
BEGIN
   mycollection.DELETE;
   EXECUTE IMMEDIATE 'TRUNCATE TABLE ' || workspace_tab;
   DBMS_SESSION.FREE_UNUSED_USER_MEMORY;
END;

The Unit Test Procedure

      The unit test procedure is, of course, where it
      gets really interesting and very application specific.

The general format for a test procedure is as follows:

CREATE OR REPLACE PACKAGE <prefix><package>
IS
   PROCEDURE <prefix><program>;

      where <prefix> is the unit test prefix and <package>
      is the name of the package (or stand alone program) to be tested. The default
      naming convention is that your test package and the unit test procedure
      each have a prefix of "ut_". You can override that prefix with another
      of your own choosing in your call to utPLSQL.test
      or utPLSQL.testsuite. Under some circumstances, you can drop
      the prefix on the unit test procedure, but this is not recommended. see
      Naming Conventions. for details.

      Here is a very generic version of a unit test package
      specification and a single unit test procedure:

-- Test package for stand alone program
CREATE OR REPLACE PACKAGE ut_<package>
IS
   PROCEDURE ut_setup;
   PROCEDURE ut_teardown;
   PROCEDURE ut_<program>;
END;

      The body of your unit test procedure is, well, mostly
      yours to figure out, since we don't know what you are testing and how you
      need to test it. The basic format of this test procedure, however, should
      be:

PROCEDURE <myprogram>
IS
BEGIN
   <run package.myprogram or set up for test>

   -- call a utAssert assertion to check results:
   utAssert.<assertion> (...);

   <repeat of the above for different test cases>
EXCEPTION
   WHEN OTHERS
   THEN
      utAssert.this (
         'Unknown failure of <package.myprogram>: ' || SQLERRM,
         FALSE);
END;

      You should include a call to a utAssert assertion program in the exception
      section to trap unexpected errors and register a test failure (I pass FALSE
      for the second argument, which guarantees a failure!). You might, of course,
      have other handlers to trap specific exceptions like NO_DATA_FOUND and
      either register a failure or ignore the exception, since it might not be
      an actual test failure.

      Here is an example of a unit test procedure that contains multiple calls
      to assertion programs for different test cases.

PROCEDURE ut_BETWNSTR IS
BEGIN
   utAssert.eq (
      'Typical valid usage',
      BETWNSTR(
         STRING_IN => 'abcdefg',
         START_IN => 3,
         END_IN => 5
      ),
      'cde'
   );

   utAssert.isnull (
      'NULL start',
      BETWNSTR(
         STRING_IN => 'abcdefg',
         START_IN => NULL,
         END_IN => 5
      )
   );

   utAssert.isnull (
      'NULL end',
      BETWNSTR(
         STRING_IN => 'abcdefg',
         START_IN => 2,
         END_IN => NULL
      )
   );

   utAssert.isnull (
      'End smaller than start',
      BETWNSTR(
         STRING_IN => 'abcdefg',
         START_IN => 5,
         END_IN => 2
      )
   );

   utAssert.eq (
      'End larger than string length',
      BETWNSTR(
         STRING_IN => 'abcdefg',
         START_IN => 3,
         END_IN => 200
      ),
      'cdefg'
   );

END ut_BETWNSTR;

      In the above case, I am testing a function, so I call the function "in
      line" with the assertion program. When testing a procedure, you will call
      the procedure first and then call the appropriate assertion program to
      test the outcome.

      Explore the Examples to learn about different
      ways to write unit test procedures.

Naming Conventions

      When you execute a test or test suite, utPLSQL looks for a test package,
      based on the name of the program you are testing. It then attempts to execute
      specific programs within that package. utPLSQL allows you to test stand-alone
      programs (procedure or function) or package-based programs. When testing
      the contents of a package, you can place your unit test procedures in the
      same
      package or a separate test package. That's a lot of flexibility, and
      flexibility generally leads to confusion.

      To make things as simple as possible, the default mode of utPLSQL follows
      this simple rule:

      Your unit test package and each utPLSQL-related program in that package
      (setup, teardown and unit tests) must all use the same prefix.

      The default prefix is "ut_", but you can override that with your own.
      If you follow this rule (and you can follow it very easily by using the
      utGen
      package to generate a starting point for your test packages), utPLSQL

      If you are following the utPLSQL defaults and letting the utility automatically
      detect and execute unit tests, do not read any further!

      If you choose to perform manual
      registration of your unit tests, then read the following sections carefully,
      as there is a scenario in which you should not apply the utPLSQL
      prefix to your unit test procedures.

      This section describes the conventions or rules that utPLSQL follows
      to locate and execute your unit tests. There are three different "scenarios"
      to consider:

Separate test package to test package-based programs

Separate test package to test a stand-alone program

Single package containing both source to be tested and unit test programs

      While these rules might seem confusing at first glance, you will find
      over time that they are designed to make the issue of what things are named
      as transparent as possible when you run your tests. In other words, you
      simply ask to test "mypackage"; you don't have to run some oddly-named
      program with a prefix in front of it.

      In addition, you can use the utGen package to
      generate a starting point for your test packages. utGen will automatically
      follow the rules; you only need to "fill in the blanks" of your unit test
      procedures within the established headers.

Separate test package to test package-based programs

      If you are placing your unit test code in a package separate from your
      source code (the default setting), then the name of that test package must
      be of the form:

<prefix><package>

      where <prefix> is the utPLSQL prefix and <package> is the name of
      the package containing the programs to be tested.

You specify the prefix in one of the following ways:

         When you call utPLSQL.test or utPLSQL.testsuite, you can pass a value for
         the prefix_in parameter (the default is "ut_").

         When you call utPackage.add to add a package
         to a suite, you can pass a value for the prefix_in parameter (the default
         is "ut_"). This prefix is then stored in the ut_package table.

      The names of the test package programs, on the other hand, should not
      have a prefix before them. These prefixes are not necessary to distinguish
      the test procedure with the program being tested, since they are defined
      in different packages.

Separate test package to test a stand-alone program

      If you are placing your unit test code in a package separate from your
      source code (the default setting), then the name of that test package must
      be of the form:

<prefix><program>

      where <prefix> is the utPLSQL prefix and <program> is the name of
      the stand-alone program you plan to test.

      You specify the prefix in one of the following ways:

         When you call utPLSQL.test or utPLSQL.testsuite, you can pass a value for
         the prefix_in parameter (the default is "ut_").

         When you call utPackage.add to add a package
         to a suite, you can pass a value for the prefix_in parameter (the default
         is "ut_"). This prefix is then stored in the ut_package table.

      The names of the test package programs, on the other hand, also must have
      the same prefix. This is necessary to avoid confusing naming conflicts
      between the program you are testing and the name of the unit test procedure
      for that program, as in the following package that tests the betwnstr function:

CREATE OR REPLACE PACKAGE ut_betwnstr
IS
   PROCEDURE ut_setup;
   PROCEDURE ut_teardown;
   PROCEDURE ut_betwnstr;
END ut_betwnstr;
/

      I suppose that looks odd; I have created a function named ut_betwnstr.ut_betwnstr
      and it would be very strange to write code like that. But that is the whole
      point of utPLSQL: I don't have to write code like that. I just run
      my test with nothing more than this:

SQL> exec utPLSQL.test ('betwnstr')

Single package containing both source to be tested and unit test programs

      Finally, there is the scenario in which a developer places all of her test
      programs (setup, teardown and unit tests) in the same package as the code
      to be tested. In this case, there is no separate test package, so all of
      the test programs must use the utPLSQL prefix, as in:

CREATE OR REPLACE PACKAGE str
IS
   FUNCTION betwn (
      string_in IN VARCHAR2,
      start_in IN PLS_INTEGER,
      end_in IN PLS_INTEGER
   )
      RETURN VARCHAR2;

   PROCEDURE ut_setup;
   PROCEDURE ut_teardown;
   PROCEDURE ut_betwn;

END str;
/

You specify the prefix in one of the following ways:

            When you call utPLSQL.test or utPLSQL.testsuite, you can pass a value for
            the prefix_in parameter (the default is "ut_"). When you call utPackage.add
            to add a package to a suite, you can pass a value for the prefix_in parameter
            (the default is "ut_"). This prefix is then stored in the ut_package table.

< Previous Section: Build Test Packages | Next Section: A 'Test Run' with utPLSQL >

Copyright © 2000-2005, 2014-2015 Steven Feuerstein, Chris Rimmer, Patrick Barel and the utPLSQL Project. All rights reserved


text:
package sune.ssp.util;

public class UnitHelper {

	public static String formatSize(long bytes, int decimals) {
		double factor = 1024;
		double value  = bytes;
		int unitType  = 0;

		if(value >= 1024.0) {
			while((++unitType < 4) &&
				  (value = bytes / factor) >= 1024) {
				factor *= 1024.0;
			}
		}

		return Utils.round(value, decimals) +
			(unitType == 1 ? " kB" :
			 unitType == 2 ? " MB" :
			 unitType == 3 ? " GB" :
			 unitType == 4 ? " TB" : " B");
	}

	public static String formatTime(long milliseconds) {
		double _second = 1000;
		double _minute = 60 * _second;
		double _hour   = 60 * _minute;
		double _day    = 24 * _hour;

		StringBuilder builder = new StringBuilder();
		double days 	= (milliseconds / _day);
		double hours 	= (milliseconds % _day)    / _hour;
		double minutes 	= (milliseconds % _hour)   / _minute;
		double seconds 	= (milliseconds % _minute) / _second;

		if(days 	>= 1) builder.append((int) Utils.round(days, 	0)).append("d ");
		if(hours 	>= 1) builder.append((int) Utils.round(hours, 	0)).append("h ");
		if(minutes 	>= 1) builder.append((int) Utils.round(minutes, 0)).append("m ");
		if(seconds 	>= 1) builder.append((int) Utils.round(seconds, 0)).append("s ");
		builder.append((int) (milliseconds % _second)).append("ms");
		return builder.toString().trim();
	}
}


text:
//
//  THNKeyboardShadowView.h
//  https://github.com/teethandnail/THNKeyboardShadowView
//
//  Created by ZhangHonglin on 2017/3/8.
//  Copyright © 2017年 h.enc. All rights reserved.
//

/**
 * THNKeyboardShadowView function description:
 * When editing UITxtField/UITextView, touch other field, keyboard dismiss,
 * touch same UITextField/UITextView, keyboard still appear.
 */

#import <UIKit/UIKit.h>

@interface THNKeyboardShadowView : UIWindow
/*!
 *  @author HonglinZhang, 17-03-08 12:03:01
 *
 *  @brief enable the shadow function (default is YES)
 */
@property (nonatomic, assign) BOOL enabled;

+ (instancetype)sharedInstance;

@end


text:
# Eloquent: Serialization

- [Giới thiệu](#introduction)
- [Sử dụng cơ bản](#basic-usage)
- [Giấu attributes khỏi JSON](#hiding-attributes-from-json)
- [Thêm giá trị vào JSON](#appending-values-to-json)

## Giới thiệu

Khi xây dựng JSON API, bạn sẽ cần phải convert model và relationship thành mảng hay JSON. Eloquent cung cấp sẵn các hàm tiện ích để thực hiện việc này, cũng như các thao tác xử lý attributes đi kèm trong serialization.

## Sử dụng cơ bản

#### Convert một model thành mảng

Khi convert một model và [relationships](/docs/{{version}}/eloquent-relationships) của nó thành một mảng, bạn có thể sử dụng hàm `toArray`. Hàm này thực hiện đệ quy, vì thế tất cả các attributes và relations (bao gồm relation của relations nữa) sẽ được convert thành mảng:

    $user = App\User::with('roles')->first();

    return $user->toArray();

Bạn cũng có thể convert [collections](/docs/{{version}}/eloquent-collections) thành mảng:

    $users = App\User::all();

    return $users->toArray();

#### Convert một model thành JSON

Để convert một model thành JSON, bạn có thể sử dụng hàm `toJson`. Giống như `toArray`, hàm `toJson` cũng đệ quy và tất cả attributes cùng với relations sẽ được convert thành JSON:

    $user = App\User::find(1);

    return $user->toJson();

Ngoài ra, bạn có thể cast model hay collection thành string, việc này sẽ tự động gọi tới hàm `toJson`:

    $user = App\User::find(1);

    return (string) $user;

Vì model và collection được convert thành JSON khi cast thành string, bạn có thể trả về đối tượng Eloquent trực tiếp từ trong route hay controller:

    Route::get('users', function () {
        return App\User::all();
    });

## Giấu các attributes khỏi JSON

Sẽ có lúc bạn muốn giới hạn attributes như mật khẩu không được hiển thị trong kết quả array hay JSON sau khi convert. Để làm được điều đó, thêm vào thuộc tính `$hidden` vào trong model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = ['password'];
    }

> **Chú ý:** Khi giấu relationships, sử dụng tên **method** của relationship, chứ không phải thuộc tính động của nó.

Một cách khác, bạn có thể sử dụng thuộc tính `visible` để khai báo danh sách các attributes cần được thêm vào trong kết quả array và JSON:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * The attributes that should be visible in arrays.
         *
         * @var array
         */
        protected $visible = ['first_name', 'last_name'];
    }

#### Tạm thời mở attribute bị giấu

Nếu bạn muốn làm cho một số thuộc tính đã giấu có thể thấy được, sử dụng hàm `makeVisible`. Hàm này trả về một đối tượng của model làm cho việc móc nối tiện hơn:

    return $user->makeVisible('attribute')->toArray();

## Thêm giá trị vào JSON

Bạn cũng có thể thêm vào thuộc tính mà không có trường lưu trong database. Để làm thế, đầu tiện cần phải khai báo một [accessor](/docs/{{version}}/eloquent-mutators):

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * Get the administrator flag for the user.
         *
         * @return bool
         */
        public function getIsAdminAttribute()
        {
            return $this->attributes['admin'] == 'yes';
        }
    }

Khi đã tạo được accessor, them vào tên của attribute vào thuộc tính `$appends` trên model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * The accessors to append to the model's array form.
         *
         * @var array
         */
        protected $appends = ['is_admin'];
    }

Khi mà attribute được thêm vào trong danh sách `$appends`, nó sẽ được thêm vào khi convert thành thành array hay JSON. Attribute trong mảng `appends` cũng sẽ tuần tự theo cấu hình `$visible` và `$hidden` trong model.


text:
import sys
import gzip
import re

xopen = lambda f: (gzip.open if f.endswith(".gz") else open)(f)
vcf = xopen(sys.argv[1])
key = sys.argv[2]

patt = re.compile("ID=AN_(...),")
fields = []
for line in vcf:
    if line[0] != "#": break

    m = patt.search(line)
    if not m: continue
    group = m.groups()[0]
    fields.extend(["AC_{group}".format(**locals()),
                   "AN_{group}".format(**locals())])
    if group != "Adj":
        fields.extend([
                   "Hom_{group}".format(**locals()),
                   "Het_{group}".format(**locals())])

    # create a postannotation block for each population
    print """\
[[postannotation]]
fields=["{key}_AC_{group}", "{key}_AN_{group}"]
name="{key}_af_{group}"
op="div2"
type="Float"
""".format(**locals())

# create a single annotation that pulls all fields.
print """\
[[annotation]]
file="{vcf}"
fields=[{fields}]
ops=[{ops}]
names=[{names}]
""".format(vcf=sys.argv[1],
                          fields=",".join('"%s"' % f for f in fields),
                          ops=",".join(['"self"'] * len(fields)),
                          names=",".join('"%s_%s"' % (key, f) for f in fields))


text:
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_gpio.h>

#include <linux/power/gpio-charger.h>

struct gpio_charger {
	const struct gpio_charger_platform_data *pdata;
	unsigned int irq;
	bool wakeup_enabled;

	struct power_supply *charger;
	struct power_supply_desc charger_desc;
};

static irqreturn_t gpio_charger_irq(int irq, void *devid)
{
	struct power_supply *charger = devid;

	power_supply_changed(charger);

	return IRQ_HANDLED;
}

static inline struct gpio_charger *psy_to_gpio_charger(struct power_supply *psy)
{
	return power_supply_get_drvdata(psy);
}

static int gpio_charger_get_property(struct power_supply *psy,
		enum power_supply_property psp, union power_supply_propval *val)
{
	struct gpio_charger *gpio_charger = psy_to_gpio_charger(psy);
	const struct gpio_charger_platform_data *pdata = gpio_charger->pdata;

	switch (psp) {
	case POWER_SUPPLY_PROP_ONLINE:
		val->intval = !!gpio_get_value_cansleep(pdata->gpio);
		val->intval ^= pdata->gpio_active_low;
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

static enum power_supply_property gpio_charger_properties[] = {
	POWER_SUPPLY_PROP_ONLINE,
};

static
struct gpio_charger_platform_data *gpio_charger_parse_dt(struct device *dev)
{
	struct device_node *np = dev->of_node;
	struct gpio_charger_platform_data *pdata;
	const char *chargetype;
	enum of_gpio_flags flags;
	int ret;

	if (!np)
		return ERR_PTR(-ENOENT);

	pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
	if (!pdata)
		return ERR_PTR(-ENOMEM);

	pdata->name = np->name;

	pdata->gpio = of_get_gpio_flags(np, 0, &flags);
	if (pdata->gpio < 0) {
		if (pdata->gpio != -EPROBE_DEFER)
			dev_err(dev, "could not get charger gpio\n");
		return ERR_PTR(pdata->gpio);
	}

	pdata->gpio_active_low = !!(flags & OF_GPIO_ACTIVE_LOW);

	pdata->type = POWER_SUPPLY_TYPE_UNKNOWN;
	ret = of_property_read_string(np, "charger-type", &chargetype);
	if (ret >= 0) {
		if (!strncmp("unknown", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_UNKNOWN;
		else if (!strncmp("battery", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_BATTERY;
		else if (!strncmp("ups", chargetype, 3))
			pdata->type = POWER_SUPPLY_TYPE_UPS;
		else if (!strncmp("mains", chargetype, 5))
			pdata->type = POWER_SUPPLY_TYPE_MAINS;
		else if (!strncmp("usb-sdp", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_USB;
		else if (!strncmp("usb-dcp", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_USB_DCP;
		else if (!strncmp("usb-cdp", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_USB_CDP;
		else if (!strncmp("usb-aca", chargetype, 7))
			pdata->type = POWER_SUPPLY_TYPE_USB_ACA;
		else
			dev_warn(dev, "unknown charger type %s\n", chargetype);
	}

	return pdata;
}

static int gpio_charger_probe(struct platform_device *pdev)
{
	const struct gpio_charger_platform_data *pdata = pdev->dev.platform_data;
	struct power_supply_config psy_cfg = {};
	struct gpio_charger *gpio_charger;
	struct power_supply_desc *charger_desc;
	int ret;
	int irq;

	if (!pdata) {
		pdata = gpio_charger_parse_dt(&pdev->dev);
		if (IS_ERR(pdata)) {
			ret = PTR_ERR(pdata);
			if (ret != -EPROBE_DEFER)
				dev_err(&pdev->dev, "No platform data\n");
			return ret;
		}
	}

	if (!gpio_is_valid(pdata->gpio)) {
		dev_err(&pdev->dev, "Invalid gpio pin\n");
		return -EINVAL;
	}

	gpio_charger = devm_kzalloc(&pdev->dev, sizeof(*gpio_charger),
					GFP_KERNEL);
	if (!gpio_charger) {
		dev_err(&pdev->dev, "Failed to alloc driver structure\n");
		return -ENOMEM;
	}

	charger_desc = &gpio_charger->charger_desc;

	charger_desc->name = pdata->name ? pdata->name : "gpio-charger";
	charger_desc->type = pdata->type;
	charger_desc->properties = gpio_charger_properties;
	charger_desc->num_properties = ARRAY_SIZE(gpio_charger_properties);
	charger_desc->get_property = gpio_charger_get_property;

	psy_cfg.supplied_to = pdata->supplied_to;
	psy_cfg.num_supplicants = pdata->num_supplicants;
	psy_cfg.of_node = pdev->dev.of_node;
	psy_cfg.drv_data = gpio_charger;

	ret = gpio_request(pdata->gpio, dev_name(&pdev->dev));
	if (ret) {
		dev_err(&pdev->dev, "Failed to request gpio pin: %d\n", ret);
		goto err_free;
	}
	ret = gpio_direction_input(pdata->gpio);
	if (ret) {
		dev_err(&pdev->dev, "Failed to set gpio to input: %d\n", ret);
		goto err_gpio_free;
	}

	gpio_charger->pdata = pdata;

	gpio_charger->charger = power_supply_register(&pdev->dev,
						      charger_desc, &psy_cfg);
	if (IS_ERR(gpio_charger->charger)) {
		ret = PTR_ERR(gpio_charger->charger);
		dev_err(&pdev->dev, "Failed to register power supply: %d\n",
			ret);
		goto err_gpio_free;
	}

	irq = gpio_to_irq(pdata->gpio);
	if (irq > 0) {
		ret = request_any_context_irq(irq, gpio_charger_irq,
				IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
				dev_name(&pdev->dev), gpio_charger->charger);
		if (ret < 0)
			dev_warn(&pdev->dev, "Failed to request irq: %d\n", ret);
		else
			gpio_charger->irq = irq;
	}

	platform_set_drvdata(pdev, gpio_charger);

	device_init_wakeup(&pdev->dev, 1);

	return 0;

err_gpio_free:
	gpio_free(pdata->gpio);
err_free:
	return ret;
}

static int gpio_charger_remove(struct platform_device *pdev)
{
	struct gpio_charger *gpio_charger = platform_get_drvdata(pdev);

	if (gpio_charger->irq)
		free_irq(gpio_charger->irq, gpio_charger->charger);

	power_supply_unregister(gpio_charger->charger);

	gpio_free(gpio_charger->pdata->gpio);

	return 0;
}

#ifdef CONFIG_PM_SLEEP
static int gpio_charger_suspend(struct device *dev)
{
	struct gpio_charger *gpio_charger = dev_get_drvdata(dev);

	if (device_may_wakeup(dev))
		gpio_charger->wakeup_enabled =
			!enable_irq_wake(gpio_charger->irq);

	return 0;
}

static int gpio_charger_resume(struct device *dev)
{
	struct platform_device *pdev = to_platform_device(dev);
	struct gpio_charger *gpio_charger = platform_get_drvdata(pdev);

	if (device_may_wakeup(dev) && gpio_charger->wakeup_enabled)
		disable_irq_wake(gpio_charger->irq);
	power_supply_changed(gpio_charger->charger);

	return 0;
}
#endif

static SIMPLE_DEV_PM_OPS(gpio_charger_pm_ops,
		gpio_charger_suspend, gpio_charger_resume);

static const struct of_device_id gpio_charger_match[] = {
	{ .compatible = "gpio-charger" },
	{ }
};
MODULE_DEVICE_TABLE(of, gpio_charger_match);

static struct platform_driver gpio_charger_driver = {
	.probe = gpio_charger_probe,
	.remove = gpio_charger_remove,
	.driver = {
		.name = "gpio-charger",
		.pm = &gpio_charger_pm_ops,
		.of_match_table = gpio_charger_match,
	},
};

module_platform_driver(gpio_charger_driver);

MODULE_AUTHOR("Lars-Peter Clausen <lars@metafoo.de>");
MODULE_DESCRIPTION("Driver for chargers which report their online status through a GPIO");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:gpio-charger");


text:
{% extends "site_base.html" %}

{% load i18n %}
{% load generic_flatblocks %}

{% block head_title %}{% gblock "contact_title" for "gblocks.Title" %}{% endblock %}

{% block tab_id %}id="contact_tab"{% endblock %}

{% block body %}
    {% gblock "contact_content" for "gblocks.TitleTextAndImage" %}
{% endblock %}


text:
function setup()
    -- Create a new craft scene
    scene = craft.scene()

    myEntity = scene:entity()
    myEntity.model = craft.model("Blocky Characters:Robot")
    myEntity.y = -7
    myEntity.z = 30
    myEntity.eulerAngles = vec3(0, 0, 180)

end

function update(dt)
    -- Update the scene (physics, transforms etc)
    scene:update(dt)
end

-- Called automatically by codea
function draw()
    update(DeltaTime)

    -- Draw the scene
    scene:draw()
end

function PrintExplanation()
    print([[A blank scene.]])
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>capacitar-conselho-escolar</id>
    <dbId>1311</dbId>
    <nome>Capacitar Conselho Escolar</nome>
    <sigla>PNFCE</sigla>
    <nomes-populares>
        <item id="2979">Programa Nacional de Fortalecimento dos Conselhos Escolares</item>
        <item id="2980">Conselho Escolar</item>
    </nomes-populares>
    <descricao>

Atenção! Serviço temporariamente indisponível!

O Programa Nacional de Fortalecimento dos Conselhos Escolares visa fomentar a implantação e o fortalecimento dos Conselhos Escolares, bem como qualificar a atuação de seus membros (pais, estudantes, professores, demais funcionários, diretor e comunidade local) para que contribuam com a melhoria da qualidade do ensino ofertado e para garantir a efetiva participação das comunidades escolar e local na gestão administrativa, financeira e pedagógica das escolas.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="4846">
            <tipo>Estados e municípios</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <entre min="2" max="7" unidade="dias-corridos"/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="8886">
            <titulo>Realizar matrícula</titulo>
            <descricao>Entrega de documentos para matricula-se no curso a distância.</descricao>
            <documentos>
                <default>
                    <item id="13091">Carteira de identidade (RG)</item>
                    <item id="13092">CPF</item>
                    <item id="13093">Comprovante de endereço</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="9640" tipo="presencial">
                        <descricao>Nas IFES parceira no estado ou município</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="8887">
            <titulo>Participar da capacitação</titulo>
            <descricao></descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="9641" tipo="presencial">
                        <descricao>Na IFES parceira no estado ou município</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/244" dbId="37528">
        <nomeOrgao>Ministério da Educação (MEC)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="2" idServicoSegmento="8562">Órgãos e entidades públicas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Administração e Gestão Pública</item>
        <item>Educação à distância</item>
        <item>Profissionais da educação</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="16168">conselho municipal de educação</item>
        <item id="16169">capacitação</item>
        <item id="16170">implementar conselho</item>
    </palavras-chave>
    <servicos-relacionados>
        <item>1309</item>
        <item>1310</item>
        <item>992</item>
    </servicos-relacionados>
</servico>


text:
from django.shortcuts import render, get_object_or_404

# Create your views here.
from .models import Post

def post_list(request):
    queryset_list = Post.objects.all() #.order_by("-timestamp")
    context = {
        "object_list": queryset_list,
    }
    return render(request, "posts/list.html", context)

def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    context = {
        "instance": instance,
    }
    return render(request, "posts/detail.html", context)


text:
import $ from 'jquery';
import { bootstrapPolyfills } from '../../src/bootstrap';
import { delay } from '../../src/helpers/delay';

describe('imported component', async() => {

	await bootstrapPolyfills;
	let { component } = await System.import('app-decorators');
	let { Test } = await System.import('test/imports/testcomponent');

	@component()
	class Col {

		created({ testEl }){

			this.item = {
				name: 'A',
				content: 1
			};

			testEl.render(this.item);
			$(this).append(testEl);
		}

	}

	it('should create an domnode', async () => {

		let col = Col.create({
			testEl: Test.create()
		});

        await delay(5);
		col.outerHTML.should.equal(`<com-col><com-test rendered="true"><div class="A">1</div> </com-test></com-col>`);
	});

});


text:
void ofApp::setup(){
	ofSetLogLevel(OF_LOG_VERBOSE);

	ofFileDialogResult result = ofSystemLoadDialog();
	if (result.bSuccess) {
        stream.setup(2, 0, 44100, 256, 1);
        stream.setOutput(output);

        player.load(result.getPath());
		player.play();

		wave.setup(0, 0, ofGetWidth(), ofGetHeight());

        player.connectTo(wave).connectTo(output);

		ofBackground(0);
	}
}

//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){

	wave.draw();

}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){}


text:
import React from 'react'
import Main from '../app/components/main'
import JobSearchLayout from '../app/components/jobs/job-search.layout'
// import JobSearchLayout from '../app/layouts/JobSearchLayout'
import SearchForm from '../app/components/commons/forms/search-form'
import NotFound from '../app/components/commons/not-found.layout'
import {Route,IndexRoute} from 'react-router'

import GoogleAnalytics from './google-analytics';

const GA = new GoogleAnalytics(GA_TRACKING_CODE);

const onRouteChange = (prevState, nextState, replace, callback)=>{
    GA.send(nextState.location)
    callback()
}

export default (
    <Route path="/" component={Main}

           onChange={onRouteChange.bind(this)}>
        <IndexRoute component={JobSearchLayout}/>
        <Route path="/search" component={JobSearchLayout}/>
        <Route path="/form" component={SearchForm}/>
        <Route path="*" component={JobSearchLayout}/>
    </Route>
)


text:
using System;
using Accidis.WebServices.Models;

namespace Accidis.Sjoslaget.WebService.Models
{
	public sealed class BookingPax
	{
		public Guid Id { get; set; }
		public Guid BookingCabinId { get; set; }
		public string Group { get; set; }
		public string FirstName { get; set; }
		public string LastName { get; set; }
		public Gender Gender { get; set; }
		public DateOfBirth Dob { get; set; }
		public string Nationality { get; set; }
		public int Years { get; set; }

		public static BookingPax FromSource(BookingSource.Pax source, Guid bookingCabinId)
		{
			return new BookingPax
			{
				BookingCabinId = bookingCabinId,
				Group = source.Group,
				FirstName = source.FirstName,
				LastName = source.LastName,
				Gender = Gender.FromString(source.Gender),
				Dob = new DateOfBirth(source.Dob),
				Nationality = source.Nationality,
				Years = source.Years
			};
		}
	}
}


text:
package org.apache.ftpserver.listener.nio;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.LoggingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Internal class, do not use directly.
 *
 * Specialized @see {@link LoggingFilter} that optionally masks FTP passwords.
 *
 * @author Apache MINA Project
 */
public class FtpLoggingFilter extends LoggingFilter {

    private boolean maskPassword = true;

    private final Logger logger;

    /**
     * @see LoggingFilter#LoggingFilter()
     */
    public FtpLoggingFilter() {
        this(FtpLoggingFilter.class.getName());
    }

    /**
     * @see LoggingFilter#LoggingFilter(Class)
     */
    public FtpLoggingFilter(Class<?> clazz) {
        this(clazz.getName());
    }

    /**
     * @see LoggingFilter#LoggingFilter(String)
     */
    public FtpLoggingFilter(String name) {
        super(name);

        logger = LoggerFactory.getLogger(name);
    }

    /**
     * @see LoggingFilter#messageReceived(org.apache.mina.core.filterchain.IoFilter.NextFilter,
     *      IoSession, Object)
     */
    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session,
            Object message) throws Exception {
        String request = (String) message;

        String logMessage;
        if (maskPassword) {

            if (request.trim().toUpperCase().startsWith("PASS ")) {
                logMessage = "PASS *****";
            } else {
                logMessage = request;
            }
        } else {
            logMessage = request;
        }

        logger.info("RECEIVED: {}", logMessage);
        nextFilter.messageReceived(session, message);
    }

    /**
     * Are password masked?
     *
     * @return true if passwords are masked
     */
    public boolean isMaskPassword() {
        return maskPassword;
    }

    /**
     * Mask password in log messages
     *
     * @param maskPassword
     *            true if passwords should be masked
     */
    public void setMaskPassword(boolean maskPassword) {
        this.maskPassword = maskPassword;
    }

}


text:
/**
 *
 */
package uk.ac.manchester.cs.pronto.index;

import java.io.IOException;
import java.io.Writer;
import java.util.Collection;

import aterm.ATermAppl;

/**
 *
Title: IndexSet

 *
 *
Description:
 *

 *
 *
Copyright: Copyright (c) 2007, 2008

 *
 *
Company: Clark & Parsia, LLC. <http://www.clarkparsia.com>

 *
 * @author pavel
 */
public interface IndexSet {
	/**
	 * @return all index terms
	 */
	public Collection<? extends IndexTerm> getTerms();
	/**
	 * Retrieves all index terms that are subsumed by the given term
	 * w.r.t to the knowledge base
	 */
	public Collection<? extends IndexTerm> getSubsumedTerms(ATermAppl term);

	public IndexSet clone();

	public void dump(Writer writer) throws IOException;

	public void clear();

	public boolean isEmpty();

}


text:
'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var globby = require('globby');
var mocha = require('gulp-mocha');
var through = require('through2');
var rename = require('gulp-rename');
var historyApiFallback = require('connect-history-api-fallback');
var useref = require('gulp-useref');
var gutil = require('gulp-util');
var packager = require('electron-packager');
var electronInstaller = require('electron-winstaller');
var exec = require('child_process').exec;

const buildVersion = '1.0.1';
const electronVersion = '1.4.0';

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// Browserify npm modules
gulp.task('browserify', function () {

  return browserify('app/scripts/app.js')
    .bundle()
    //Pass desired output filename to vinyl-source-stream
    .pipe(source('bundle.js'))
    // Uglify
    //.pipe(streamify($.uglify()))
    // Start piping stream to tasks!
    .pipe(gulp.dest('./app/scripts/'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
      'app/scripts/**/*.js',
      '!app/scripts/adapters/**/*.js',
      '!app/scripts/vendor/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    /*.pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))*/
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/sourcefiles',
    '!app/precache.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*'])
    .pipe(gulp.dest('dist/elements'));

  var images = gulp.src(['app/images/**/*'])
    .pipe(gulp.dest('dist/images'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vendorScripts = gulp.src(['app/scripts/vendor/**/*'])
    .pipe(gulp.dest('dist/scripts/vendor'));

  var vendorStyles = gulp.src(['app/styles/vendor/**/*'])
    .pipe(gulp.dest('dist/styles/vendor'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  var profiles = gulp.src(['app/profiles/**/*'])
    .pipe(gulp.dest('dist/profiles'));

  var fonts = gulp.src(['app/fonts/**/*'])
    .pipe(gulp.dest('dist/fonts'));

  var manuals = gulp.src(['app/userManuals/**/*'])
    .pipe(gulp.dest('dist/userManuals'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox, profiles, vendorScripts, vendorStyles, fonts, manuals)
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {

  var assets = useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'}).on('error', gutil.log)))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe(useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  var DEST_DIR = 'dist/elements';

  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

gulp.task('npm-install', function () {

  var npmInstallPromise = new Promise(function (resolve, reject) {

    exec('cd dist && npm install', function (error, stdout, stderr) {
      console.log(stdout);
      console.log(stderr);

      if (error) {
        console.log(error);
        reject(error);
      } else {
        resolve();
      }
    });
  });

  return npmInstallPromise;
});

// Generate a list of files that should be precached when serving from 'dist'.
// The list will be consumed by the <platinum-sw-cache> element.
gulp.task('precache', function (callback) {
  var dir = 'dist';

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('online.html', 'offline.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      var filePath = path.join(dir, 'precache.json');
      fs.writeFile(filePath, JSON.stringify(files), callback);
    }
  });
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    // will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [ historyApiFallback() ],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js', '!app/scripts/bundle.js'], ['browserify']);
  gulp.watch(['app/scripts/bundle.js'], ['jshint', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    // will present a certificate warning in the browser.
    // https: true,
    server: 'dist',
    middleware: [ historyApiFallback() ]
  });
});

gulp.task("browser-unit-tests", function () {

  "use strict";

  browserSync({
    server: {
      //serve tests and the root as base dirs
      baseDir: ["./app/test/", "./"],
      index: "testrunner.html"
    }
  });
});

gulp.task('unit-tests', function () {

  // gulp expects tasks to return a stream, so we create one here.
  var bundledStream = through();

  bundledStream
    // turns the output bundle stream into a stream containing
    // the normal attributes gulp plugins expect.
    .pipe(source('stores-test.js'))
    // the rest of the gulp task, as you would normally write it.
    .pipe(buffer())
    .pipe(gulp.dest('./app/test/scripts/build/'))
    .pipe(mocha({
      bail: false,
      reporter: 'doc'
    }));

  // "globby" replaces the normal "gulp.src" as Browserify
  // creates it's own readable stream.
  globby(['./app/test/scripts/specs/*.js'], function(err, entries) {
    // ensure any errors from globby are handled
    if (err) {
      bundledStream.emit('error', err);
      return;
    }

    // create the Browserify instance and pipe the Browserify stream into the stream we created earlier
    // this starts our gulp pipeline.
    browserify({
      entries: entries
    })
    .ignore('browserify-fs')
    .bundle()
    .pipe(bundledStream);
  });

  // finally, we return the stream, so gulp knows when this task is done.
  return bundledStream;
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    'browserify',
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html', /*'unit-tests'*/],
    'npm-install',
    //'vulcanize',
    cb);
    // Note: add , 'precache' , after 'vulcanize', if your are going to use Service Worker
});

gulp.task('packager:osxpackagecreator', function () {

  var options = {
    'app-version': buildVersion,
    'app-category-type': 'public.app-category.business',
    'asar': true,
    'arch': 'all',
    'dir': './dist',
    'icon': './icons/SITFonline.ico.icns',
    'name': 'EPEPackageCreator',
    'productName': 'EPE Package Creator',
    'out': '/Users/ODonnell/SITF/Builds',
    'overwrite': true,
    'platform': 'darwin',
    'version': electronVersion
  };

  var taskPromise = new Promise(function (resolve, reject) {

    packager(options, function (error, appPaths) {

      if (error) {
        console.log(error);
        reject(error);
      } else {
        console.log(appPaths);
        resolve(appPaths);
      }
    }.bind(this));
  });

  return taskPromise;
});

gulp.task('packager:osxpackageviewer', function () {

  var options = {
    'app-version': buildVersion,
    'app-category-type': 'public.app-category.business',
    'asar': true,
    'arch': 'all',
    'dir': './dist',
    'icon': './icons/SITFoffline.ico.icns',
    'name': 'EPEPackageViewer',
    'productName': 'EPE Package Viewer',
    'out': '/Users/ODonnell/SITF/Builds',
    'overwrite': true,
    'platform': 'darwin',
    'version': electronVersion
  };

  var taskPromise = new Promise(function (resolve, reject) {

    packager(options, function (error, appPaths) {

      if (error) {
        console.log(error);
        reject(error);
      } else {
        console.log(appPaths);
        resolve(appPaths);
      }
    }.bind(this));
  });

  return taskPromise;
});

gulp.task('packager:windowspackagecreator', function () {

  var options = {
    'app-version': buildVersion,
    'asar': true,
    'arch': 'all',
    'dir': './dist',
    'icon': './icons/SITFonline.ico',
    'name': 'EPEPackageCreator',
    'productName': 'EPE Package Creator',
    'out': '/Users/ODonnell/SITF/Builds',
    'overwrite': true,
    'platform': 'win32',
    'version': electronVersion,
    'version-string': {
      'CompanyName': 'Evidential Ltd',
      'FileDescription': 'EPE Package Creator',
      'OriginalFilename': 'EPEPackageCreator',
      'ProductName': 'EPEPackageCreator',
      'InternalName': 'EPEPackageCreator'
    }
  };

  var taskPromise = new Promise(function (resolve, reject) {

    packager(options, function (error, appPaths) {

      if (error) {
        console.log(error);
        reject(error);
      } else {
        console.log(appPaths);
        resolve(appPaths);
      }
    }.bind(this));
  });

  return taskPromise;
});

gulp.task('packager:windowspackageviewer', function () {

  var options = {
    'app-version': buildVersion,
    'asar': true,
    'arch': 'all',
    'dir': './dist',
    'icon': './icons/SITFoffline.ico',
    'name': 'EPEPackageViewer',
    'productName': 'EPE Package Viewer',
    'out': '/Users/ODonnell/SITF/Builds',
    'overwrite': true,
    'platform': 'win32',
    'version': electronVersion,
    'version-string': {
      'CompanyName': 'Evidential Ltd',
      'FileDescription': 'EPE Package Viewer',
      'OriginalFilename': 'EPEPackageViewer',
      'ProductName': 'EPEPackageViewer',
      'InternalName': 'EPEPackageViewer'
    }
  };

  var taskPromise = new Promise(function (resolve, reject) {

    packager(options, function (error, appPaths) {

      if (error) {
        console.log(error);
        reject(error);
      } else {
        console.log(appPaths);
        resolve(appPaths);
      }
    }.bind(this));
  });

  return taskPromise;
});

gulp.task('installer:windowspackagecreator', function () {

  var appDirectory = '/Users/ODonnell/SITF/Builds';

  var installerPromise = electronInstaller.createWindowsInstaller({
    appDirectory: appDirectory + '/EPEPackageCreator-win32-x64',
    outputDirectory: '/Users/ODonnell/SITF/Builds',
    authors: 'Evidential Ltd',
    exe: 'EPEPackageCreator.exe',
    version: buildVersion,
    loadingGif: './icons/gears.gif',
    iconUrl: 'https://paddeee.github.io/icons/SITFonline.ico',
    setupIcon: './icons/SITFonline.ico',
    setupExe: 'EPEPackageCreatorSetUp.exe'
  });

  return installerPromise.then(function() {
    console.log('Package Creator Installer Complete');
  }, function(error) {
    console.log(`No dice: ${error.message}`);
  });
});

gulp.task('installer:windowspackageviewer', function () {

  var appDirectory = '/Users/ODonnell/SITF/Builds';

  var installerPromise = electronInstaller.createWindowsInstaller({
    appDirectory: appDirectory + '/EPEPackageViewer-win32-x64',
    outputDirectory: '/Users/ODonnell/SITF/Builds',
    authors: 'Evidential Ltd',
    exe: 'EPEPackageViewer.exe',
    version: buildVersion,
    loadingGif: './icons/gears.gif',
    iconUrl: 'https://paddeee.github.io/icons/SITFoffline.ico',
    setupIcon: './icons/SITFoffline.ico',
    setupExe: 'EPEPackageViewerSetUp.exe'
  });

  return installerPromise.then(function() {
    console.log('Package Creator Installer Complete');
  }, function(error) {
    console.log(`No dice: ${error.message}`);
  });
});

gulp.task('build:osx', function (cb) {
  runSequence(
    'default',
    'packager:osxpackagecreator',
    'packager:osxpackageviewer',
    cb);
});

gulp.task('build:windows', function (cb) {
  runSequence(
    'default',
    'packager:windowspackagecreator',
    'packager:windowspackageviewer',
    'installer:windowspackagecreator',
    'installer:windowspackageviewer',
    cb);
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
//require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}


text:
package generate

import (
	"bytes"
	"errors"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"io"
	"reflect"
	"regexp"
	"text/template"
)

const tmplStr = `
// This file was auto-generated using createmock. See the following page for
// more information:
//
//     https://github.com/jacobsa/oglemock
//

package {{.Pkg}}

import (
	{{range $identifier, $import := .Imports}}{{$identifier}} "{{$import}}"
	{{end}}
)

{{range .Interfaces}}
	{{$interfaceName := printf "Mock%s" .Name}}
	{{$structName := printf "mock%s" .Name}}

	type {{$interfaceName}} interface {
		{{getTypeString .}}
		oglemock.MockObject
	}

	type {{$structName}} struct {
		controller oglemock.Controller
		description string
	}

	func New{{printf "Mock%s" .Name}}(
		c oglemock.Controller,
		desc string) {{$interfaceName}} {
	  return &{{$structName}}{
			controller: c,
			description: desc,
		}
	}

	func (m *{{$structName}}) Oglemock_Id() uintptr {
		return uintptr(unsafe.Pointer(m))
	}

	func (m *{{$structName}}) Oglemock_Description() string {
		return m.description
	}

	{{range getMethods .}}
	  {{$funcType := .Type}}
	  {{$inputTypes := getInputs $funcType}}
	  {{$outputTypes := getOutputs $funcType}}

		func (m *{{$structName}}) {{.Name}}({{range $i, $type := $inputTypes}}p{{$i}} {{getInputTypeString $i $funcType}}, {{end}}) ({{range $i, $type := $outputTypes}}o{{$i}} {{getTypeString $type}}, {{end}}) {
			// Get a file name and line number for the caller.
			_, file, line, _ := runtime.Caller(1)

			// Hand the call off to the controller, which does most of the work.
			retVals := m.controller.HandleMethodCall(
				m,
				"{{.Name}}",
				file,
				line,
				[]interface{}{ {{range $i, $type := $inputTypes}}p{{$i}}, {{end}} })

			if len(retVals) != {{len $outputTypes}} {
				panic(fmt.Sprintf("{{$structName}}.{{.Name}}: invalid return values: %v", retVals))
			}

			{{range $i, $type := $outputTypes}}
				// o{{$i}} {{getTypeString $type}}
				if retVals[{{$i}}] != nil {
					o{{$i}} = retVals[{{$i}}].({{getTypeString $type}})
				}
			{{end}}

			return
		}
	{{end}}
{{end}}
`

type tmplArg struct {
	// The package of the generated code.
	Pkg string

	// Imports needed by the interfaces.
	Imports importMap

	// The set of interfaces to mock.
	Interfaces []reflect.Type
}

var tmpl *template.Template

func init() {
	extraFuncs := make(template.FuncMap)
	extraFuncs["getMethods"] = getMethods
	extraFuncs["getInputs"] = getInputs
	extraFuncs["getOutputs"] = getOutputs
	extraFuncs["getInputTypeString"] = getInputTypeString
	extraFuncs["getTypeString"] = getTypeString

	tmpl = template.New("code")
	tmpl.Funcs(extraFuncs)
	tmpl.Parse(tmplStr)
}

func getInputTypeString(i int, ft reflect.Type) string {
	numInputs := ft.NumIn()
	if i == numInputs-1 && ft.IsVariadic() {
		return "..." + getTypeString(ft.In(i).Elem())
	}

	return getTypeString(ft.In(i))
}

func getTypeString(t reflect.Type) string {
	return t.String()
}

func getMethods(it reflect.Type) []reflect.Method {
	numMethods := it.NumMethod()
	methods := make([]reflect.Method, numMethods)

	for i := 0; i < numMethods; i++ {
		methods[i] = it.Method(i)
	}

	return methods
}

func getInputs(ft reflect.Type) []reflect.Type {
	numIn := ft.NumIn()
	inputs := make([]reflect.Type, numIn)

	for i := 0; i < numIn; i++ {
		inputs[i] = ft.In(i)
	}

	return inputs
}

func getOutputs(ft reflect.Type) []reflect.Type {
	numOut := ft.NumOut()
	outputs := make([]reflect.Type, numOut)

	for i := 0; i < numOut; i++ {
		outputs[i] = ft.Out(i)
	}

	return outputs
}

// A map from import identifier to package to use that identifier for,
// containing elements for each import needed by a set of mocked interfaces.
type importMap map[string]string

var typePackageIdentifierRegexp = regexp.MustCompile(`^([\pL_0-9]+)\.[\pL_0-9]+$`)

// Add an import for the supplied type, without recursing.
func addImportForType(imports importMap, t reflect.Type) {
	// If there is no package path, this is a built-in type and we don't need an
	// import.
	pkgPath := t.PkgPath()
	if pkgPath == "" {
		return
	}

	// Work around a bug in Go:
	//
	//     http://code.google.com/p/go/issues/detail?id=2660
	//
	var errorPtr *error
	if t == reflect.TypeOf(errorPtr).Elem() {
		return
	}

	// Use the identifier that's part of the type's string representation as the
	// import identifier. This means that we'll do the right thing for package
	// "foo/bar" with declaration "package baz".
	match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
	if match == nil {
		return
	}

	imports[match[1]] = pkgPath
}

// Add all necessary imports for the type, recursing as appropriate.
func addImportsForType(imports importMap, t reflect.Type) {
	// Add any import needed for the type itself.
	addImportForType(imports, t)

	// Handle special cases where recursion is needed.
	switch t.Kind() {
	case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice:
		addImportsForType(imports, t.Elem())

	case reflect.Func:
		// Input parameters.
		for i := 0; i < t.NumIn(); i++ {
			addImportsForType(imports, t.In(i))
		}

		// Return values.
		for i := 0; i < t.NumOut(); i++ {
			addImportsForType(imports, t.Out(i))
		}

	case reflect.Map:
		addImportsForType(imports, t.Key())
		addImportsForType(imports, t.Elem())
	}
}

// Add imports for each of the methods of the interface, but not the interface
// itself.
func addImportsForInterfaceMethods(imports importMap, it reflect.Type) {
	// Handle each method.
	for i := 0; i < it.NumMethod(); i++ {
		m := it.Method(i)
		addImportsForType(imports, m.Type)
	}
}

// Given a set of interfaces, return a map from import identifier to package to
// use that identifier for, containing elements for each import needed by the
// mock versions of those interfaces.
func getImports(interfaces []reflect.Type) importMap {
	imports := make(importMap)
	for _, it := range interfaces {
		addImportForType(imports, it)
		addImportsForInterfaceMethods(imports, it)
	}

	// Make sure there are imports for other types used by the generated code
	// itself.
	imports["fmt"] = "fmt"
	imports["oglemock"] = "github.com/jacobsa/oglemock"
	imports["runtime"] = "runtime"
	imports["unsafe"] = "unsafe"

	return imports
}

// Given a set of interfaces to mock, write out source code for a package named
// `pkg` that contains mock implementations of those interfaces.
func GenerateMockSource(w io.Writer, pkg string, interfaces []reflect.Type) error {
	// Sanity-check arguments.
	if pkg == "" {
		return errors.New("Package name must be non-empty.")
	}

	if len(interfaces) == 0 {
		return errors.New("List of interfaces must be non-empty.")
	}

	// Make sure each type is indeed an interface.
	for _, it := range interfaces {
		if it.Kind() != reflect.Interface {
			return errors.New("Invalid type: " + it.String())
		}
	}

	// Create an appropriate template arg, then execute the template. Write the
	// raw output into a buffer.
	var arg tmplArg
	arg.Pkg = pkg
	arg.Imports = getImports(interfaces)
	arg.Interfaces = interfaces

	buf := new(bytes.Buffer)
	if err := tmpl.Execute(buf, arg); err != nil {
		return err
	}

	// Parse the output.
	fset := token.NewFileSet()
	astFile, err := parser.ParseFile(fset, pkg+".go", buf, parser.ParseComments)
	if err != nil {
		return errors.New("Error parsing generated code: " + err.Error())
	}

	// Sort the import lines in the AST in the same way that gofmt does.
	ast.SortImports(fset, astFile)

	// Pretty-print the AST, using the same options that gofmt does by default.
	cfg := &printer.Config{
		Mode:     printer.UseSpaces | printer.TabIndent,
		Tabwidth: 8,
	}

	if err = cfg.Fprint(w, fset, astFile); err != nil {
		return errors.New("Error pretty printing: " + err.Error())
	}

	return nil
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Class InvalidArgumentException | tomkyle/DbFacade</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

DbFacade

PHP

Classes

PDO

PDOStatement

SplDoublyLinkedList

SplQueue

Interfaces

ArrayAccess

Countable

Iterator

Serializable

Traversable

Exceptions

Exception

InvalidArgumentException

LogicException

RuntimeException

UnexpectedValueException

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Namespace

Class

				Tree

Class InvalidArgumentException

			Exception

			LogicException

InvalidArgumentException

		PHP Extension: SPL

		Documented at php.net

Methods inherited from Exception

			__construct(),
			__toString(),
			getCode(),
			getFile(),
			getLine(),
			getMessage(),
			getPrevious(),
			getTrace(),
			getTraceAsString()

Properties inherited from Exception

			<var>$code</var>,
			<var>$file</var>,
			<var>$line</var>,
			<var>$message</var>

		tomkyle/DbFacade API documentation generated by ApiGen 2.8.0