text:
% Created 2016-03-18 Fri 15:53
\documentclass[a4paper,12pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{amssymb}
\usepackage{hyperref}
\tolerance=1000
\usepackage{fancyvrb}
\setlength{\textheight}{24cm}
\setlength{\textwidth}{16cm}
\setlength{\evensidemargin}{-0cm}
\setlength{\oddsidemargin}{-0cm}
\setlength{\topmargin}{0cm}
\renewcommand{\baselinestretch}{1.1}%1.1
\author{Hans Fangohr}
\date{\today}
\title{Class diagrams}
\hypersetup{
  pdfkeywords={},
  pdfsubject={},
  pdfcreator={Emacs 24.5.1 (Org mode 8.2.10)}}
\begin{document}

\maketitle
\tableofcontents

\section{OOMMF Classes}
\label{sec-1}

Inheritance structure taken from \url{http://math.nist.gov/oommf/doc/userguide12a6/userguide/Standard_Oxs_Ext_Child_Clas.html#BA}, with additional reading of source code in \verb~oommf/app/oxs/base~ and \verb~oommf/app/oxs/ext~

\subsection{Atlasses}
\label{sec-1-1}

Figure \ref{fig:atlas} on page \pageref{fig:atlas} shows the OOMMF Atlas classes.

\begin{figure}[htb]
\centering
\includegraphics[width=1\textwidth]{atlas.eps}
\caption{\label{fig:atlas}OOMMF Atlas classes}
\end{figure}

\subsection{Meshes}
\label{sec-1-2}

Figure \ref{fig:mesh} on page \pageref{fig:mesh} shows the OOMMF Mesh classes.

\begin{figure}[htb]
\centering
\includegraphics[width=1\textwidth]{mesh.eps}
\caption{\label{fig:mesh}Mesh classes}
\end{figure}

\subsection{Energies}
\label{sec-1-3}
\subsubsection{Anisotropy energy}
\label{sec-1-3-1}

Figure \ref{fig:anisotropy-energy} on page \pageref{fig:anisotropy-energy} shows the OOMMF anisotropy energy classes.

\begin{figure}[htb]
\centering
\includegraphics[width=1\textwidth]{anisotropy-energy.eps}
\caption{\label{fig:anisotropy-energy}Anisotropy energy classes}
\end{figure}

\#+LATEX \clearpage\newpage

\section{Setting up your system to compile this file}
\label{sec-2}

\subsection{Mini tutorial generating UML diagrams}
\label{sec-2-1}

\begin{itemize}
\item Install 'plantuml' on your system
\begin{itemize}
\item \verb~brew install plantuml~ on OS X
\end{itemize}
\item Tell Emacs where to find the plantuml jar file (in \textasciitilde{}.emacs):
\begin{Verbatim}
(setq org-plantuml-jar-path~
    (expand-file-name "/usr/local/Cellar/plantuml/8031/plantuml.8031.jar"))
\end{Verbatim}

\item Tell Emacs to parse plantuml code (also python, sh, dot in this example):

\begin{Verbatim}
;; enable python for in-buffer evaluation
(org-babel-do-load-languages
 'org-babel-load-languages
 '(
   (python . t)
   (sh . t)
   (plantuml . t)
   (dot . t)
   ))

;; all plantuml and dot code to execute without confirmation
(defun my-org-confirm-babel-evaluate (lang body)
(not (or (string= lang "plantuml") (string= lang "dot"))))
(setq org-confirm-babel-evaluate 'my-org-confirm-babel-evaluate)
\end{Verbatim}

\item To re-execute the plantuml code, use \verb~C-c C-c~ when the cursor is in that block.

\item Let's add \verb~*.eps~ files to the repository, so that we only need this
setup for creating new class diagrams.
\end{itemize}

\subsection{To compile the pdf from this file (watch how the screen changes):}
\label{sec-2-2}
\verb~C-c C-e l p~
% Emacs 24.5.1 (Org mode 8.2.10)
\end{document}


text:
#region License

#endregion

using System;
using System.Text;

namespace WebSocketSharp
{
  /// <summary>
  /// Contains the event data associated with a <see cref="WebSocket.OnClose"/> event.
  /// </summary>
  /// <remarks>
  ///   <para>
  ///   A <see cref="WebSocket.OnClose"/> event occurs when the WebSocket connection has been
  ///   closed.
  ///   </para>
  ///   <para>
  ///   If you would like to get the reason for the close, you should access
  ///   the <see cref="CloseEventArgs.Code"/> or <see cref="CloseEventArgs.Reason"/> property.
  ///   </para>
  /// </remarks>
  public class CloseEventArgs : EventArgs
  {
    #region Private Fields

    private bool        _clean;
    private ushort      _code;
    private PayloadData _payloadData;
    private byte[]      _rawData;
    private string      _reason;

    #endregion

    #region Internal Constructors

    protected internal CloseEventArgs ()
    {
      _code = (ushort) CloseStatusCode.NoStatus;
      _payloadData = new PayloadData ();
      _rawData = _payloadData.ApplicationData;
    }

    protected internal CloseEventArgs (ushort code)
    {
      _code = code;
      _rawData = code.InternalToByteArray (ByteOrder.Big);
    }

    protected internal CloseEventArgs (CloseStatusCode code)
      : this ((ushort) code)
    {
    }

    internal CloseEventArgs (PayloadData payloadData)
    {
      _payloadData = payloadData;
      _rawData = payloadData.ApplicationData;

      var len = _rawData.Length;
      _code = len > 1
              ? _rawData.SubArray (0, 2).ToUInt16 (ByteOrder.Big)
              : (ushort) CloseStatusCode.NoStatus;

      _reason = len > 2
                ? _rawData.SubArray (2, len - 2).UTF8Decode ()
                : String.Empty;
    }

    protected internal CloseEventArgs (ushort code, string reason)
    {
      _code = code;
      _reason = reason;
      _rawData = code.Append (reason);
    }

    protected internal CloseEventArgs (CloseStatusCode code, string reason)
      : this ((ushort) code, reason)
    {
    }

    #endregion

    #region Internal Properties

    internal PayloadData PayloadData {
      get {
        return _payloadData ?? (_payloadData = new PayloadData (_rawData));
      }
    }

    internal byte[] RawData {
      get {
        return _rawData;
      }
    }

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets the status code for the close.
    /// </summary>
    /// <value>
    /// A <see cref="ushort"/> that represents the status code for the close if any.
    /// </value>
    public ushort Code {
      get {
        return _code;
      }
    }

    /// <summary>
    /// Gets the reason for the close.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the reason for the close if any.
    /// </value>
    public string Reason {
      get {
        return _reason ?? String.Empty;
      }
    }

    /// <summary>
    /// Gets a value indicating whether the WebSocket connection has been closed cleanly.
    /// </summary>
    /// <value>
    /// <c>true</c> if the WebSocket connection has been closed cleanly; otherwise, <c>false</c>.
    /// </value>
    public bool WasClean {
      get {
        return _clean;
      }

      internal set {
        _clean = value;
      }
    }

    #endregion
  }
}

redpajama_set_name: RedPajamaGithub


text:
wa=$CATALINA_HOME/webapps
cpn=$CATALINA_HOME/components

# Webapps bundles
cp ./bundle/announcement/* $wa/sakai-announcement-tool/WEB-INF/classes/
cp ./bundle/gradebook/* $wa/sakai-gradebook-tool/WEB-INF/classes/org/sakaiproject/tool/
cp ./bundle/membership/* $wa/sakai-usermembership-tool/WEB-INF/classes/org/sakaiproject/umem/tool/bundle/
cp ./bundle/samigo/* $wa/samigo-app/WEB-INF/classes/org/sakaiproject/tool/assessment/bundle
cp ./bundle/tool-prefs/* $wa/sakai-user-tool-prefs/WEB-INF/classes/
cp ./bundle/web/* $wa/samigo-app/WEB-INF/classes/org/sakaiproject/tool/assessment/bundle
cp ./bundle/glossaire/* $wa/osp-glossary-tool/WEB-INF/classes/org/theospi/portfolio/glossary/bundle/

# Localization-bundle component
mkdir -p $cpn/localization-bundles-pack/WEB-INF/classes/org/sakaiproject/localization/bundle/tool
cp ./bundle/localization/* $cpn/localization-bundles-pack/WEB-INF/classes/org/sakaiproject/localization/bundle/tool/

# Portal component
mkdir -p $wa/portal/WEB-INF/classes
cp ./bundle/portal/* $wa/portal/WEB-INF/classes/

# Assets
cp ./assets/sakai_powered.gif $wa/library/image/sakai_powered.gif


text:
extern "C" double BOOST_MATH_TR1_DECL legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x)
{
   return c_policies::legendre_p BOOST_PREVENT_MACRO_SUBSTITUTION(n, x);
}


text:
		<?php echo $messageSentView->Render(); ?>

		<?php echo $messageNotSentView->Render(); ?>

<?php echo $message; ?>

		<form role="form" id="frmCSCF" name="frmCSCF" method="post">
			<?php wp_nonce_field( 'cscf_contact', 'cscf_nonce' ); ?>
			<input type="hidden" name="post-id" value="<?php echo $postID; ?>">

			<?php if ( isset( $contact->Errors['recaptcha'] ) ) { ?>

<?php echo $contact->Errors['recaptcha']; ?>

			<?php } ?>

			<div class="control-group form-group<?php if ( isset( $contact->Errors['name'] ) ) {
				echo ' error has-error';
			} ?>">
				<?php _e( 'Name:', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>

				<div class="<?php echo cscf_PluginSettings::InputIcons() ? "input-group" : ""; ?>">
					<?php if ( cscf_PluginSettings::InputIcons() == true ) { ?>

					<?php } ?>
					<input class="form-control input-xlarge"
					       data-rule-required="true"
					       data-msg-required="<?php _e( 'Please give your name.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
					       type="text" id="cscf_name" name="cscf[name]"
					       value="<?php echo esc_attr( $contact->Name ); ?>"
					       placeholder="<?php _e( 'Your Name', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
						/>

                <span for="cscf_name" class="help-inline help-block error"
                      style="display:<?php echo isset( $contact->Errors['name'] ) ? 'block' : 'none'; ?>;">

                    <?php if ( isset( $contact->Errors['name'] ) ) {
	                    echo $contact->Errors['name'];
                    } ?>

			<div class="control-group form-group<?php if ( isset( $contact->Errors['email'] ) ) {
				echo ' error has-error';
			} ?>">
				<?php _e( 'Email Address:', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>

				<div class="<?php echo cscf_PluginSettings::InputIcons() ? "input-group" : ""; ?>">
					<?php if ( cscf_PluginSettings::InputIcons() == true ) { ?>

					<?php } ?>
					<input class="form-control input-xlarge"
					       data-rule-required="true"
					       data-rule-email="true"
					       data-msg-required="<?php _e( 'Please give your email address.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
					       data-msg-email="<?php _e( 'Please enter a valid email address.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
					       type="email" id="cscf_email" name="cscf[email]"
					       value="<?php echo esc_attr( $contact->Email ); ?>"
					       placeholder="<?php _e( 'Your Email Address', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
						/>

                <span for="cscf_email" class="help-inline help-block error"
                      style="display:<?php echo isset( $contact->Errors['email'] ) ? 'block' : 'none'; ?>;">
                    <?php if ( isset( $contact->Errors['email'] ) ) {
	                    echo $contact->Errors['email'];
                    } ?>

			<?php if ( $confirmEmail ) { ?>

				<div class="control-group form-group<?php if ( isset( $contact->Errors['confirm-email'] ) ) {
					echo ' error has-error';
				} ?>">
					<?php _e( 'Confirm Email Address:', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>
					<div class="<?php echo cscf_PluginSettings::InputIcons() ? "input-group" : ""; ?>">
						<?php if ( cscf_PluginSettings::InputIcons() == true ) { ?>

						<?php } ?>
						<input class="form-control input-xlarge"
						       data-rule-required="true"
						       data-rule-email="true"
						       data-rule-equalTo="#cscf_email"
						       data-msg-required="<?php _e( 'Please enter the same email address again.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
						       data-msg-email="<?php _e( 'Please enter a valid email address.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
						       data-msg-equalTo="<?php _e( 'Please enter the same email address again.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
						       type="email" id="cscf_confirm-email" name="cscf[confirm-email]"
						       value="<?php echo esc_attr( $contact->ConfirmEmail ); ?>"
						       placeholder="<?php _e( 'Confirm Your Email Address', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
							/>

                <span for="cscf_confirm-email" class="help-inline help-block error"
                      style="display:<?php echo isset( $contact->Errors['confirm-email'] ) ? 'block' : 'none'; ?>;">
                    <?php if ( isset( $contact->Errors['confirm-email'] ) ) {
	                    echo $contact->Errors['confirm-email'];
                    } ?>

			<?php } ?>

			<div class="control-group form-group<?php if ( isset( $contact->Errors['message'] ) ) {
				echo ' error has-error';
			} ?>">
				<?php _e( 'Message:', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>
				<div class="<?php echo cscf_PluginSettings::InputIcons() ? "input-group" : ""; ?>">
					<?php if ( cscf_PluginSettings::InputIcons() == true ) { ?>

					<?php } ?>
					<textarea class="form-control input-xlarge"
					          data-rule-required="true"
					          data-msg-required="<?php _e( 'Please give a message.', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"
					          id="cscf_message" name="cscf[message]" rows="10"
					          placeholder="<?php _e( 'Your Message', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"><?php echo esc_textarea( $contact->Message ); ?></textarea>

					<span for="cscf_message" class="help-inline help-block error"
					      style="display:<?php echo isset( $contact->Errors['message'] ) ? 'block' : 'none'; ?>;">
                    <?php if ( isset( $contact->Errors['message'] ) ) {
	                    echo $contact->Errors['message'];
                    } ?>

			<?php if ( cscf_PluginSettings::EmailToSender() ) { ?>

				<div class="control-group form-group<?php if ( isset( $contact->Errors['email-sender'] ) ) {
					echo ' error has-error';
				} ?>">
					<?php _e( 'Send me a copy:', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>
					<div class="<?php echo cscf_PluginSettings::InputIcons() ? "input-group" : ""; ?>">
						<?php if ( cscf_PluginSettings::InputIcons() == true ) { ?>

						<?php } ?>
						<input <?php echo $contact->EmailToSender == true ? 'checked' : ''; ?> type="checkbox"
						                                                                       id="cscf_email-sender"
						                                                                       name="cscf[email-sender]">

						<span for="cscf_email-sender" class="help-inline help-block error"
						      style="display:<?php echo isset( $contact->Errors['email-sender'] ) ? 'block' : 'none'; ?>;">
                        <?php if ( isset( $contact->Errors['email-sender'] ) ) {
	                        echo $contact->Errors['email-sender'];
                        } ?>

			<?php } ?>

			<?php if ( $contact->RecaptchaPublicKey <> '' && $contact->RecaptchaPrivateKey <> '' ) { ?>

				<div class="control-group form-group<?php
				if ( isset( $contact->Errors['recaptcha'] ) ) {
					echo ' error has-error';
				} ?>">

						<div class="g-recaptcha" data-theme="<?php echo cscf_PluginSettings::Theme(); ?>"
						     data-sitekey="<?php echo $contact->RecaptchaPublicKey; ?>">

<?php if ( isset( $contact->Errors['recaptcha'] ) ) {
								echo $contact->Errors['recaptcha'];
							} ?>

										<iframe
											src="https://www.google.com/recaptcha/api/fallback?k=<?php echo $contact->RecaptchaPublicKey; ?>"
											frameborder="0" scrolling="no"
											style="width: 302px; height:422px; border-style: none;">

        <textarea id="g-recaptcha-response" name="g-recaptcha-response"
                  class="g-recaptcha-response"
                  style="width: 250px; height: 40px; border: 1px solid #c1c1c1;
                         margin: 10px 25px; padding: 0px; resize: none;">
        </textarea>

			<?php } ?>
			<input type="submit" id="cscf_SubmitButton" class="btn btn-default" value="<?php _e( 'Send Message', 'clean-and-simple-contact-form-by-meg-nicholas' ); ?>"/>
		</form>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LionFire.Collections;
using LionFire.Persistence;
using LionFire.Persistence.Handles;
using LionFire.Referencing;

namespace LionFire.ObjectBus.Handles
{
    public enum OBocTrackingState
    {
        Unspecified,
        Unchanged = 1 << 0,
        Added = 1 << 1,
        Removed = 1 << 2,
    }

    /// <summary>
    /// OBus Object Collection contains a collection of list entries (OBaseListEntry) representing the items within the folder at a OBase reference.
    /// (Examples: filesystem directory, database table.)
    /// </summary>
    /// <typeparam name="TListEntry"></typeparam>
    public abstract class ROBoc<TReference, T, TListEntry>
        : ReadHandle<TReference, T>
        , RC<T, TListEntry>
        where TReference : IReference<T>, IReference<INotifyingReadOnlyCollection<TListEntry>>
        where T : INotifyingReadOnlyCollection<TListEntry>
        where TListEntry : ICollectionEntry
    {
        #region Construction

        public ROBoc() { }

        /// <param name="reference">(Can be null)</param>
        public ROBoc(TReference reference) : base(reference)
        {
        }

        #endregion

        public IReadHandleBase<INotifyingReadOnlyCollection<T>> Handle { get; protected set; }
        public INotifyingReadOnlyCollection<TListEntry> Entries => Value;

        public int Count => Entries.Count;

        public abstract IReadHandle<T> this[string subpath] { get; }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        public abstract IEnumerator<T> GetEnumerator();

    }
}


text:
package nullable

import (
	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/runtime/protoimpl"
	"google.golang.org/protobuf/types/descriptorpb"
)

type Proto2 struct {
	OptionalBool    bool                                   `protobuf:"varint,100,opt,name=optional_bool"`
	OptionalInt32   int32                                  `protobuf:"varint,101,opt,name=optional_int32"`
	OptionalInt64   int64                                  `protobuf:"varint,102,opt,name=optional_int64"`
	OptionalUint32  uint32                                 `protobuf:"varint,103,opt,name=optional_uint32"`
	OptionalUint64  uint64                                 `protobuf:"varint,104,opt,name=optional_uint64"`
	OptionalFloat   float32                                `protobuf:"fixed32,105,opt,name=optional_float"`
	OptionalDouble  float64                                `protobuf:"fixed64,106,opt,name=optional_double"`
	OptionalString  string                                 `protobuf:"bytes,107,opt,name=optional_string"`
	OptionalBytes   []byte                                 `protobuf:"bytes,108,opt,name=optional_bytes"`
	OptionalEnum    descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,109,req,name=optional_enum"`
	OptionalMessage descriptorpb.FieldOptions              `protobuf:"bytes,110,req,name=optional_message"`

	RepeatedBool    []bool                                   `protobuf:"varint,200,rep,name=repeated_bool"`
	RepeatedInt32   []int32                                  `protobuf:"varint,201,rep,name=repeated_int32"`
	RepeatedInt64   []int64                                  `protobuf:"varint,202,rep,name=repeated_int64"`
	RepeatedUint32  []uint32                                 `protobuf:"varint,203,rep,name=repeated_uint32"`
	RepeatedUint64  []uint64                                 `protobuf:"varint,204,rep,name=repeated_uint64"`
	RepeatedFloat   []float32                                `protobuf:"fixed32,205,rep,name=repeated_float"`
	RepeatedDouble  []float64                                `protobuf:"fixed64,206,rep,name=repeated_double"`
	RepeatedString  []string                                 `protobuf:"bytes,207,rep,name=repeated_string"`
	RepeatedBytes   [][]byte                                 `protobuf:"bytes,208,rep,name=repeated_bytes"`
	RepeatedEnum    []descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,209,rep,name=repeated_enum"`
	RepeatedMessage []descriptorpb.FieldOptions              `protobuf:"bytes,210,rep,name=repeated_message"`

	MapBool    map[string]bool                                   `protobuf:"bytes,300,rep,name=map_bool" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapInt32   map[string]int32                                  `protobuf:"bytes,301,rep,name=map_int32" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapInt64   map[string]int64                                  `protobuf:"bytes,302,rep,name=map_int64" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapUint32  map[string]uint32                                 `protobuf:"bytes,303,rep,name=map_uint32" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapUint64  map[string]uint64                                 `protobuf:"bytes,304,rep,name=map_uint64" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapFloat   map[string]float32                                `protobuf:"bytes,305,rep,name=map_float" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
	MapDouble  map[string]float64                                `protobuf:"bytes,306,rep,name=map_double" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
	MapString  map[string]string                                 `protobuf:"bytes,307,rep,name=map_string" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
	MapBytes   map[string][]byte                                 `protobuf:"bytes,308,rep,name=map_bytes" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
	MapEnum    map[string]descriptorpb.FieldDescriptorProto_Type `protobuf:"bytes,309,rep,name=map_enum" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
	MapMessage map[string]descriptorpb.FieldOptions              `protobuf:"bytes,310,rep,name=map_message" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`

	OneofUnion isProto2_OneofUnion `protobuf_oneof:"oneof_union"`
}

func (x *Proto2) ProtoMessage()  {}
func (x *Proto2) Reset()         { *x = Proto2{} }
func (x *Proto2) String() string { return prototext.Format(protoimpl.X.ProtoMessageV2Of(x)) }
func (x *Proto2) XXX_OneofWrappers() []interface{} {
	return []interface{}{
		(*Proto2_OneofBool)(nil),
		(*Proto2_OneofInt32)(nil),
		(*Proto2_OneofInt64)(nil),
		(*Proto2_OneofUint32)(nil),
		(*Proto2_OneofUint64)(nil),
		(*Proto2_OneofFloat)(nil),
		(*Proto2_OneofDouble)(nil),
		(*Proto2_OneofString)(nil),
		(*Proto2_OneofBytes)(nil),
		(*Proto2_OneofEnum)(nil),
		(*Proto2_OneofMessage)(nil),
	}
}

type isProto2_OneofUnion interface{ isProto2_OneofUnion() }

type Proto2_OneofBool struct {
	OneofBool bool `protobuf:"varint,400,opt,name=oneof_bool,oneof"`
}
type Proto2_OneofInt32 struct {
	OneofInt32 int32 `protobuf:"varint,401,opt,name=oneof_int32,oneof"`
}
type Proto2_OneofInt64 struct {
	OneofInt64 int64 `protobuf:"varint,402,opt,name=oneof_int64,oneof"`
}
type Proto2_OneofUint32 struct {
	OneofUint32 uint32 `protobuf:"varint,403,opt,name=oneof_uint32,oneof"`
}
type Proto2_OneofUint64 struct {
	OneofUint64 uint64 `protobuf:"varint,404,opt,name=oneof_uint64,oneof"`
}
type Proto2_OneofFloat struct {
	OneofFloat float32 `protobuf:"fixed32,405,opt,name=oneof_float,oneof"`
}
type Proto2_OneofDouble struct {
	OneofDouble float64 `protobuf:"fixed64,406,opt,name=oneof_double,oneof"`
}
type Proto2_OneofString struct {
	OneofString string `protobuf:"bytes,407,opt,name=oneof_string,oneof"`
}
type Proto2_OneofBytes struct {
	OneofBytes []byte `protobuf:"bytes,408,opt,name=oneof_bytes,oneof"`
}
type Proto2_OneofEnum struct {
	OneofEnum descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,409,opt,name=oneof_enum,oneof"`
}
type Proto2_OneofMessage struct {
	OneofMessage descriptorpb.FieldOptions `protobuf:"bytes,410,opt,name=oneof_message,oneof"`
}

func (*Proto2_OneofBool) isProto2_OneofUnion()    {}
func (*Proto2_OneofInt32) isProto2_OneofUnion()   {}
func (*Proto2_OneofInt64) isProto2_OneofUnion()   {}
func (*Proto2_OneofUint32) isProto2_OneofUnion()  {}
func (*Proto2_OneofUint64) isProto2_OneofUnion()  {}
func (*Proto2_OneofFloat) isProto2_OneofUnion()   {}
func (*Proto2_OneofDouble) isProto2_OneofUnion()  {}
func (*Proto2_OneofString) isProto2_OneofUnion()  {}
func (*Proto2_OneofBytes) isProto2_OneofUnion()   {}
func (*Proto2_OneofEnum) isProto2_OneofUnion()    {}
func (*Proto2_OneofMessage) isProto2_OneofUnion() {}

type Proto3 struct {
	OptionalBool    bool                                   `protobuf:"varint,100,opt,name=optional_bool,proto3"`
	OptionalInt32   int32                                  `protobuf:"varint,101,opt,name=optional_int32,proto3"`
	OptionalInt64   int64                                  `protobuf:"varint,102,opt,name=optional_int64,proto3"`
	OptionalUint32  uint32                                 `protobuf:"varint,103,opt,name=optional_uint32,proto3"`
	OptionalUint64  uint64                                 `protobuf:"varint,104,opt,name=optional_uint64,proto3"`
	OptionalFloat   float32                                `protobuf:"fixed32,105,opt,name=optional_float,proto3"`
	OptionalDouble  float64                                `protobuf:"fixed64,106,opt,name=optional_double,proto3"`
	OptionalString  string                                 `protobuf:"bytes,107,opt,name=optional_string,proto3"`
	OptionalBytes   []byte                                 `protobuf:"bytes,108,opt,name=optional_bytes,proto3"`
	OptionalEnum    descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,109,req,name=optional_enum,proto3"`
	OptionalMessage descriptorpb.FieldOptions              `protobuf:"bytes,110,req,name=optional_message,proto3"`

	RepeatedBool    []bool                                   `protobuf:"varint,200,rep,name=repeated_bool,proto3"`
	RepeatedInt32   []int32                                  `protobuf:"varint,201,rep,name=repeated_int32,proto3"`
	RepeatedInt64   []int64                                  `protobuf:"varint,202,rep,name=repeated_int64,proto3"`
	RepeatedUint32  []uint32                                 `protobuf:"varint,203,rep,name=repeated_uint32,proto3"`
	RepeatedUint64  []uint64                                 `protobuf:"varint,204,rep,name=repeated_uint64,proto3"`
	RepeatedFloat   []float32                                `protobuf:"fixed32,205,rep,name=repeated_float,proto3"`
	RepeatedDouble  []float64                                `protobuf:"fixed64,206,rep,name=repeated_double,proto3"`
	RepeatedString  []string                                 `protobuf:"bytes,207,rep,name=repeated_string,proto3"`
	RepeatedBytes   [][]byte                                 `protobuf:"bytes,208,rep,name=repeated_bytes,proto3"`
	RepeatedEnum    []descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,209,rep,name=repeated_enum,proto3"`
	RepeatedMessage []descriptorpb.FieldOptions              `protobuf:"bytes,210,rep,name=repeated_message,proto3"`

	MapBool    map[string]bool                                   `protobuf:"bytes,300,rep,name=map_bool,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapInt32   map[string]int32                                  `protobuf:"bytes,301,rep,name=map_int32,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapInt64   map[string]int64                                  `protobuf:"bytes,302,rep,name=map_int64,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapUint32  map[string]uint32                                 `protobuf:"bytes,303,rep,name=map_uint32,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapUint64  map[string]uint64                                 `protobuf:"bytes,304,rep,name=map_uint64,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapFloat   map[string]float32                                `protobuf:"bytes,305,rep,name=map_float,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"fixed32,2,opt,name=value,proto3"`
	MapDouble  map[string]float64                                `protobuf:"bytes,306,rep,name=map_double,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"fixed64,2,opt,name=value,proto3"`
	MapString  map[string]string                                 `protobuf:"bytes,307,rep,name=map_string,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
	MapBytes   map[string][]byte                                 `protobuf:"bytes,308,rep,name=map_bytes,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
	MapEnum    map[string]descriptorpb.FieldDescriptorProto_Type `protobuf:"bytes,309,rep,name=map_enum,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
	MapMessage map[string]descriptorpb.FieldOptions              `protobuf:"bytes,310,rep,name=map_message,proto3" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`

	OneofUnion isProto3_OneofUnion `protobuf_oneof:"oneof_union"`
}

func (x *Proto3) ProtoMessage()  {}
func (x *Proto3) Reset()         { *x = Proto3{} }
func (x *Proto3) String() string { return prototext.Format(protoimpl.X.ProtoMessageV2Of(x)) }
func (x *Proto3) XXX_OneofWrappers() []interface{} {
	return []interface{}{
		(*Proto3_OneofBool)(nil),
		(*Proto3_OneofInt32)(nil),
		(*Proto3_OneofInt64)(nil),
		(*Proto3_OneofUint32)(nil),
		(*Proto3_OneofUint64)(nil),
		(*Proto3_OneofFloat)(nil),
		(*Proto3_OneofDouble)(nil),
		(*Proto3_OneofString)(nil),
		(*Proto3_OneofBytes)(nil),
		(*Proto3_OneofEnum)(nil),
		(*Proto3_OneofMessage)(nil),
	}
}

type isProto3_OneofUnion interface{ isProto3_OneofUnion() }

type Proto3_OneofBool struct {
	OneofBool bool `protobuf:"varint,400,opt,name=oneof_bool,proto3,oneof"`
}
type Proto3_OneofInt32 struct {
	OneofInt32 int32 `protobuf:"varint,401,opt,name=oneof_int32,proto3,oneof"`
}
type Proto3_OneofInt64 struct {
	OneofInt64 int64 `protobuf:"varint,402,opt,name=oneof_int64,proto3,oneof"`
}
type Proto3_OneofUint32 struct {
	OneofUint32 uint32 `protobuf:"varint,403,opt,name=oneof_uint32,proto3,oneof"`
}
type Proto3_OneofUint64 struct {
	OneofUint64 uint64 `protobuf:"varint,404,opt,name=oneof_uint64,proto3,oneof"`
}
type Proto3_OneofFloat struct {
	OneofFloat float32 `protobuf:"fixed32,405,opt,name=oneof_float,proto3,oneof"`
}
type Proto3_OneofDouble struct {
	OneofDouble float64 `protobuf:"fixed64,406,opt,name=oneof_double,proto3,oneof"`
}
type Proto3_OneofString struct {
	OneofString string `protobuf:"bytes,407,opt,name=oneof_string,proto3,oneof"`
}
type Proto3_OneofBytes struct {
	OneofBytes []byte `protobuf:"bytes,408,opt,name=oneof_bytes,proto3,oneof"`
}
type Proto3_OneofEnum struct {
	OneofEnum descriptorpb.FieldDescriptorProto_Type `protobuf:"varint,409,opt,name=oneof_enum,proto3,oneof"`
}
type Proto3_OneofMessage struct {
	OneofMessage descriptorpb.FieldOptions `protobuf:"bytes,410,opt,name=oneof_message,proto3,oneof"`
}

func (*Proto3_OneofBool) isProto3_OneofUnion()    {}
func (*Proto3_OneofInt32) isProto3_OneofUnion()   {}
func (*Proto3_OneofInt64) isProto3_OneofUnion()   {}
func (*Proto3_OneofUint32) isProto3_OneofUnion()  {}
func (*Proto3_OneofUint64) isProto3_OneofUnion()  {}
func (*Proto3_OneofFloat) isProto3_OneofUnion()   {}
func (*Proto3_OneofDouble) isProto3_OneofUnion()  {}
func (*Proto3_OneofString) isProto3_OneofUnion()  {}
func (*Proto3_OneofBytes) isProto3_OneofUnion()   {}
func (*Proto3_OneofEnum) isProto3_OneofUnion()    {}
func (*Proto3_OneofMessage) isProto3_OneofUnion() {}

type Methods struct {
	OptionalInt32 int32 `protobuf:"varint,101,opt,name=optional_int32"`
}

func (x *Methods) ProtoMessage()  {}
func (x *Methods) Reset()         { *x = Methods{} }
func (x *Methods) String() string { return prototext.Format(protoimpl.X.ProtoMessageV2Of(x)) }

func (x *Methods) Marshal() ([]byte, error) {
	var b []byte
	b = protowire.AppendTag(b, 101, protowire.VarintType)
	b = protowire.AppendVarint(b, uint64(x.OptionalInt32))
	return b, nil
}

func (x *Methods) Unmarshal(b []byte) error {
	for len(b) > 0 {
		num, typ, n := protowire.ConsumeTag(b)
		if n < 0 {
			return protowire.ParseError(n)
		}
		b = b[n:]
		if num != 101 || typ != protowire.VarintType {
			n = protowire.ConsumeFieldValue(num, typ, b)
			if n < 0 {
				return protowire.ParseError(n)
			}
			b = b[n:]
			continue
		}
		v, n := protowire.ConsumeVarint(b)
		if n < 0 {
			return protowire.ParseError(n)
		}
		b = b[n:]
		x.OptionalInt32 = int32(v)
	}
	return nil
}


text:
package com.stulsoft.exercises.list

/** Generate the combinations of K distinct objects chosen from the N elements of a list.
  *
  * <p>
  * Example:
  * {{{combinations(3, List('a, 'b, 'c, 'd, 'e, 'f))}}}
  * {{{List[List[Symbol]] = List(List('a, 'b, 'c), List('a, 'b, 'd), List('a, 'b, 'e), ...}}}
  *
  * @author Yuriy Stul.
  */
object P26GenerateCombinations extends App {

  test(3, List(1, 2, 3, 4, 5))

  def test[A](n: Int, ls: List[A]): Unit = {
    val r1 = combinations1(n, ls)
    println(s"(1) $n from $ls -> ${r1.length}s $r1")
  }

  /** Builds combinations
    *
    * @param n  number of elements in combinations
    * @param ls the list
    * @tparam A the list items type
    * @return list of combinations
    */
  def combinations1[A](n: Int, ls: List[A]): List[List[A]] = {
    /** flatMapSublists is like list.flatMap, but instead of passing each element
      * to the function, it passes successive sublists of L.
      */
    def flatMapSublists[B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
      ls match {
        case Nil => Nil
        case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f) // There are two patterns
      }

    if (n == 0) List(Nil)
    else flatMapSublists(ls) { sl =>
      combinations1(n - 1, sl.tail) map {
        sl.head :: _
      }
    }
  }
}


text:
package sg.yikjiun.scf4j.set;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Lee Yik Jiun
 */
public class JDKSetFactory implements SetFactoryDelegate {
    public IntSet createIntHashSet() {
        Set<Integer> set = new HashSet<Integer>();
        return new JDKIntSetAdapter(set);
    }

    public ByteSet createByteHashSet() {
        Set<Byte> set = new HashSet<Byte>();
        return new JDKByteSetAdapter(set);
    }

    public ShortSet createShortHashSet() {
        Set<Short> set = new HashSet<Short>();
        return new JDKShortSetAdapter(set);
    }

    public LongSet createLongHashSet() {
        Set<Long> set = new HashSet<Long>();
        return new JDKLongSetAdapter(set);
    }

    public DoubleSet createDoubleHashSet() {
        Set<Double> set = new HashSet<Double>();
        return new JDKDoubleSetAdapter(set);
    }

    public FloatSet createFloatHashSet() {
        Set<Float> set = new HashSet<Float>();
        return new JDKFloatSetAdapter(set);
    }

    public CharSet createCharHashSet() {
        Set<Character> set = new HashSet<Character>();
        return new JDKCharSetAdapter(set);
    }

    public BooleanSet createBooleanHashSet() {
        Set<Boolean> set = new HashSet<Boolean>();
        return new JDKBooleanSetAdapter(set);
    }

    public IntSet createIntTreeSet() {
        Set<Integer> set = new TreeSet<Integer>();
        return new JDKIntSetAdapter(set);
    }

    public ByteSet createByteTreeSet() {
        Set<Byte> set = new TreeSet<Byte>();
        return new JDKByteSetAdapter(set);
    }

    public ShortSet createShortTreeSet() {
        Set<Short> set = new TreeSet<Short>();
        return new JDKShortSetAdapter(set);
    }

    public LongSet createLongTreeSet() {
        Set<Long> set = new TreeSet<Long>();
        return new JDKLongSetAdapter(set);
    }

    public DoubleSet createDoubleTreeSet() {
        Set<Double> set = new TreeSet<Double>();
        return new JDKDoubleSetAdapter(set);
    }

    public FloatSet createFloatTreeSet() {
        Set<Float> set = new TreeSet<Float>();
        return new JDKFloatSetAdapter(set);
    }

    public CharSet createCharTreeSet() {
        Set<Character> set = new TreeSet<Character>();
        return new JDKCharSetAdapter(set);
    }

    public BooleanSet createBooleanTreeSet() {
        Set<Boolean> set = new TreeSet<Boolean>();
        return new JDKBooleanSetAdapter(set);
    }
}


text:
//=====================================================================
//
//File:      $RCSfile: CanvasEditorReloadContentsTest.java,v $
//Version:   $Revision: 1.15 $
//Modified:  $Date: 2013/05/10 05:41:50 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================

package org.xtuml.bp.ui.canvas.test;

import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.InstanceStateMachine_c;
import org.xtuml.bp.core.ModelClass_c;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.StateMachineState_c;
import org.xtuml.bp.core.StateMachine_c;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.test.common.BaseTest;
import org.xtuml.bp.test.common.CanvasTestUtils;
import org.xtuml.bp.test.common.OrderedRunner;
import org.xtuml.bp.test.common.UITestingUtilities;
import org.xtuml.bp.ui.canvas.GraphicalElement_c;
import org.xtuml.bp.ui.canvas.Model_c;
import org.xtuml.bp.ui.canvas.Ooaofgraphics;
import org.xtuml.bp.ui.canvas.Shape_c;
import org.xtuml.bp.ui.graphics.editor.GraphicalEditor;

import junit.framework.TestCase;

/**
 * Performs tests related to the updating of an editor's
 * contents when a model is reloaded from disk.
 */
@RunWith(OrderedRunner.class)
public class CanvasEditorReloadContentsTest extends CanvasTest
{
    /**
     * The name of the test domain used during these tests.
     */
    private static final String testModelName = "odms";

    /**
     * Constructor.
     */
    public CanvasEditorReloadContentsTest()
    {
        super(null, null);
    }

    /* (non-Javadoc)
     * @see org.xtuml.bp.ui.canvas.test.CanvasTest#getResultName()
     */
    protected String getResultName()
    {
        return null;
    }

    @Override
    @Before
	public void setUp() throws Exception {
    	super.setUp();
    	Ooaofooa.setPersistEnabled(true);
    }

    @After
	public void tearDown() throws Exception {
    	super.tearDown();
    	Ooaofooa.setPersistEnabled(false);
    }

    /**
     * For issue 780.  Drags a shape on a domain diagram, then copies
     * over the domain's changed file with the original version,
     * checking to see that the shape reverts to its original position
     * due to the domain being reloaded.
     * @throws IOException
     * @throws CoreException
     */
    @Test
	public void testEditorUpdatesOnReload() throws CoreException, IOException
    {
        // make sure the user isn't prompted to do a parse all
        CorePlugin.enableParseAllOnResourceChange();

        // setup the test project and model
        loadProject(testModelName);

        BaseTest.dispatchEvents(0);

        // find a subsystem's shape that is in the canvas
        Package_c subsystem = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() {

			@Override
			public boolean evaluate(Object candidate) {
				return ((Package_c) candidate).getName().equals("Odms");
			}
		});
        // open an editor on the test domain
        GraphicalEditor editor = UITestingUtilities.getGraphicalEditorFor(subsystem, false);
        Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(modelRoot.getId());
        GraphicalElement_c element =
        	CanvasTestUtils.getGraphicalElement(graphicsRoot, subsystem);
        Shape_c shape = Shape_c.getOneGD_SHPOnR2(element);
        UITestingUtilities.addElementToGraphicalSelection(subsystem);
        // drag the subsystem's shape a bit, then let go to get the
        // change persisted
        Model_c canvas = editor.getModel();
        Point oldCenter = CanvasTestUtils.getShapeCenter(shape);
        Point mouse = CanvasTestUtils.convertToMouseCoor(oldCenter, canvas);
        CanvasTestUtils.createMouseEvent(
            mouse.x, mouse.y, "MouseDown");
        int dx = 30, dy = 30;
        CanvasTestUtils.createMouseEvent(
            mouse.x + dx, mouse.y + dy, "MouseMove");
        CanvasTestUtils.createMouseEvent(
            mouse.x + dx, mouse.y + dy, "MouseUp");
        Point draggedCenter = CanvasTestUtils.getShapeCenter(shape);
        draggedCenter = CanvasTestUtils.convertToMouseCoor(draggedCenter, canvas);
        assertTrue("Drag had no effect", !draggedCenter.equals(oldCenter));
        BaseTest.dispatchEvents(0);
        // restore from local history
        IFile file = ((NonRootModelElement) Model_c.getOneGD_MDOnR1(element).getRepresents()).getFile();
        IFileState[] history = file.getHistory(new NullProgressMonitor());
        if (history.length > 0) {
        	file.setContents(history[0], IFile.FORCE, new NullProgressMonitor());
        }

        // find the same subsystem's shape (once again) that
        // is presumably in the editor's new canvas (as the shape
        // would not be created if there were not also a new canvas
        // created)
        subsystem = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() {

			@Override
			public boolean evaluate(Object candidate) {
				return ((Package_c) candidate).getName().equals("Odms");
			}
		});
        element = CanvasTestUtils.getGraphicalElement(graphicsRoot, subsystem);
        shape = Shape_c.getOneGD_SHPOnR2(element);
        assertNotNull("No new shape (and therefore, canvas) after reload", shape);

        // check that the shape reverted to its original position
        // due to the reload
        Point finalCenter = CanvasTestUtils.getShapeCenter(shape);
        assertTrue("Shape position did not revert after reload",
            finalCenter.equals(oldCenter));
    }

    /**
     * For issue MFP issue 54.  If the data for a state machine changes,
     * make sure the canvas editor doesn't close.
     * @throws IOException
     * @throws CoreException
     */
    @Test
	public void testISMEditorStaysOpenOnReload() throws CoreException, IOException
    {
		// setup the test project and model
		loadProject(testModelName);

		// open an editor on the test domain
		ModelClass_c mc = ModelClass_c.ModelClassInstance(modelRoot,
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						if (((ModelClass_c) candidate).getName().equals("Disk"))
							return true;
						else
							return false;
					}
        } );
    	InstanceStateMachine_c uut = InstanceStateMachine_c.getOneSM_ISMOnR518(mc);
    	TestCase.assertNotNull(uut);
    	CanvasTestUtils.openCanvasEditor(uut);
    	BaseTest.dispatchEvents(0);
    	GraphicalEditor editor = CanvasTestUtils.getCanvasEditor("Disk");

    	BaseTest.dispatchEvents(0);
        // find a state's shape that is in the canvas
        StateMachineState_c state = StateMachineState_c.getOneSM_STATEOnR501(
        		StateMachine_c.getOneSM_SMOnR517(uut));
        moveShapeInEditor(editor, state);

        // replace the ISM file with previous from local history
        IFileState[] fh = state.getFile().getHistory(null);
        state.getFile().setContents(fh[0], true, true, null);

    	BaseTest.dispatchEvents(0);

        // verify that the canvas editor is still open
    	GraphicalEditor afterEditor = CanvasTestUtils.getCanvasEditor("Disk");
        assertNotNull("Editor closed by file reload", afterEditor);
    }

    /**
     * Move the shape that represents me in the editor
     *
     * @param editor
     * @param me
     * @return the center of the shape before the move
     */
	private Point moveShapeInEditor(GraphicalEditor editor, NonRootModelElement me) {
		editor.zoomAll();
    	BaseTest.dispatchEvents(0);

		Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(modelRoot.getId());
        GraphicalElement_c element =
        	CanvasTestUtils.getGraphicalElement(graphicsRoot, me);
        Shape_c shape = Shape_c.getOneGD_SHPOnR2(element);

        // drag the state's shape a bit, then let go to get the
        // change persisted
        Model_c canvas = editor.getModel();
        Point oldCenter = CanvasTestUtils.getShapeCenter(shape);
        Point mouse = CanvasTestUtils.convertToMouseCoor(oldCenter, canvas);
        CanvasTestUtils.createMouseEvent(
            mouse.x, mouse.y, "MouseDown");
        int dx = 20, dy = 20;
        CanvasTestUtils.createMouseEvent(
            mouse.x + dx, mouse.y + dy, "MouseMove");
        CanvasTestUtils.createMouseEvent(
            mouse.x + dx, mouse.y + dy, "MouseUp");
    	BaseTest.dispatchEvents(0);

        Point draggedCenter = CanvasTestUtils.getShapeCenter(shape);
        assertTrue("Drag had no effect", !draggedCenter.equals(oldCenter));
        return oldCenter;
	}

}


text:
from __future__ import print_function
from __future__ import absolute_import
import sys, datetime
from . import FlyMovieFormat

def main():
    try:
        filename1 = sys.argv[1]
    except:
        print("Usage: fmf_info fmf_filename")
        sys.exit()

    fly_movie = FlyMovieFormat.FlyMovie(filename1)
    ts = fly_movie.get_all_timestamps()
    dt0 = datetime.datetime.fromtimestamp(ts[0])
    dt1 = datetime.datetime.fromtimestamp(ts[-1])
    print(
        "%s: %d frames, %d x %d pixels, %s format (%d bpp), timestamps range %.1f (%s) to %.1f (%s)"
        % (
            filename1,
            fly_movie.get_n_frames(),
            fly_movie.get_width(),
            fly_movie.get_height(),
            fly_movie.get_format(),
            fly_movie.get_bits_per_pixel(),
            ts[0],
            dt0.isoformat(),
            ts[-1],
            dt1.isoformat(),
        )
    )

if __name__ == "__main__":
    main()


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <solid android:color="@color/background2" />
        <stroke android:width="2dp" android:color="#808080" />

        <padding android:bottom="4dp" android:left="3dp" android:right="3dp" android:top="6dp" />

        <corners android:radius="10px"/>
    </shape></item>
    <item><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <solid android:color="@color/background2" />
        <stroke android:width="1dp" android:color="#808080" />

        <padding android:bottom="4dp" android:left="3dp" android:right="3dp" android:top="6dp" />

        <corners android:radius="1px"/>
    </shape></item>
</selector>


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}

module Server.Web where

import Data.String (fromString)

import Web.Scotty

import Network.HTTP.Types                   (status404)
import Network.Wai.Middleware.RequestLogger (logStdoutDev)

import Server.Types
import Server.ProgramOptions (ProgramOptions(..))
import Server.Stream         (getStream)
import Server.HLSProxy       (getProxy)

import Control.Monad.IO.Class  (liftIO)
import Control.Concurrent.MVar (MVar(..))

runServer :: MVar ServerState -> ProgramOptions -> IO ()
runServer state options = scotty webPort $ do
  middleware logStdoutDev

  get "/:channel" $ do
    channel <- param "channel"

    maybeStream <- liftIO $ getStream options channel state

    withJustOr404 json maybeStream

  get playlistRoutePattern $ do
    channel <- param "channel"
    quality <- param "quality"

    mbProxy <- liftIO $ getProxy options channel quality state

    withJustOr404 serveProxy mbProxy

  where
    ProgramOptions{indexFileName, webPort} = options

    playlistRoutePattern = fromString $
      "/:channel/:quality/" ++ indexFileName

    withJustOr404 :: (a -> ActionM ()) -> Maybe a -> ActionM ()
    withJustOr404 = maybe $ status status404

    serveProxy :: HLSProxy -> ActionM ()
    serveProxy proxy = do
      addHeader "Content-Type" "application/vnd.apple.mpegurl"
      file $ indexPath proxy


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

namespace OLEDB.Test.ModuleCore
{
    ////////////////////////////////////////////////////////////////
    // CTestBase
    //
    ////////////////////////////////////////////////////////////////
    public abstract class CTestBase : IComparable
    {
        //Defines
        public const int TEST_FAIL = (int)tagVARIATION_STATUS.eVariationStatusFailed;
        public const int TEST_PASS = (int)tagVARIATION_STATUS.eVariationStatusPassed;
        public const int TEST_SKIPPED = (int)tagVARIATION_STATUS.eVariationStatusNotRun;
        public const int TEST_NOTFOUND = (int)tagVARIATION_STATUS.eVariationStatusNonExistent;
        public const int TEST_UNKNOWN = (int)tagVARIATION_STATUS.eVariationStatusUnknown;
        public const int TEST_TIMEOUT = (int)tagVARIATION_STATUS.eVariationStatusTimedOut;
        public const int TEST_WARNING = (int)tagVARIATION_STATUS.eVariationStatusConformanceWarning;
        public const int TEST_EXCEPTION = (int)tagVARIATION_STATUS.eVariationStatusException;
        public const int TEST_ABORTED = (int)tagVARIATION_STATUS.eVariationStatusAborted;

        //Data
        private CTestBase _parent;
        private List<object> _children;
        private CAttrBase _attribute;

        //Constructor
        public CTestBase(string desc)
            : this(null, desc)
        {
        }

        //Constructor
        public CTestBase(string name, string desc)
        {
            //Now set the passed in names.
            if (name != null)
                this.Name = name;
            if (this.Name == null) this.Name = "No Name Provided";
            if (desc != null)
                this.Desc = desc;
        }

        //Accessors
        public virtual CAttrBase Attribute
        {
            get
            {
                if (_attribute == null)
                    _attribute = CreateAttribute();
                return _attribute;
            }
            set { _attribute = value; }
        }

        protected abstract CAttrBase CreateAttribute();

        //Note: These are just a mere convenience to access the attribute values
        //for this particular object.  Also note that for non-attribute based
        //scenarios (dynamic), the attribute class will be created just to hold
        //the values
        public object Param
        {
            get { return Attribute.Param; }
            set { Attribute.Param = value; }
        }

        public object[] Params
        {
            get { return Attribute.Params; }
            set { Attribute.Params = value; }
        }

        public int id
        {
            get { return Attribute.id; }
            set { Attribute.id = value; }
        }

        public int Pri
        {
            get { return Attribute.Pri; }
            set { Attribute.Pri = value; }
        }

        public int Priority //Alias for Pri
        {
            get { return Attribute.Pri; }
            set { Attribute.Pri = value; }
        }

        public string Name
        {
            get { return Attribute.Name; }
            set { Attribute.Name = value; }
        }

        public string Desc
        {
            get { return Attribute.Desc; }
            set { Attribute.Desc = value; }
        }

        public bool Implemented
        {
            get { return Attribute.Implemented; }
            set { Attribute.Implemented = value; }
        }

        public bool Skipped
        {
            get { return Attribute.Skipped; }
            set { Attribute.Skipped = value; }
        }

        public bool Error
        {
            get { return Attribute.Error; }
            set { Attribute.Error = value; }
        }

        public SecurityFlags Security
        {
            get { return Attribute.Security; }
            set { Attribute.Security = value; }
        }

        public bool Inheritance
        {
            get { return Attribute.Inheritance; }
            set { Attribute.Inheritance = value; }
        }

        public string FilterCriteria
        {
            get { return Attribute.FilterCriteria; }
            set { Attribute.FilterCriteria = value; }
        }

        public string Language
        {
            get { return Attribute.Language; }
            set { Attribute.Language = value; }
        }

        public string[] Languages
        {
            get { return Attribute.Languages; }
            set { Attribute.Languages = value; }
        }

        public string Xml
        {
            get { return Attribute.Xml; }
            set { Attribute.Xml = value; }
        }

        protected CTestBase Parent
        {
            get { return _parent; }
            set { _parent = value; }
        }

        public string Filter
        {
            get { return Attribute.Filter; }
            set { Attribute.Filter = value; }
        }

        public List<object> Children
        {
            get
            {
                //Deferred Creation of the children.
                if (_children == null)
                    _children = new List<object>();
                return _children;
            }
            set { _children = value; }
        }

        protected virtual void UpdateAttributes()
        {
        }

        protected virtual void DetermineChildren()
        {
            //Override this method if this node has children
        }

        protected void AddChild(CTestBase child)
        {
            //Setup the parent
            child.Parent = this;

            //Inheritance of attributes
            child.Attribute.Parent = this.Attribute;

            //Adjust the Id (if not set)
            if (child.id <= 0)
                child.id = Children.Count + 1;

            //Only add implemented items
            //Note: we still increment id counts, to save the 'spot' once they are implemented
            if (child.Implemented || CModInfo.IncludeNotImplemented)
            {
                //Determine any children of this node (before adding it)
                //Note: We don't call 'determinechildren' from within the (testcase) constructor
                //since none of the attributes/properties are setup until now.  So as soon as we
                //setup that information then we call determinechildren which when implemented
                //for dynamic tests can now look at those properties (otherwise they wouldn't be setup
                //until after the constructor returns).
                child.DetermineChildren();

                //Add it to our list...
                Children.Add(child);
            }
        }

        public virtual void AddChildren()
        {
        }

        //ITestCase implementation
        public string GetName()
        {
            return Name;
        }

        public string GetDescription()
        {
            return Desc;
        }

        public virtual int Init(object o)
        {
            //Note: This version is the only override-able Init, since the other one
            //automatically handles the exception you might throw from this function
            //Note: If you override this function, (as with most overrides) make sure you call the base.
            return TEST_PASS;
        }

        public int Init()
        {
            try
            {
                //Skipped
                if (this.Skipped || !this.Implemented)
                    return TEST_SKIPPED;

                return Init(Param);
            }
            catch (Exception e)
            {
                return HandleException(e);
            }

        }

        public virtual int Terminate(object o)
        {
            //Note: This version is the only override-able Terminate, since the other one
            //automatically handles the exception you might throw from this function
            //Note: If you override this function, (as with most overrides) make sure you call the base.
            return TEST_PASS;
        }

        public bool Terminate()
        {
            bool bResult = false;
            try
            {
                //Skipped
                if (this.Skipped || !this.Implemented)
                    return true;

                if (Terminate(Param) == TEST_PASS)
                    bResult = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                HandleException(e);
            }

            try
            {
                //Clear any previous existing info (in the static class).
                if (this is CTestModule)
                {
                    //Note: We actually have to clear these "statics" since they are not cleaned up
                    //until the process exits.  Which means that if you run again, in an apartment model
                    //thread it will try to release these when setting them which is not allowed to
                    //call a method on an object created in another apartment
                    CModInfo.Dispose();
                }
            }
            catch (Exception e)
            {
                HandleException(e);
            }

            //This is also a good point to hint to the GC to free up any unused memory
            //at the end of each TestCase and the end of each module.
            GC.Collect();
            GC.WaitForPendingFinalizers();
            return bResult;
        }

        public virtual tagVARIATION_STATUS Execute()
        {
            return tagVARIATION_STATUS.eVariationStatusPassed;
        }
        public int CompareTo(object o)
        {
            return this.id.CompareTo(((CTestBase)o).id);
        }

        public static int HandleException(Exception e)
        {
            //TargetInvocationException is almost always the outer
            //since we call the variation through late binding
            if (e.InnerException != null)
                e = e.InnerException;

            int eResult = TEST_FAIL;
            object actual = e.GetType();
            object expected = null;
            string message = e.Message;
            tagERRORLEVEL eErrorLevel = tagERRORLEVEL.HR_FAIL;

            if (e is CTestException)
            {
                CTestException eTest = (CTestException)e;

                //Setup more meaningful info
                actual = eTest.Actual;
                expected = eTest.Expected;
                eResult = eTest.Result;
                switch (eResult)
                {
                    case TEST_PASS:
                    case TEST_SKIPPED:
                        return eResult; //were done

                    case TEST_WARNING:
                        eErrorLevel = tagERRORLEVEL.HR_WARNING;
                        break;
                };
            }

            //Note: We don't use Exception.ToString as the details for the log since that also includes
            //the message text (again).  Normally this isn't a problem but if you throw a good message
            //(multiple lines) it show up twice and is confusing.  So we will strictly use the
            //StackTrace as the details and roll our own message (which also include inner exception
            //messages).
            Exception inner = e.InnerException;
            CError.Log(actual, expected, e.Source, message, e.StackTrace, eErrorLevel);

            while (inner != null)
            {
                CError.WriteLine("\n INNER EXCEPTION :");
                CError.Log(actual, expected, inner.Source, inner.Message, inner.StackTrace, eErrorLevel);
                inner = inner.InnerException;
            }

            return eResult;
        }
    }
}


text:
import unittest

from scripts.migrate_to_whatsapp_templates.prebirth3 import Prebirth3Migration

class Testprebirth3(unittest.TestCase):
    def setUp(self):
        self.prebirth3 = Prebirth3Migration()

    def test_sequence_number_to_weeks(self):
        """
        Given a certain sequence number for the prebirth 1 messageset, it should return
        the correct number of weeks pregnant
        """
        self.assertEqual(self.prebirth3.sequence_number_to_weeks(1), 36)
        self.assertEqual(self.prebirth3.sequence_number_to_weeks(2), 36)
        self.assertEqual(self.prebirth3.sequence_number_to_weeks(3), 36)
        self.assertEqual(self.prebirth3.sequence_number_to_weeks(14), 40)
        self.assertEqual(self.prebirth3.sequence_number_to_weeks(15), 40)

    def test_get_template_variables(self):
        message = {
            "id": "1",
            "messageset": "2",
            "sequence_number": "3",
            "lang": "zul_ZA",
            "text_content": "test",
            "binary_content": "",
            "metadata": "{}",
        }
        self.assertEqual(self.prebirth3.get_template_variables(message), ["36", "test"])


text:
package com.databricks.spark.csv

import java.io.IOException
import java.text.SimpleDateFormat

import scala.collection.JavaConversions._
import scala.util.control.NonFatal

import org.apache.commons.csv._
import org.apache.hadoop.fs.Path
import org.slf4j.LoggerFactory

import org.apache.spark.rdd.RDD
import org.apache.spark.sql._
import org.apache.spark.sql.sources.{PrunedScan, BaseRelation, InsertableRelation, TableScan}
import org.apache.spark.sql.types._
import com.databricks.spark.csv.readers.{BulkCsvReader, LineCsvReader}
import com.databricks.spark.csv.util._

case class CsvRelation protected[spark] (
    baseRDD: () => RDD[String],
    location: Option[String],
    useHeader: Boolean,
    delimiter: Char,
    quote: Character,
    escape: Character,
    comment: Character,
    parseMode: String,
    parserLib: String,
    ignoreLeadingWhiteSpace: Boolean,
    ignoreTrailingWhiteSpace: Boolean,
    treatEmptyValuesAsNulls: Boolean,
    userSchema: StructType = null,
    inferCsvSchema: Boolean,
    codec: String = null,
    nullValue: String = "",
    dateFormat: String = null,
    maxCharsPerCol: Int = 100000)(@transient val sqlContext: SQLContext)
  extends BaseRelation with TableScan with PrunedScan with InsertableRelation {

  // Share date format object as it is expensive to parse date pattern.
  private val dateFormatter = if (dateFormat != null) new SimpleDateFormat(dateFormat) else null

  private val logger = LoggerFactory.getLogger(CsvRelation.getClass)

  // Parse mode flags
  if (!ParseModes.isValidMode(parseMode)) {
    logger.warn(s"$parseMode is not a valid parse mode. Using ${ParseModes.DEFAULT}.")
  }

  if ((ignoreLeadingWhiteSpace || ignoreLeadingWhiteSpace) && ParserLibs.isCommonsLib(parserLib)) {
    logger.warn(s"Ignore white space options may not work with Commons parserLib option")
  }

  private val failFast = ParseModes.isFailFastMode(parseMode)
  private val dropMalformed = ParseModes.isDropMalformedMode(parseMode)
  private val permissive = ParseModes.isPermissiveMode(parseMode)

  override val schema: StructType = inferSchema()

  private def tokenRdd(header: Array[String]): RDD[Array[String]] = {

    if (ParserLibs.isUnivocityLib(parserLib)) {
      univocityParseCSV(baseRDD(), header)
    } else {
      val csvFormat = defaultCsvFormat
        .withDelimiter(delimiter)
        .withQuote(quote)
        .withEscape(escape)
        .withSkipHeaderRecord(false)
        .withHeader(header: _*)
        .withCommentMarker(comment)

      // If header is set, make sure firstLine is materialized before sending to executors.
      val filterLine = if (useHeader) firstLine else null

      baseRDD().mapPartitions { iter =>
        // When using header, any input line that equals firstLine is assumed to be header
        val csvIter = if (useHeader) {
          iter.filter(_ != filterLine)
        } else {
          iter
        }
        parseCSV(csvIter, csvFormat)
      }
    }
  }

  override def buildScan: RDD[Row] = {
    val simpleDateFormatter = dateFormatter
    val schemaFields = schema.fields
    val rowArray = new Array[Any](schemaFields.length)
    tokenRdd(schemaFields.map(_.name)).flatMap { tokens =>

      if (dropMalformed && schemaFields.length != tokens.length) {
        logger.warn(s"Dropping malformed line: ${tokens.mkString(",")}")
        None
      } else if (failFast && schemaFields.length != tokens.length) {
        throw new RuntimeException(s"Malformed line in FAILFAST mode: ${tokens.mkString(",")}")
      } else {
        var index: Int = 0
        try {
          index = 0
          while (index < schemaFields.length) {
            val field = schemaFields(index)
            rowArray(index) = TypeCast.castTo(tokens(index), field.dataType, field.nullable,
              treatEmptyValuesAsNulls, nullValue, simpleDateFormatter)
            index = index + 1
          }
          Some(Row.fromSeq(rowArray))
        } catch {
          case aiob: ArrayIndexOutOfBoundsException if permissive =>
            (index until schemaFields.length).foreach(ind => rowArray(ind) = null)
            Some(Row.fromSeq(rowArray))
          case _: java.lang.NumberFormatException |
               _: IllegalArgumentException if dropMalformed =>
            logger.warn("Number format exception. " +
              s"Dropping malformed line: ${tokens.mkString(delimiter.toString)}")
            None
          case pe: java.text.ParseException if dropMalformed =>
            logger.warn("Parse exception. " +
              s"Dropping malformed line: ${tokens.mkString(delimiter.toString)}")
            None
        }
      }
    }
  }

  /**
   * This supports to eliminate unneeded columns before producing an RDD
   * containing all of its tuples as Row objects. This reads all the tokens of each line
   * and then drop unneeded tokens without casting and type-checking by mapping
   * both the indices produced by `requiredColumns` and the ones of tokens.
   */
  override def buildScan(requiredColumns: Array[String]): RDD[Row] = {
    val simpleDateFormatter = dateFormatter
    val schemaFields = schema.fields
    val requiredFields = StructType(requiredColumns.map(schema(_))).fields
    val shouldTableScan = schemaFields.deep == requiredFields.deep
    val safeRequiredFields = if (dropMalformed) {
      // If `dropMalformed` is enabled, then it needs to parse all the values
      // so that we can decide which row is malformed.
      requiredFields ++ schemaFields.filterNot(requiredFields.contains(_))
    } else {
      requiredFields
    }
    val rowArray = new Array[Any](safeRequiredFields.length)
    if (shouldTableScan) {
      buildScan()
    } else {
      val safeRequiredIndices = new Array[Int](safeRequiredFields.length)
      schemaFields.zipWithIndex.filter {
        case (field, _) => safeRequiredFields.contains(field)
      }.foreach {
        case (field, index) => safeRequiredIndices(safeRequiredFields.indexOf(field)) = index
      }
      val requiredSize = requiredFields.length
      tokenRdd(schemaFields.map(_.name)).flatMap { tokens =>

        if (dropMalformed && schemaFields.length != tokens.length) {
          logger.warn(s"Dropping malformed line: ${tokens.mkString(delimiter.toString)}")
          None
        } else if (failFast && schemaFields.length != tokens.length) {
          throw new RuntimeException(s"Malformed line in FAILFAST mode: " +
            s"${tokens.mkString(delimiter.toString)}")
        } else {
          val indexSafeTokens = if (permissive && schemaFields.length > tokens.length) {
            tokens ++ new Array[String](schemaFields.length - tokens.length)
          } else if (permissive && schemaFields.length < tokens.length) {
            tokens.take(schemaFields.length)
          } else {
            tokens
          }
          try {
            var index: Int = 0
            var subIndex: Int = 0
            while (subIndex < safeRequiredIndices.length) {
              index = safeRequiredIndices(subIndex)
              val field = schemaFields(index)
              rowArray(subIndex) = TypeCast.castTo(
                indexSafeTokens(index),
                field.dataType,
                field.nullable,
                treatEmptyValuesAsNulls,
                nullValue,
                simpleDateFormatter
              )
              subIndex = subIndex + 1
            }
            Some(Row.fromSeq(rowArray.take(requiredSize)))
          } catch {
            case _: java.lang.NumberFormatException |
                 _: IllegalArgumentException if dropMalformed =>
              logger.warn("Number format exception. " +
                s"Dropping malformed line: ${tokens.mkString(delimiter.toString)}")
              None
            case pe: java.text.ParseException if dropMalformed =>
              logger.warn("Parse exception. " +
                s"Dropping malformed line: ${tokens.mkString(delimiter.toString)}")
              None
          }
        }
      }
    }
  }

  private def inferSchema(): StructType = {
    if (this.userSchema != null) {
      userSchema
    } else {
      val firstRow = if (ParserLibs.isUnivocityLib(parserLib)) {
        val escapeVal = if (escape == null) '\\' else escape.charValue()
        val commentChar: Char = if (comment == null) '\0' else comment
        val quoteChar: Char = if (quote == null) '\0' else quote
        new LineCsvReader(
          fieldSep = delimiter,
          quote = quoteChar,
          escape = escapeVal,
          commentMarker = commentChar).parseLine(firstLine)
      } else {
        val csvFormat = defaultCsvFormat
          .withDelimiter(delimiter)
          .withQuote(quote)
          .withEscape(escape)
          .withSkipHeaderRecord(false)
        CSVParser.parse(firstLine, csvFormat).getRecords.head.toArray
      }
      val header = if (useHeader) {
        firstRow
      } else {
        firstRow.zipWithIndex.map { case (value, index) => s"C$index"}
      }
      if (this.inferCsvSchema) {
        val simpleDateFormatter = dateFormatter
        InferSchema(tokenRdd(header), header, nullValue, simpleDateFormatter)
      } else {
        // By default fields are assumed to be StringType
        val schemaFields = header.map { fieldName =>
          StructField(fieldName.toString, StringType, nullable = true)
        }
        StructType(schemaFields)
      }
    }
  }

  /**
   * Returns the first line of the first non-empty file in path
   */
  private lazy val firstLine = {
    if (comment != null) {
      baseRDD().filter { line =>
        line.trim.nonEmpty && !line.startsWith(comment.toString)
      }.first()
    } else {
      baseRDD().filter { line =>
        line.trim.nonEmpty
      }.first()
    }
  }

  private def univocityParseCSV(
     file: RDD[String],
     header: Seq[String]): RDD[Array[String]] = {
    // If header is set, make sure firstLine is materialized before sending to executors.
    val filterLine = if (useHeader) firstLine else null
    val dataLines = if (useHeader) file.filter(_ != filterLine) else file
    val rows = dataLines.mapPartitionsWithIndex({
      case (split, iter) => {
        val escapeVal = if (escape == null) '\\' else escape.charValue()
        val commentChar: Char = if (comment == null) '\0' else comment
        val quoteChar: Char = if (quote == null) '\0' else quote

        new BulkCsvReader(iter, split,
          headers = header, fieldSep = delimiter,
          quote = quoteChar, escape = escapeVal,
          commentMarker = commentChar, maxCharsPerCol = maxCharsPerCol)
      }
    }, true)

    rows
  }

  private def parseCSV(
      iter: Iterator[String],
      csvFormat: CSVFormat): Iterator[Array[String]] = {
    iter.flatMap { line =>
      try {
        val records = CSVParser.parse(line, csvFormat).getRecords
        if (records.isEmpty) {
          logger.warn(s"Ignoring empty line: $line")
          None
        } else {
          Some(records.head.toArray)
        }
      } catch {
        case NonFatal(e) if !failFast =>
          logger.error(s"Exception while parsing line: $line. ", e)
          None
      }
    }
  }

  // The function below was borrowed from JSONRelation
  override def insert(data: DataFrame, overwrite: Boolean): Unit = {

    val filesystemPath = location match {
      case Some(p) => new Path(p)
      case None =>
        throw new IOException(s"Cannot INSERT into table with no path defined")
    }

    val fs = filesystemPath.getFileSystem(sqlContext.sparkContext.hadoopConfiguration)

    if (overwrite) {
      try {
        fs.delete(filesystemPath, true)
      } catch {
        case e: IOException =>
          throw new IOException(
            s"Unable to clear output directory ${filesystemPath.toString} prior"
              + s" to INSERT OVERWRITE a CSV table:\n${e.toString}")
      }
      // Write the data. We assume that schema isn't changed, and we won't update it.

      val codecClass = CompressionCodecs.getCodecClass(codec)
      data.saveAsCsvFile(filesystemPath.toString, Map("delimiter" -> delimiter.toString),
        codecClass)
    } else {
      sys.error("CSV tables only support INSERT OVERWRITE for now.")
    }
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Erro 404</title>

Erro : Pagina nao encontrada :( voltar para o site


text:
<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\TableGateway\TableGateway;
use Zend\Authentication\AuthenticationService;

use Application\Model\UserTable;
use Application\Model\User;

use Application\Form\ForgottenPasswordForm;
use Application\Form\ForgottenPasswordFilter;
use Application\Form\RestorePasswordForm;
use Application\Form\RestorePasswordFilter;

use Zend\Mail\Message;
use Zend\Mail\Transport\Sendmail as SendmailTransport;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;

class UserController extends AbstractActionController
{
	protected $usersTable = null;

	//remove
	private function _predump($value){
		echo "
";
		var_dump($value);
		echo "
";
		die;
	}

	public function getUsersTable(){
        if(!$this->usersTable){
            $sm = $this->getServiceLocator();
            $this->usersTable = $sm->get('Application\Model\UserTable');
        }
        return $this->usersTable;
    }

	public function indexAction(){

		$auth = new AuthenticationService();
		$identity = $auth->getIdentity();

		if (!$auth->hasIdentity()) {
			return $this->redirect()->toRoute('auth', array('controller' => 'auth', 'action' => 'login'));
		}

        return new ViewModel(array(
        	'user_logged' => $identity,
            'users' => $this->getUsersTable()->fetchAll()
        ));

    }

    /*
    	- restore password -
		from logged in user link (user)
    */
	public function restorePasswordAction(){

		//validate user logged in
		$auth = new AuthenticationService();
		$identity = $auth->getIdentity();
		$usr_id = $identity->user_id;

		if (!$auth->hasIdentity()) {
			return $this->redirect()->toRoute('auth', array('controller' => 'auth', 'action' => 'login'));
		}

		$form = new RestorePasswordForm();
		$request = $this->getRequest();

		//check data
		if ($request->isPost()) {

			$form->setInputFilter(new RestorePasswordFilter($this->getServiceLocator()));
			$form->setData($request->getPost());

			if ($form->isValid()) {

				$data 			= $form->getData();
				$password 		= $data['password'];
				$usersTable 	= $this->getUsersTable();
				$user 			= $usersTable->getUser($usr_id);
				$user->password = $this->encriptPassword($this->getStaticSalt(), $password, $user->password_salt);

				$usersTable->saveUser($user);

				//return $this->redirect()->toRoute('user', array('controller'=>'user', 'action'=>'restore-password-success'));
				$view_message = "La contraseña ha sido cambiada con éxito.";

				return new ViewModel(array('form' => $form, 'message' => $view_message));

			}

		}

		return new ViewModel(array('form' => $form));

	}

    /*
    	- forgotten password -
		from login form (auth)
    */
    public function forgottenPasswordAction(){

		$form = new ForgottenPasswordForm();

		$request = $this->getRequest();

		if ($request->isPost()) {

			$form->setInputFilter(new ForgottenPasswordFilter($this->getServiceLocator()));
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$data = $form->getData();

				$usr_email = $data['usr_email'];

				$usersTable = $this->getUsersTable();

				$auth = $usersTable->getUserByEmail($usr_email);

				$password = $this->generatePassword();

				$auth->password = $this->encriptPassword($this->getStaticSalt(), $password, $auth->password_salt);
				//$usersTable->changePassword($auth->usr_id, $password);
				// or

				$usersTable->saveUser($auth);
				$this->sendPasswordByEmail($usr_email, $password);
				$this->flashMessenger()->addMessage($usr_email);
				//return $this->redirect()->toRoute('user', array('controller'=>'user', 'action'=>'index'));

				$view_message = "La solicitud de restablecimiento de contraseña ha sido enviada a ".$usr_email.".

					Por favor, compruebe su buzón de entrada y regrese a la página de inicio de sesión.";

				return new ViewModel(array('form' => $form, 'message' => $view_message));
			}
		}
		return new ViewModel(array('form' => $form));

	}

	//sending new password by email
	//error expected!
	public function sendPasswordByEmail($usr_email, $password){
		$message = new Message();

		$this->getRequest()->getServer(); //Server vars

		$html_message = '

								<meta charset="UTF-8">

Tu nueva contraseña de Catálogo URREA ha sido restaurada.

														Tu nueva contraseña es: '.$password.'

Por favor inicia sesión nuevamente con ésta contraseña. Porsteriormente podrás personalizarla en la sección de usuario.

Si tienes algun problema o necesitas ayuda puedes enviar un correo a
							                            programacion@hoppercat.com y solicitar ayuda técnica.
							                            .

							';

		$html = new MimePart($html_message);
		$html->type = "text/html";

		$body = new MimeMessage();
		$body->setParts(array($html));

		$message->addTo($usr_email)
			->addFrom('catalogoapp@urrea.mx')
			->setSubject('Tu contraseña ha sido cambiada!')
			->setBody($body);

		$transport = new SendmailTransport();

		$transport->send($message);
	}

	//generating new dynamic salt
	public function generateDynamicSalt(){
		$dynamicSalt = '';
		for ($i = 0; $i < 50; $i++) {
			$dynamicSalt .= chr(rand(33, 126));
		}
		return $dynamicSalt;
	}

	//getting user static salt
	public function getStaticSalt(){
		$staticSalt = '';
		$config = $this->getServiceLocator()->get('Config');
		$staticSalt = $config['static_salt'];
		return $staticSalt;
	}

	//encriptation password function
	public function encriptPassword($staticSalt, $password, $dynamicSalt){
		return $password = md5($staticSalt . $password . $dynamicSalt);
	}

	//generate password function
	public function generatePassword($l = 8, $c = 0, $n = 0, $s = 0) {

		// get count of all required minimum special chars
		$count = $c + $n + $s;
		$out = '';

		// sanitize inputs; should be self-explanatory
		if(!is_int($l) || !is_int($c) || !is_int($n) || !is_int($s)) {
			trigger_error('Argument(s) not an integer', E_USER_WARNING);
			return false;
		}elseif($l < 0 || $l > 20 || $c < 0 || $n < 0 || $s < 0) {
			trigger_error('Argument(s) out of range', E_USER_WARNING);
			return false;
		}elseif($c > $l) {
			trigger_error('Number of password capitals required exceeds password length', E_USER_WARNING);
			return false;
		}elseif($n > $l) {
			trigger_error('Number of password numerals exceeds password length', E_USER_WARNING);
			return false;
		}elseif($s > $l) {
			trigger_error('Number of password capitals exceeds password length', E_USER_WARNING);
			return false;
		}elseif($count > $l) {
			trigger_error('Number of password special characters exceeds specified password length', E_USER_WARNING);
			return false;
		}

		// all inputs clean, proceed to build password
		// change these strings if you want to include or exclude possible password characters
		$chars = "abcdefghijklmnopqrstuvwxyz";
		$caps = strtoupper($chars);
		$nums = "0123456789";
		$syms = "!@#$%^&*()-+?";

		// build the base password of all lower-case letters
		for($i = 0; $i < $l; $i++) {
			$out .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}

		// create arrays if special character(s) required
		if($count) {

			// split base password to array; create special chars array
			$tmp1 = str_split($out);
			$tmp2 = array();

			// add required special character(s) to second array
			for($i = 0; $i < $c; $i++) {
				array_push($tmp2, substr($caps, mt_rand(0, strlen($caps) - 1), 1));
			}

			for($i = 0; $i < $n; $i++) {
				array_push($tmp2, substr($nums, mt_rand(0, strlen($nums) - 1), 1));
			}

			for($i = 0; $i < $s; $i++) {
				array_push($tmp2, substr($syms, mt_rand(0, strlen($syms) - 1), 1));
			}

			// hack off a chunk of the base password array that's as big as the special chars array
			$tmp1 = array_slice($tmp1, 0, $l - $count);

			// merge special character(s) array with base password array
			$tmp1 = array_merge($tmp1, $tmp2);

			// mix the characters up
			shuffle($tmp1);

			// convert to string for output
			$out = implode('', $tmp1);
		}

		return $out;
	}

}


text:
package com.apigee.monitoring;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.apigee.sdk.ApigeeClient;
import com.apigee.sdk.apm.android.ApigeeMonitoringClient;
import com.apigee.sdk.apm.android.Log;

import java.util.Random;

//import android.util.Log;

public class MonitoringSampleActivity extends Activity implements NetworkResponseListener {

    private static final String ORG_NAME = "<YOUR ORG NAME>";
    private static final String APP_NAME = "sandbox"; // or <YOUR APP NAME>

	private static final String TAG_LOGGING = "monitoring";
	private static final String LOGGING_INDICATOR_TEXT = "Logging ";
	private static final String ERROR_INDICATOR_TEXT = "Error Reporting ";

	private Button buttonForceCrash;
	private Button buttonLog;
	private Button buttonError;
	private Button buttonNetworkPerfMetrics;
	private TextView textViewLogLevel;
	private TextView textViewErrorLevel;
	private SeekBar seekBarLogLevel;
	private CheckBox checkBoxPaused;
	private SeekBar seekBarErrorLevel;
	private Object connection;
	private String urlString;
	private int loggingLevelIndex;
	private int errorLevelIndex;
	private Random randomGenerator;
	private String[] listLoggingMessages;
	private String[] listErrorMessages;
	private String[] listUrls;
	private int httpClientMethodToUse;

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

		setContentView(R.layout.activity_monitoring_sample);

		Activity activity = this;

		loggingLevelIndex = 0;
		errorLevelIndex = 0;
		httpClientMethodToUse = 0;

    	seekBarLogLevel = (SeekBar) activity.findViewById(R.id.seekBarLogLevel);
    	seekBarErrorLevel = (SeekBar) activity.findViewById(R.id.seekBarErrorLevel);

    	buttonForceCrash = (Button) activity.findViewById(R.id.buttonForceCrash);
    	buttonLog = (Button) activity.findViewById(R.id.buttonLog);
    	buttonError = (Button) activity.findViewById(R.id.buttonError);
    	buttonNetworkPerfMetrics = (Button) activity.findViewById(R.id.buttonNetworkPerfMetrics);

    	textViewLogLevel = (TextView) activity.findViewById(R.id.textViewLogLevel);
    	textViewErrorLevel = (TextView) activity.findViewById(R.id.textViewErrorLevel);

    	checkBoxPaused = (CheckBox) activity.findViewById(R.id.checkBoxPause);

    	updateLogLevelIndicator();
    	updateErrorLevelIndicator();

		randomGenerator = new Random();

	    listLoggingMessages = new String[]{
	            "user denied access to location",
	                "battery level low",
	                "device paired with bluetooth keyboard",
	                "shake to refresh enabled",
	                "device registered for push notifications",
	                "device running older level of Android, disabling feature X",
	                "data cache refreshed from server",
	                "security policy updated from server",
	                "local notifications enabled" };

	    listErrorMessages = new String[]{
	            "unable to connect to database",
	                "unable to save user preference",
	                "encryption of payload failed",
	                "unzipping of server response failed",
	                "authentication failed",
	                "update server not found" };

	    listUrls = new String[]{
	            "http://www.cnn.com",
	                "http://www.abcnews.com",
	                "http://www.cbsnews.com",
	                "http://www.bbc.co.uk"       // one in Europe
	               };

		seekBarLogLevel.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
		    @Override
		    public void onProgressChanged(SeekBar v, int progress, boolean isUser) {
		    	loggingLevelIndex = progress;
		    	updateLogLevelIndicator();
		    }
		    @Override
		    public void onStartTrackingTouch(SeekBar seekBar) {
		    }
		    @Override
		    public void onStopTrackingTouch(SeekBar seekBar) {
		    }
		});

		seekBarErrorLevel.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
		    @Override
		    public void onProgressChanged(SeekBar v, int progress, boolean isUser) {
		    	errorLevelIndex = progress;
		    	updateErrorLevelIndicator();
		    }
		    @Override
		    public void onStartTrackingTouch(SeekBar seekBar) {
		    }
		    @Override
		    public void onStopTrackingTouch(SeekBar seekBar) {
		    }
		});

    	buttonForceCrash.setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			forceCrashPressed();
    		}
    	});

    	buttonLog.setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			generateLoggingEntryPressed();
    		}
    	});

    	buttonError.setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			generateErrorPressed();
    		}
    	});

    	buttonNetworkPerfMetrics.setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			captureNetworkPerformanceMetricsPressed();
    		}
    	});

    	checkBoxPaused.setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			monitoringPauseCheckBoxToggled();
    		}
    	});

	    MonitoringSampleApplication app = (MonitoringSampleApplication) this.getApplication();
	    if (null == app.getApigeeClient()) {
	    	ApigeeClient apigeeClient = new ApigeeClient(ORG_NAME,APP_NAME,this.getApplicationContext());
	    	app.setApigeeClient(apigeeClient);
	    }
	}

	public void updateLogLevelIndicator() {
		String levelAsText = null;

		if (loggingLevelIndex == 0) {
			levelAsText = "Verbose";
		} else if (loggingLevelIndex == 1) {
			levelAsText = "Debug";
		} else if (loggingLevelIndex == 2) {
			levelAsText = "Info";
		} else if (loggingLevelIndex == 3) {
			levelAsText = "Warn";
		}

		String labelText = LOGGING_INDICATOR_TEXT;

		if (levelAsText != null) {
			labelText = labelText + "(" + levelAsText + ")";
		}

		textViewLogLevel.setText(labelText);
	}

	public void updateErrorLevelIndicator() {
		String levelAsText = null;

		if (errorLevelIndex == 0) {
			levelAsText = "Error";
		} else if (errorLevelIndex == 1) {
			levelAsText = "Assert/Critical";
		}

		String labelText = ERROR_INDICATOR_TEXT;

		if (levelAsText != null) {
			labelText = labelText + "(" + levelAsText + ")";
		}

		textViewErrorLevel.setText(labelText);
	}

	protected String randomStringFromList(String[] listOfStrings) {
		int index = randomGenerator.nextInt(listOfStrings.length);
		return listOfStrings[index];
	}

	public void forceCrashPressed()
	{
	    // purposefully go beyond end of array to generate a crash
	    String x = listUrls[50];
	    Log.v( "tag", x );
	}

	public void generateLoggingEntryPressed()
	{
	    String logMessage = randomStringFromList(listLoggingMessages);

	    if( loggingLevelIndex == 0 )
	    {
	        Log.v(TAG_LOGGING, logMessage);  // verbose
	    }
	    else if( loggingLevelIndex == 1 )
	    {
	        Log.d(TAG_LOGGING, logMessage);  // debug
	    }
	    else if( loggingLevelIndex == 2 )
	    {
	        Log.i(TAG_LOGGING, logMessage);  // info
	    }
	    else if( loggingLevelIndex == 3 )
	    {
	        Log.w(TAG_LOGGING, logMessage);  // warning
	    }
	}

	public void generateErrorPressed()
	{
	    String errorMessage = randomStringFromList(listErrorMessages);

	    if( errorLevelIndex == 0 )
	    {
	        Log.e(TAG_LOGGING, errorMessage);   // error
	    }
	    else if( errorLevelIndex == 1 )
	    {
	        Log.wtf(TAG_LOGGING, errorMessage);  // assert/critical
	    }
	}

	public void captureNetworkPerformanceMetricsPressed()
	{
	    if( connection == null )
	    {
	        String urlAsString = randomStringFromList(listUrls);

	        // if we have more than 1 url in the list, make sure that the new one
	        // is different from the last one that we used
	        if( (urlString != null) &&
	        	(urlString.length() > 0) &&
	        	(listUrls.length > 1) &&
	        	urlAsString.equals(urlString) )
	        {
	            do {
	                urlAsString = randomStringFromList(listUrls);
	            } while( urlAsString.equals(urlString) );
	        }

	        urlString = urlAsString;

	        Log.d(TAG_LOGGING, "making call to " + urlAsString);

	        String httpClient = "HttpClient";
	        //String httpUrlConnection = "HttpURLConnection";
	        String mechanismToUse = httpClient;

    		HttpRequestTask httpTask = new HttpRequestTask(mechanismToUse,6000,httpClientMethodToUse);  // timeout in milliseconds
    		httpTask.setNetworkResponseListener(this);
    		httpTask.execute(urlString);
    		++httpClientMethodToUse;
    		if (httpClientMethodToUse > 7) {
    			httpClientMethodToUse = 0;
    		}
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_monitoring_sample, menu);
		return true;
	}

	public void notifyNetworkResponseSuccess(String response) {
		Log.d(TAG_LOGGING,"network response received successfully");
	}

	public void notifyNetworkResponseFailure(Exception exception, String response) {
		if (exception != null) {
			if (response != null) {
				Log.e(TAG_LOGGING,"error: " + exception.getLocalizedMessage() + ";" + response);
			} else {
				Log.e(TAG_LOGGING,"error: " + exception.getLocalizedMessage());
			}
		} else {
			if (response != null) {
				Log.e(TAG_LOGGING,"error: (no exception given); " + response);
			}
		}
	}

	public void monitoringPauseCheckBoxToggled() {
	    MonitoringSampleApplication app = (MonitoringSampleApplication) this.getApplication();
	    ApigeeClient apigeeClient = app.getApigeeClient();
        ApigeeMonitoringClient monitorClient = null;

	    if (apigeeClient != null) {
	    	monitorClient = apigeeClient.getMonitoringClient();
	    }

		if (this.checkBoxPaused.isChecked()) {
			if (monitorClient != null) {
				Log.i(TAG_LOGGING, "pausing monitoring");
				monitorClient.pause();
			} else {
				Log.w(TAG_LOGGING, "monitoring client is null, unable to pause");
			}
		} else {
			if (monitorClient != null) {
				Log.i(TAG_LOGGING, "resuming monitoring");
				monitorClient.resume();
			} else {
				Log.w(TAG_LOGGING, "monitoring client is null, unable to resume");
			}
		}
	}

}


text:
package com.sxjs.jd.composition.main.goodsinfo_xqs;

import android.app.Application;

import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.sxjs.common.GlobalAppComponent;
import com.sxjs.common.model.DataManager;
import com.sxjs.common.model.dao.DataBaseHelper;
import com.sxjs.common.model.http.HttpHelper;
import com.sxjs.common.model.sp.SharePreferenceHelper;

/**
 * @author admin
 */
public class MyApplication extends Application {

    HttpHelper httpHelper;
    SharePreferenceHelper sharePreferenceHelper;
    DataBaseHelper dataBaseHelper;
    DataManager dataManager;

    @Override
    public void onCreate() {
        super.onCreate();
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return;
//        }
//        if(CommonConfig.DEBUG){
//            LeakCanary.install(this);
//            ARouter.openLog();     // 打印日志
//            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
//        }

        ARouter.init(this);
        //CrashReport.initCrashReport(getApplicationContext(), "93f0e37549", CommonConfig.DEBUG);
        Fresco.initialize(this);
        GlobalAppComponent.init(this);
        httpHelper= new HttpHelper(this);
        sharePreferenceHelper = new SharePreferenceHelper(this);
        dataBaseHelper = new DataBaseHelper(this);
        dataManager = new DataManager(this,httpHelper,sharePreferenceHelper,dataBaseHelper);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.clearMemoryCaches();
    }

    public DataManager getDataManager(){
        return dataManager;
    }

    public HttpHelper getHttpHelper(){
        return httpHelper;
    }
    public SharePreferenceHelper getSharePreferenceHelper(){
        return sharePreferenceHelper;
    }
    public DataBaseHelper getDataBaseHelper(){
        return dataBaseHelper;
    }
}