text:
package sign

import (
	"fmt"
	"math/rand"
	"path/filepath"
	"time"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/core/dnsserver"
	"github.com/coredns/coredns/plugin"
)

func init() { plugin.Register("sign", setup) }

func setup(c *caddy.Controller) error {
	sign, err := parse(c)
	if err != nil {
		return plugin.Error("sign", err)
	}

	c.OnStartup(sign.OnStartup)
	c.OnStartup(func() error {
		for _, signer := range sign.signers {
			go signer.refresh(durationRefreshHours)
		}
		return nil
	})
	c.OnShutdown(func() error {
		for _, signer := range sign.signers {
			close(signer.stop)
		}
		return nil
	})

	// Don't call AddPlugin, *sign* is not a plugin.
	return nil
}

func parse(c *caddy.Controller) (*Sign, error) {
	sign := &Sign{}
	config := dnsserver.GetConfig(c)

	for c.Next() {
		if !c.NextArg() {
			return nil, c.ArgErr()
		}
		dbfile := c.Val()
		if !filepath.IsAbs(dbfile) && config.Root != "" {
			dbfile = filepath.Join(config.Root, dbfile)
		}

		origins := make([]string, len(c.ServerBlockKeys))
		copy(origins, c.ServerBlockKeys)
		args := c.RemainingArgs()
		if len(args) > 0 {
			origins = args
		}
		for i := range origins {
			origins[i] = plugin.Host(origins[i]).Normalize()
		}

		signers := make([]*Signer, len(origins))
		for i := range origins {
			signers[i] = &Signer{
				dbfile:      dbfile,
				origin:      plugin.Host(origins[i]).Normalize(),
				jitterIncep: time.Duration(float32(durationInceptionJitter) * rand.Float32()),
				jitterExpir: time.Duration(float32(durationExpirationDayJitter) * rand.Float32()),
				directory:   "/var/lib/coredns",
				stop:        make(chan struct{}),
				signedfile:  fmt.Sprintf("db.%ssigned", origins[i]), // origins[i] is a fqdn, so it ends with a dot, hence %ssigned.
			}
		}

		for c.NextBlock() {
			switch c.Val() {
			case "key":
				pairs, err := keyParse(c)
				if err != nil {
					return sign, err
				}
				for i := range signers {
					for _, p := range pairs {
						p.Public.Header().Name = signers[i].origin
					}
					signers[i].keys = append(signers[i].keys, pairs...)
				}
			case "directory":
				dir := c.RemainingArgs()
				if len(dir) == 0 || len(dir) > 1 {
					return sign, fmt.Errorf("can only be one argument after %q", "directory")
				}
				if !filepath.IsAbs(dir[0]) && config.Root != "" {
					dir[0] = filepath.Join(config.Root, dir[0])
				}
				for i := range signers {
					signers[i].directory = dir[0]
					signers[i].signedfile = fmt.Sprintf("db.%ssigned", signers[i].origin)
				}
			default:
				return nil, c.Errf("unknown property '%s'", c.Val())
			}
		}
		sign.signers = append(sign.signers, signers...)
	}

	return sign, nil
}


text:
% BEGIN LICENSE BLOCK
% Version: CMPL 1.1
%
% The contents of this file are subject to the Cisco-style Mozilla Public
% License Version 1.1 (the "License"); you may not use this file except
% in compliance with the License.  You may obtain a copy of the License
% at www.eclipse-clp.org/license.
%
% Software distributed under the License is distributed on an "AS IS"
% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
% the License for the specific language governing rights and limitations
% under the License.
%
% The Original Code is  The ECLiPSe Constraint Logic Programming System.
% The Initial Developer of the Original Code is  Cisco Systems, Inc.
% Portions created by the Initial Developer are
% Copyright (C) 1994 - 2006 Cisco Systems, Inc.  All Rights Reserved.
%
% Contributor(s):
%
% END LICENSE BLOCK
%
% @(#)umsio.tex 1.8 94/10/20
%

% \comment{@(\#)text2.mss       20.3 9/19/88}
% \part{text2, root = `manual.mss'}
\chapter{Input and Output}
\label{chapio}
%HEVEA\cutdef[1]{section}
%----------------------------------------------------------------------
\section{Streams}
%----------------------------------------------------------------------
\index{input/output}
Input and output in {\eclipse} is done via communication channels
called \defnotioni{streams}{stream}.
They are usually associated with I/O devices (a file, a terminal,
a socket, a pipe), or in-memory queues or buffers.

The streams may be opened for input only
(\defnotion{read mode}\index{mode!read}),
output only (\defnotion{write mode}\index{mode!write}),
or for both input and output (\defnotion{update mode}\index{mode!update}).

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Predefined Streams}
\label{streams}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Every {\eclipse} session defines the following symbolic stream names, which
indicate the \aboutidx{current streams} for certain categories of input/output:
\begin{quote}
\begin{description}
\item[\Indextt{input}]
  Used by the input predicates that do not have an explicit stream argument,
  e.g., \bipref{read/1}{../bips/kernel/ioterm/read-1.html}.
  This is by default the same as user_input and stdin, but can be redirected.
\item[\Indextt{output}]
  Used by the output predicates that do not have an explicit stream argument,
  e.g., \bipref{write/1}{../bips/kernel/ioterm/write-1.html}.
  This is by default the same as user_output and stdout, but can be redirected.
\item[\Indextt{error}]
  Output for error messages and all messages about exceptional states.
  This is by default the same as user_error and stderr, but can be redirected.
\item[\Indextt{warning_output}]
  Used by the system or user programs to output warning messages.
  This is by default the same as user_output and stdout, but can be redirected.
\item[\Indextt{log_output}]
  Used by the system for information messages (e.g. garbage collection),
  or by user programs for e.g. messages about computational progress.
  This is by default the same as user_output and stdout, but can be redirected.
\end{description}
\end{quote}

The above streams can be freely redirected, but are initially set to one
of the following three \aboutidx{default streams}, to which they will
also be reset whenever a redirection ends:
\begin{quote}
\begin{description}
\item[\Indextt{user_input}]
  The default input stream.
  This is initially the same as stdin, but can be redirected.
\item[\Indextt{user_output}]
  The default output stream.
  This is initially the same as stdout, but can be redirected.
\item[\Indextt{user_error}]
  The default error stream.
  This is initially the same as stderr, but can be redirected.
\end{description}
\end{quote}

Finally, there are the four predefined \aboutidx{standard streams},
which cannot be closed or redirected.  Apart from the \notationidx{null}
stream, there is usually no need to refer to them explicitly:
\begin{quote}
\begin{description}
\item[\Indextt{stdin}]
  The standard input stream.
\item[\Indextt{stdout}]
  The standard output stream.
\item[\Indextt{stderr}]
  The standard error stream.
\item[\Indextt{null}]
  A dummy stream, output to it is discarded, on input it always
  gives end of file.
\end{description}
\end{quote}
In a stand-alone {\eclipse} stdin, stdout and stderr are connected
to the corresponding standard I/O descriptors of the process.
In an embedded {\eclipse}, the meaning of stdin, stdout and
stderr is determined by the {\eclipse} initialization options.

\begin{center}
\begin{tabular}{|l|l|l|}
\hline
Current Stream  & Default Stream & Standard Stream\\
\hline
\hline
input           & user_input  & stdin\\
\hline
output          & user_output & stdout\\
warning_output  & user_output & stdout\\
log_output      & user_output & stdout\\
\hline
error           & user_error  & stderr\\
\hline
                &             & null\\
\hline
\end{tabular}

Initial assignment of symbolic stream names
\end{center}

For compatibility with Prolog systems, the system accepts the stream
name \notationidx{user} in certain places.  Its meaning is
identical to \notation{stdin} and \notation{stdout},
depending on the context where it is used.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Stream Handles and Aliases}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Streams can be identified by anonymous
\aboutidx{stream handles} or by symbolic names.\footnote{%
    Earlier {\eclipse} versions identified streams by small integers, which
    is now deprecated, except for some foreign language interfaces. If needed,
    the number is available as the physical_stream stream property.}
Most of the built-in predicates that require a stream to be specified
have a stream argument at the first position,
e.g., \notation{write(Stream, Term)}. This argument can be either a
stream handle or a symbolic stream name.

Streams that are opened by programs should preferably use stream handles,
as this allows the system to better keep track of their lifetime.
Nevertheless, alias names can be given, either immediately when a stream is
newly opened (e.g. with \bipref{open/4}{../bips/kernel/iostream/open-4.html}),
or later via redirection
(\bipref{set_stream/2}{../bips/kernel/iostream/set_stream-2.html}).
A stream can have more than one symbolic alias.

To obtain a handle when only an alias is known, use
\bipref{get_stream/2}{../bips/kernel/iostream/get_stream-2.html}:
\begin{quote}
\begin{verbatim}
get_stream(StreamOrAlias, Handle)
\end{verbatim}
\end{quote}
\bipref{get_stream/2}{../bips/kernel/iostream/get_stream-2.html} can also
be used to check whether two stream names are aliases of each other.

Note that stream handles are not normal Prolog terms!  They
can not be assembled, decomposed, or occur literally in Prolog text.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Opening New Streams}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\label{openstream}

Streams provide a uniform interface to a variety of I/O devices and
pseudo-devices. The following table gives an overview of how
streams on the different devices are opened.
\begin{center}
\begin{tabular}{|c|l|}
\hline
I/O device      &       How to open             \\
\hline
\hline
tty             &
implicit (\notation{stdin}, \notation{stdout}, \notation{stderr}) or
\bipref{open/3}{../bips/kernel/iostream/open-3.html} of a device file \\
\hline
file            &
\biptxtref{open(\pattern{FileName},~\pattern{Mode},~\pattern{Stream})}{open/3}%
{../bips/kernel/iostream/open-3.html}           \\
\hline
string          &
\biptxtref{open(string(\pattern{String}),~\pattern{Mode},~\pattern{Stream})}%
{open/3}{../bips/kernel/iostream/open-3.html}           \\
\hline
queue           &
\biptxtref{open(queue(\pattern{String}),~\pattern{Mode},~\pattern{Stream})}%
{open/3}{../bips/kernel/iostream/open-3.html}           \\
\hline
pipe            &       \bipref{exec/2}{../bips/kernel/opsys/exec-2.html},
                        \bipref{exec/3}{../bips/kernel/opsys/exec-3.html} and
                        \bipref{exec_group/3}%
{../bips/kernel/opsys/exec_group-3.html}        \\
\hline
socket          &       \bipref{socket/3}{../bips/kernel/iostream/socket-3.html}
                        and
                    \bipref{accept/3}{../bips/kernel/iostream/accept-3.html} \\
\hline
null            &       implicit (null stream)  \\
\hline
\end{tabular}

How to open streams onto the different I/O devices
\end{center}

Most streams are opened for input or output by means of the
\bipref{open/3}{../bips/kernel/iostream/open-3.html}
or
\bipref{open/4}{../bips/kernel/iostream/open-4.html}
predicate.
The goals
\begin{quote}
\begin{verbatim}
open(SourceSink, Mode, Stream)
open(SourceSink, Mode, Stream, Options)
\end{verbatim}
\end{quote}
open a communication channel with \about{SourceSink}.

If \about{SourceSink} is an atom or a string, a file is being opened
and \about{SourceSink} takes
the form of a file name in the host machine environment.
{\eclipse} uses an operating
system independent path name syntax, where the components are separated by
forward slashes.
The following forms are possible:
\begin{itemize}
\item absolute path name, e.g., \notation{/usr/peter/prolog/file.pl};
\item relative to the current directory, e.g., \notation{prolog/file.pl};
\item relative to the own home directory, e.g.,
       \verb:~:\notation{/prolog/file.pl};
\item start with an environment variable, e.g.,
      \notation{\$HOME/prolog/file.pl};
\item relative to a user's home directory, e.g.,
       \verb:~:\notation{peter/prolog/file.pl} (UNIX only);
\item specifying a drive name, e.g., \notation{//C/prolog/file.pl}
       (Windows only).
\end{itemize}
Note that path names usually have to be quoted (in single or double quotes)
because they contain non-alphanumeric characters.

If \about{SourceSink} is of the form \notation{string(\pattern{InitString})} a
    pseudo-file
in memory is opened, see section \ref{stringio}.

If \about{SourceSink} is of the form \notation{queue(\pattern{InitString})} a
pseudo-pipe in memory is opened, see section \ref{queueio}.

\about{Mode} must be one of the atoms \notation{read}, \notation{write},
\notation{append} or \notation{update},
which means that the stream is to be opened for input, output, output at the
end of the existing stream, or both input and output, respectively.
Opening a file in \notation{write} mode will create it if it does not exist,
and erase the previous contents if it does exist.
Opening a file in \notation{append} mode will keep the current contents
of the file and start writing at its end.

\about{Stream} is a symbolic stream identifier or an uninstantiated variable.
If it is uninstantiated, the system will bind it to an anonymous stream handle:
\begin{quote}
\begin{verbatim}
[eclipse 1]: open(new_file, write, Stream).
Stream = $&(stream(7))
Yes (0.00s cpu)
\end{verbatim}
\end{quote}
If the stream argument is an atomic name, this name becomes an alias
for the (hidden) stream number:
\begin{quote}
\begin{verbatim}
[eclipse 1]: open(new_file, write, new_stream).
yes.
\end{verbatim}
\end{quote}
This is equivalent to
\begin{verbatim}
[eclipse 1]: open(new_file, write, _, [alias(new_stream)]).
yes.
\end{verbatim}
The stream identifier (symbolic or handle) may then be used in predicates
which have a named stream as one of their arguments. For example
\begin{quote}
\begin{verbatim}
open("foo", update, Stream), write(Stream, subject), close(Stream).
\end{verbatim}
\end{quote}
will write the atom
\about{subject} to the file `foo' and close the stream subsequently.

It is recommended style \emph{not} to use symbolic stream names in code that is
meant to be reused. This is because these stream names are global,
there is the possibility of name clashes, and the code will not be reentrant.
It is cleaner to open streams with a variable for the stream identifier
and pass the resulting handle as an argument wherever it is needed.

\defnotion{Socket streams} are not opened with \predspec{open/3}, but with the
special primitives
\bipref{socket/3}{../bips/kernel/iostream/socket-3.html} and
\bipref{accept/3}{../bips/kernel/iostream/accept-3.html}.
More details are in chapter \ref{sockets}.

%The predicate
%\bipref{pipe/2}{../bips/kernel/obsolete/pipe-2.html} is used to
%open a UNIX pipe, i.e., two streams, {\it In} for reading and {\it Out}
%for writing, which are connected together using the {\it pipe(2)}
%system call.
%This mechanism is normally used to communicate with other processes
%which were forked by the main process.

A further group of primitives which open streams implicitly consists of
\bipref{exec/2}{../bips/kernel/opsys/exec-2.html},
\bipref{exec/3}{../bips/kernel/opsys/exec-3.html}
and \bipref{exec_group/3}{../bips/kernel/opsys/exec_group-3.html}.
They open \defnotion{pipe streams} which connect directly to the I/O channels of
the executed process. See chapter \ref{chapopsys} for details.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Closing Streams}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

A stream lives until it is closed.  Streams that are only referenced
by handle are closed automatically, either on failure across the
open/3,4 predicate, or after all copies of their handle become unused
and garbage collected.  This means that no extra precautions have to
be taken to ensure that streams are closed on failure or when
aborting.  Handle-streams can optionally be closed explicitly if their
lifetime is statically known in the program.  Streams that have
aliases cannot be closed automatically:  all aliases must be closed
explicitly.

The predicates
\bipref{close/1}{../bips/kernel/iostream/close-1.html},
\biptxtref{2}{close/2}{../bips/kernel/iostream/close-2.html}
\begin{quote}
\preddef{close(\pattern{Stream})}\\
\preddef{close(\pattern{Stream},\pattern{Options})}
\end{quote}
are used to explicitly close an open stream.
If a stream has several alias names, closing any of them will close
the actual stream. All the other aliases should be closed as well
(or redirected to streams that are still open),
because otherwise they will continue
to refer to an identifier of the already closed stream.

When an attempt is made to close a redirected system stream (e.g.,
\notation{output}),
the stream is closed, but the system stream is reset to its default setting.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Redirecting Streams}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

\index{redirecting streams}\index{streams!redirecting}
The \bipref{set_stream/2}{../bips/kernel/iostream/set_stream-2.html}
primitive can be used to redirect an already existing symbolic stream
to a new actual stream.
This is particularly useful to redirect e.g., the default \notation{output}
stream:
\begin{quote}
\begin{verbatim}
set_stream(output, MyStream)
\end{verbatim}
\end{quote}
so that all standard output is redirected to some other destination
(e.g., an opened file instead of the terminal).
Note that the stream modes (read/write) must be compatible.
The redirection is terminated by calling
\begin{quote}
\begin{verbatim}
close(output)
\end{verbatim}
\end{quote}
which will reestablish the original meaning of the output stream
by resetting it to the user_output default stream.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Finding Streams}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The predicate
\begin{quote}
\preddef{current_stream(?\pattern{Stream})}\indextt{current_stream/1}
\end{quote}
can be used to backtrack over all the currently opened streams,
and obtain handles for them (but not their aliases).

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Stream Properties}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
A stream's properties can be accessed using
\bipref{get_stream_info/3}{../bips/kernel/iostream/get_stream_info-3.html}:
\begin{quote}
\preddef{get_stream_info(%
+\pattern{Stream},~+\pattern{Property},~-\pattern{Value})}
\end{quote}
e.g., its mode, line number, file name etc.
Some stream properties can be modified using
\bipref{set_stream_property/3}%
{../bips/kernel/iostream/set_stream_property-3.html}:
\begin{quote}
\preddef{set_stream_property(%
+\pattern{Stream},~+\pattern{Property},~+\pattern{Value})}
\end{quote}
e.g., the end-of-line sequence used, the flushing behaviour, the event-raising
behaviour, the prompt etc.

%----------------------------------------------------------------------
\section{Communication via Streams}
%----------------------------------------------------------------------
The contents of a stream may be interpreted in one of
three basic ways.
The first one is to
consider it as a sequence of characters, so that the basic unit to
be read or written is a character. The second one interprets
the stream as a sequence of tokens, thus providing an interface
to the Prolog lexical analyzer and the third one is to consider a stream as
a sequence of Prolog terms.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Character I/O}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The \biprefni{get/1,2}{../bips/kernel/iochar/get-1.html}%
\indextt{get/1}\indextt{get/2}
and
\biprefni{put/1,2}{../bips/kernel/iochar/put-1.html}%
\indextt{put/1}\indextt{put/2}
predicates corresponds to the first way
of looking at streams. The call
\begin{quote}
\begin{verbatim}
get(Char)
\end{verbatim}
\end{quote}
takes the next character from
the current input stream and matches it as a single character with Char.
Note that a character in {\eclipse} is represented as an integer corresponding
to the ISO-8859-1 (iso_latin_1) code of the character.
If the end of file has been reached then an exception is raised and -1
is returned.
The call
\begin{quote}
\begin{verbatim}
put(Char)
\end{verbatim}
\end{quote}
puts the char Char on to the current output stream.
The predicates
\begin{quote}
\begin{verbatim}
get(Stream, Char)
\end{verbatim}
\end{quote}
 and
\begin{quote}
\begin{verbatim}
put(Stream, Char)
\end{verbatim}
\end{quote}
work similarly on the specified
stream.

The input and output is normally buffered by {\eclipse}.
To make I/O in \defnotion{raw mode}\index{mode!raw}, without buffering, the
predicates
\biprefni{tyi/1,2}{../bips/kernel/iochar/tyi-1.html}%
\indextt{tyi/1}\indextt{tyi/2}
and
\biprefni{tyo/1,2}{../bips/kernel/iochar/tyo-1.html}%
\indextt{tyo/1}\indextt{tyo/2}
are provided.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Token I/O}
\index{token}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The predicates
\bipref{read_token/2}{../bips/kernel/iochar/read_token-2.html} and
\bipref{read_token/3}{../bips/kernel/iochar/read_token-3.html}:
\begin{quote}
\preddef{read_token(\pattern{Token},~\pattern{Class})}\\
\preddef{read_token(\pattern{Stream},~\pattern{Token},~\pattern{Class})}
\end{quote}
represent the second way of interpreting stream contents.
They read the next token from the current
input stream, unify it with \about{Token},
and its token class is unified with \about{Class}.
A token is either a sequence of characters with the same or compatible
\Index{character class}, e.g., ab_1A, then it is a Prolog constant
or variable, or a single character, e.g., ')'.
The \Index{token class} represents the type of the token and
its special meaning, e.g., \notation{fullstop}, \notation{comma},
\notation{open_par}, etc.
The exact definition of character classes and tokens can be found in
appendices \ref{charclass} and \ref{tokendef}, respectively.

A further, very flexible possibility to read a sequence of
characters is provided by the built-in
\bipref{read_string/5}{../bips/kernel/iochar/read_string-5.html}
\begin{quote}
\preddef{read_string(%
\pattern{Stream},~\pattern{SepChars},~\pattern{PadChars},~\pattern{Separator},~\pattern{String})}
\end{quote}
Here, the input is read up to a specified delimiter,
and returned as an {\eclipse} string.

In particular, one line of input can be read as follows:
\begin{quote}
\begin{verbatim}
read_line(Stream, String) :-
    read_string(Stream, end_of_line, "", _Separator, String).
\end{verbatim}
\end{quote}
The \about{SepChar} argument allows the specification of padding
characters, which will be ignored before and after separators.
Once a string has been read, string manipulation predicates like
\bipref{split_string/4}{../bips/kernel/stratom/split_string-4.html}
can be used to break it up into even smaller components.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Term I/O}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The \biprefni{read/1,2}{../bips/kernel/ioterm/read-1.html}%
\indextt{read/1}\indextt{read/2}
and
\biprefni{write/1,2}{../bips/kernel/ioterm/write-1.html}%
\indextt{write/1}\indextt{write/2}
predicates  correspond to
the third way of looking at streams.
For input, the goal
\begin{quote}
\begin{verbatim}
read(Term)
\end{verbatim}
\end{quote}
 reads the next {\eclipse} term from the
current input
stream and unifies it with \about{Term}. The input term must be followed by a
full stop, that is, a '.' character followed by a layout
character (tab, space or newline) or by the end of file.
The exact definition of the term syntax can be found in appendix
\ref{chapsyntax}.

If end of file has been reached then
an exception is raised, the default handler causes the atom
\notation{end_of_file} to be returned.
A term may be read from a stream other than the current input stream by
the call
\begin{quote}
\begin{verbatim}
read(Stream, Term)
\end{verbatim}
\end{quote}
which reads the term from the named stream.

For additional information about other options for reading terms,
in particular for how to get variable names, refer to
\bipref{readvar/3}{../bips/kernel/ioterm/readvar-3.html},
\bipref{read_term/2}{../bips/kernel/ioterm/read_term-2.html} and
\bipref{read_term/3}{../bips/kernel/ioterm/read_term-3.html}.
For reading and processing complete {\eclipse} source code files, use the
\bipref{library(source_processor)}{../bips/lib/source_processor/index.html}.

For output, the goal
\begin{quote}
\begin{verbatim}
write(Term)
\end{verbatim}
\end{quote}
writes \about{Term} to the current output stream.
This is done by taking the current operator declarations into account. Output
produced by the
\biprefni{write/1,2}{../bips/kernel/ioterm/write-1.html}%
\indextt{write/1}\indextt{write/2}
predicate is not (necessarily) in
a form suitable for subsequent input to a Prolog program using the
\bipref{read/1}{../bips/kernel/ioterm/read-1.html}
predicate, for this purpose
\biprefni{writeq/1,2}{../bips/kernel/ioterm/writeq-1.html}%
\indextt{writeq/1}\indextt{writeq/2}
is to be used.
The goal
\begin{quote}
\begin{verbatim}
write(Stream, Term)
\end{verbatim}
\end{quote}
writes \about{Term} to the named output stream.
For more details about how to output terms in different formats, see
section \ref{secoutputformats}.

%The predicate \begin{quote}\begin{verbatim}
%display(Term)\end{verbatim}\end{quote}
%\index{display/1}
%outputs the {\it Term} on the current output stream in the functor syntax,
%ignoring possible operator declarations.

%The predicate \begin{quote}\begin{verbatim}
%readvar(Stream, Term, VarList)\end{verbatim}\end{quote}
%%\index{readvar/3}
%can be used to read a term from the specified stream
%and obtain the list of variable names contained in the {\it Term}.
%{\it VarList} is a list of pairs {\tt [VarName\verb'|'Var]} where
%{\it VarName} is the atom corresponding to the variable name
%and {\it Var} is the corresponding variable.

When the flag \notationidx{variable_names} is switched off,
the output predicates are not able to write free variables
in their source form, i.e., with the correct variable names.
Then the variables are output in the form
\begin{quote}
\begin{verbatim}
_N
\end{verbatim}
\end{quote}
where \about{N} is a number which identifies the variable (but note that these
numbers may change on garbage collection and can therefore not be used to
identify the variable in a more permanent way).
Occasionally the number will be prefixed with the lower-case letter
\notation{l},
indicating that the variable is in a short-lived memory area called the
local stack (see \ref{chapmemory}).%
\index{variable!output}\index{output of variables}

%It is possible to pass any input stream to the {\eclipse} compiler
%using the predicate
%\index{compile_stream/1}
%\begin{quote}\begin{verbatim}
%compile_stream(Stream)\end{verbatim}\end{quote}
%and it is of course possible to mix the compilation with
%other input predicates.
%If, for example, the file {\bf a.pl} contains the following data
%\begin{quote}\begin{verbatim}
%p(1).
%p(2).
%end_of_file.
%p(3).
%\end{verbatim}\end{quote}
%it is possible to execute
%\begin{quote}\begin{verbatim}
%[eclipse 1]: open('a.pl', read, a).
%
%yes.
%[eclipse 2]: read(a, X).
%
%X = p(1)
%yes.
%[eclipse 3]: compile_stream(a).
%a.pl    compiled 40 bytes in 0.00 seconds
%
%yes.
%[eclipse 4]: read(a, X).
%
%X = p(3)
%yes.
%[eclipse 5]: p(X).
%
%X = 2
%yes.
%\end{verbatim}\end{quote}

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Newlines}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Newlines should be output using either
\bipref{nl/0}{../bips/kernel/iochar/nl-0.html},
\bipref{nl/1}{../bips/kernel/iochar/nl-1.html},
\bipref{writeln/1}{../bips/kernel/ioterm/writeln-1.html},
\bipref{writeln/2}{../bips/kernel/ioterm/writeln-2.html},
or using the \notation{\%n} format with
\bipref{printf/2}{../bips/kernel/ioterm/printf-2.html},
\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}.
All those will produce a LF or CRLF sequence, depending on the
stream property settings (see
\bipref{set_stream_property/3}%
{../bips/kernel/iostream/set_stream_property-3.html}).

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{General Parsing and Text Generation}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Reading and writing of I/O formats that cannot be handled by the methods
discussed above are probably best done using Definite Clause Grammar
(DCG) rules. See chapter \ref{dcg} for details.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Flushing}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
On most devices, output is buffered, i.e., any output does not appear
\index{buffered output}\index{output!buffered}
immediately on the file, pipe or socket, but goes into a buffer first.
To make sure the data is actually written to the device, the stream
usually has to be flushed using
\bipref{flush/1}{../bips/kernel/iostream/flush-1.html}.
If this is forgotten, the receiving end of a pipe or socket may hang
in a blocking read operation.

It is possible to configure a stream such that it is automatically
flushed at every line end (see
\bipref{set_stream_property/3}%
{../bips/kernel/iostream/set_stream_property-3.html}).

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Prompting}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Input streams on terminals can be configured to print a prompt
whenever input is required, see
\bipref{set_stream_property/3}%
{../bips/kernel/iostream/set_stream_property-3.html}.

%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\subsection{Positioning}
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Streams that are opened on files or strings can be positioned,
i.e., the read/write position can be moved forward or backwards.
This is not possible on pipes, sockets, queues and terminals.

To specify a position in the file
to write to or read from, the predicate
\bipref{seek/2}{../bips/kernel/iostream/seek-2.html}
is provided. The
call
\begin{quote}
\begin{verbatim}
seek(Stream, Pointer)
\end{verbatim}
\end{quote}
moves the current position in the
file (the 'file pointer') to the offset \about{Pointer} (a number specifying
the length in bytes) from
the start of the file.
If \about{Pointer} is the atom \notation{end_of_file}, the
current position is moved to the end of the file.
Hence a file could be open in \notation{append} mode using
\begin{quote}
\begin{verbatim}
open(File, update, Stream), seek(Stream, end_of_file)
\end{verbatim}
\end{quote}
The current position in a file may be found by the predicate
\bipref{at/2}{../bips/kernel/iostream/at-2.html}.
The call
\begin{quote}
\begin{verbatim}
at(Stream, Pointer)
\end{verbatim}
\end{quote}
unifies \about{Pointer} with the current position in the file.
The predicate
\begin{quote}
\begin{verbatim}
at_eof(Stream)
\end{verbatim}
\end{quote}
succeeds if the current position in the given stream
is at the file end.

%----------------------------------------------------------------------
\section{In-memory Streams}
%----------------------------------------------------------------------
There are two kinds of in-memory streams, string streams and queues.
String streams behave much like files, they can be read, written,
positioned etc, but they are implemented as buffer in memory.
Queues are intended mainly for message-passing-style communication
between \eclipse and a host language, and they are also implemented as
memory buffers.

\subsection{String Streams}
\label{stringio}
In {\eclipse} it is possible to associate a stream with a Prolog string
in its memory, and this string is then used in the same way as a file
for the input and output operations.
A string stream is opened like a file by a call to the
\bipref{open/3}{../bips/kernel/iostream/open-3.html} predicate:
\begin{quote}
\notation{open(string(\pattern{InitString}),~\pattern{Mode},~\pattern{Stream})}
\end{quote}
where \about{InitString} can be a {\eclipse} string or a variable and represents
the initial contents of the string stream.
If a variable is supplied for \about{InitString}, the initial value of the
string
stream is the empty string and the variable is bound to this value:
\begin{quote}
\begin{verbatim}
[eclipse 1]: open(string(S), update, s).
S = ""
yes.
\end{verbatim}
\end{quote}
Once a string stream is opened, all predicates using streams
can take it as argument and perform I/O on it.
In particular the predicates
\bipref{seek/2}{../bips/kernel/iostream/seek-2.html} and
\bipref{at/2}{../bips/kernel/iostream/at-2.html}
can be used with them.

While writing into a stream changes the stream contents destructively,
the initial string that has been opened will never be affected.
The new stream contents can be retrieved either by reading from the string
stream, or as a whole by using
\bipref{get_stream_info/3}{../bips/kernel/iostream/get_stream_info-3.html}:
\begin{quote}
\begin{verbatim}
[eclipse 1]: S = "abcdef", open(string(S), write, s), write(s, ---).

S = "abcdef"
yes.
[eclipse 2]: get_stream_info(s, name, S).

S = "---def"
yes.
[eclipse 3]: seek(s, 1), write(s, .), get_stream_info(s, name, S).

S = "-.-def"
yes.
[eclipse 4]: seek(s, end_of_file), write(s, ine),
             get_stream_info(s, name, S).

S = "-.-define"
yes.
\end{verbatim}
\end{quote}

\subsection{Queue streams}
\label{queueio}
A queue stream is opened by the
\bipref{open/3}{../bips/kernel/iostream/open-3.html} predicate:
\begin{quote}
\notation{open(queue(\pattern{InitString}),~\pattern{Mode},~\pattern{Stream})}
\end{quote}
The initial queue contents is \about{InitString}.
It can be seen as a string which gets extended at its end on writing
and consumed at its beginning on reading.
\begin{quote}
\begin{verbatim}
[eclipse 11]: open(queue(""), update, q), write(q, hello), write(q," wo").
yes.
[eclipse 12]: read_string(q, " ", "", _, X).
S = "hello"
yes.
[eclipse 13]: write(q, "rld"), read(q, X).
S = world
yes.
[eclipse 14]: at_eof(q).
yes.
\end{verbatim}
\end{quote}
It is not allowed to seek on a queue. Therefore, once something is read
from a queue, it is no longer accessible. A queue is considered to be
at its end-of-file position when it is currently empty, however this
is no longer the case when the queue is written again.

A useful feature of queues is that they can raise a synchronous event
when data arrives on the empty queue. To create such an event-raising
queue, this has to be specified as an option when opening the queue with
\bipref{open/4}{../bips/kernel/iostream/open-4.html}.
In the example we have chosen the same name for the stream and for the
event, which is not necessary but convenient when the same handler
is going to be used for different queues:
\begin{quote}
\begin{verbatim}
[eclipse 1]: [user].
 handle_queue_event(Q) :-
        read_string(Q, "", "", _, Data),
        printf("Queue %s received data: %s\n", [Q,Data]).
yes.
[eclipse 2]: set_event_handler(eventq, handle_queue_event/1).
yes.
[eclipse 3]: open(queue(""), update, eventq, [event(eventq)]).
yes.
[eclipse 4]: write(eventq, hello).
Queue eventq received data: hello
yes.
\end{verbatim}
\end{quote}

%----------------------------------------------------------------------
\section{Term Output Formats}
\label{secoutputformats}
%----------------------------------------------------------------------

\subsection{Write_term and Printf}

The way {\eclipse} terms are printed can be customised in a number of ways.
The most flexible predicates to print terms are
\bipref{write_term/3}{../bips/kernel/ioterm/write_term-3.html}
and
\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}.
They both allow all variants of term output, but the format is
specified in a different way.
\index{output options}
The following figure gives an overview.
\vfill %<<<<<<<<<<<<<<<<<<<<<<

\newlength{\WidthOne}\settowidth{\WidthOne}{\notation{variables(anonymous)}}
\newlength{\WidthTwo}\settowidth{\WidthTwo}{char~for}
\newlength{\WidthThree}\setlength{\WidthThree}{\textwidth}%
\addtolength{\WidthThree}{-\WidthOne}%
\addtolength{\WidthThree}{-\WidthTwo}%
\addtolength{\WidthThree}{-36pt}
\begin{center}
%\begin{tabular}{|p{3.5cm}|p{1.5cm}|p{10cm}|}
\begin{tabular}{|p{\WidthOne}|p{\WidthTwo}|p{\WidthThree}|}
\hline
\parbox{\WidthOne}{
  Output option for\\
  \predspec{write_term/2,3}
}
                        & \parbox{\WidthTwo}{Format\\
                                                char for\\
                                                printf\\
                                                \%..w}
                            & \parbox{\WidthThree}{Meaning} \\
\hline
\hline
\notation{as(term)}     &   & do not assume any particular meaning of the
                                                                printed term \\
\hline
\notation{as(clause)}   & \notation{C}
                             & print the term as a clause (apply clause
                                                            transformations) \\
\hline
\notation{as(goal)}     & \notation{G}
                             & print the term as a goal (apply goal
                                                            transformations) \\
\hline
\notation{attributes(none)}
                        &   & do not print any variable attributes \\
\hline
\notation{attributes(pretty)}
                        & \notation{m}
                            & print attributes using the corresponding print
                                                                    handlers \\
\hline
\notation{attributes(full)}
                        & \notation{M}
                            & print the full contents of all variable
                                                                   attributes\\
\hline
\notation{compact(false)}
                        &   & print extra blank space (around operators, after
                                        commas, etc.) for better readability \\
\hline
\notation{compact(true)}
                        & \notation{K}
                            & don't print blank space unless necessary \\
\hline
\notation{depth(\pattern{Max})}
                        & \notation{<\pattern{Max}>}
                            & print the term only up to a maximum nesting
                                    depth of \about{Max} (a positive integer) \\
\hline
\notation{depth(0)}     &   & observe the stream-specific or global flag
                                                      \notation{print_depth} \\
\hline
\notation{depth(full)}  & \notation{D}
                            & print the whole term (may loop when the term is
                                                                    cyclic!) \\
\hline
\notation{dotlists(false)}
                        &   & write lists in square bracket notation, e.g.,
                                                             \notation{[a,b]} \\
\hline
\notation{dotlists(true)}
                        & \notation{.}
                             & write lists as terms with functor
                                                               \predspec{./2} \\
\hline
\notation{newlines(false)}
                        &   & print newlines inside quotes as the escape
                                                           sequence \verb:\n: \\
\hline
\notation{newlines(true)}
                        & \notation{N}
                            & print newlines as line breaks even inside
                                                                       quotes \\
\hline
\notation{nl(false)}
                        &   & do not add a newline \\
\hline
\notation{nl(true)}
                        & \notation{L}
                            & print a newline sequence (as with nl/1) after
			      the term. If this is used together with the
			      fullstop(true) option, this newline serves as
			      the blank space after the fullstop \\
\hline
\notation{fullstop(false)}
                        &   & do not add a fullstop \\
\hline
\notation{fullstop(true)}
                        & \notation{F}
			    & terminate the term with a fullstop, so
			    it can be read back.  If necessary, an
			    extra space will be inserted before the
			    fullstop, in order to separate it from the
			    end of the term \\
\hline
\notation{numbervars(false)}
                        &   & do not treat \predspec{'\$VAR'/1} terms
                                                                    specially \\
\hline
\notation{numbervars(true)}
                        & \notation{I}
                            & print terms of the form
                             \notation{'\$VAR'(\pattern{N})} as named
                              variables: \notation{'\$VAR'(0)} is printed as
                              \notation{A}, \notation{'\$VAR'(25)}
                              as \notation{Z}, \notation{'\$VAR'(26)} as
                              \notation{A1} and so on. When the
                              argument is an atom or a string, just this
                              argument is printed. \\
\hline
\notation{operators(true)}
                        &   & obey operator declarations and print
                                                        prefix/infix/postfix \\
\hline
\notation{operators(false)}
                        & \notation{O}
                            & ignore operator declarations and print functor
                                                                    notation \\
\hline
\notation{portrayed(false)}
                        &   & do not use \predspec{portray/1,2} \\
\hline
\notation{portrayed(true)}
                        & \notation{P}
                            & call the user-defined predicate
                                          \predspec{portray/1,2} for printing \\
\hline
\notation{precedence(Prec)}
                        &   & print assuming given context precedence \\
\hline
\notation{quoted(false)}
                        &   & do not print quotes around strings or atoms \\
\hline
\notation{quoted(true)}
                        & \notation{Q}
                            & quote strings and atoms if necessary \\
\hline
\notation{transform(true)}
                        &   & apply portray transformations (write macros) \\
\hline
\notation{transform(false)}
                        & \notation{T}
                            & do not apply portray transformations (write
                                                                    macros). \\
\hline
\notation{variables(default)}
                        &   & print variables using their source name (if
                                                                   available) \\
\hline
\notation{variables(raw)}
                        & \notation{v}
                             & print variables using a system-generated name,
                                                       e.g., \notation{_123} \\
\hline
\notation{variables(full)}
                        & \notation{V}
                             & print variables using source name followed by a
                                          number, e.g., \notation{Alpha_132} \\
\hline
\notation{variables(anonymous)}
                        & \notation{_}
                             & print every variable as a simple underscore \\
\hline
\end{tabular}

Overview of term output options (see \predspec{write_term/3} for more details)
\label{outputoptions}
\end{center}
The
\bipref{write_term/2}{../bips/kernel/ioterm/write_term-2.html} and
\bipref{write_term/3}{../bips/kernel/ioterm/write_term-3.html}
predicates print a single {\eclipse} term and accept a list of
output options (first column in the table).

The
\bipref{printf/2}{../bips/kernel/ioterm/printf-2.html} and
\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}
predicates are similar to C's printf(3) function, but provide
additional format characters for printing {\eclipse} terms.
\index{format string}\index{output!format string}
The basic format string for printing arbitrary terms is \notation{\%w}.
Additional format characters can go between \notation{\%} and \notation{w},
according to the second column in the table.

For example, the following pairs of printing goals are equivalent:
\begin{quote}
\begin{verbatim}
printf("%mw",  [X])  <->   write_term(X, [attributes(pretty)])
printf("%O.w", [X])  <->   write_term(X, [operators(false),dotlist(true)])
printf("%5_w", [X])  <->   write_term(X, [depth(5),variables(anonymous)])
\end{verbatim}
\end{quote}

\subsection{Other Term Output Predicates}

The other term output predicates
\bipref{write/1}{../bips/kernel/ioterm/write-1.html},
\bipref{writeln/1}{../bips/kernel/ioterm/writeln-1.html},
\bipref{writeq/1}{../bips/kernel/ioterm/writeq-1.html},
\bipref{write_canonical/1}{../bips/kernel/ioterm/write_canonical-1.html},
\bipref{display/1}{../bips/kernel/ioterm/display-1.html},
\bipref{print/1}{../bips/kernel/ioterm/print-1.html}
can all be defined in terms of \predspec{write_term/2} (or, similarly
in terms of \predspec{printf/2}) as follows:
\begin{quote}
\begin{verbatim}
write(X)   :- write_term(X, [numbervars(true)]).
writeln(X) :- write_term(X, [numbervars(true)]), nl.
writeq(X)  :- write_term(X, [variables(raw), attributes(full),
              transform(false), quoted(true), depth(full),
              numbervars(true)]).
write_canonical(X) :-
              write_term(X, [variables(raw), attributes(full),
              transform(false), quoted(true), depth(full),
              dotlist(true), operators(false)]).
display(X) :- write_term(X, [dotlist(true), operators(false)]).
print(X)   :- write_term(X, [portrayed(true), numbervars(true)]).
\end{verbatim}
\end{quote}

\subsection{Default Output Options}

It is possible to set default output options for an output stream
in order to globally affect all output to this particular stream.
The
\bipref{set_stream_property/3}%
{../bips/kernel/iostream/set_stream_property-3.html}
predicate can be used to assign default options (in the same form as
accepted by \predspec{write_term/3}) to a stream.
These options will then be observed by all output predicates which do not
override the particular option.

%HEVEA\cutend

redpajama_set_name: RedPajamaGithub


text:
using System;
using UnityEngine;

namespace Devdog.General
{
    public class DestroyAfterSeconds : MonoBehaviour
    {
        public float seconds = 1f;

        protected void Awake()
        {
            Destroy(gameObject, seconds);
        }
    }
}


text:
package com.amazonaws.services.kinesis.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.kinesis.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * SplitShardRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SplitShardRequestMarshaller {

    private static final MarshallingInfo<String> STREAMNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StreamName").build();
    private static final MarshallingInfo<String> SHARDTOSPLIT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ShardToSplit").build();
    private static final MarshallingInfo<String> NEWSTARTINGHASHKEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NewStartingHashKey").build();

    private static final SplitShardRequestMarshaller instance = new SplitShardRequestMarshaller();

    public static SplitShardRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(SplitShardRequest splitShardRequest, ProtocolMarshaller protocolMarshaller) {

        if (splitShardRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(splitShardRequest.getStreamName(), STREAMNAME_BINDING);
            protocolMarshaller.marshall(splitShardRequest.getShardToSplit(), SHARDTOSPLIT_BINDING);
            protocolMarshaller.marshall(splitShardRequest.getNewStartingHashKey(), NEWSTARTINGHASHKEY_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
HRESULT CreateWriter(IXmlWriter** ppWriter);

//-----------------------------------------------------------------
//ƒeƒXƒg—pB'P'ÉSHCreateStreamOnFile()'ðŒÄ'ñ'ł邾'¯B
HRESULT CreateStreamFile(
	_In_   LPCTSTR pszFile,
	_In_   DWORD grfMode,
	_Out_  IStream **ppstm);

//-----------------------------------------------------------------
// IXmlWriter'ÌAPI'Ì'¤'¿PrintfŒ`Ž®'ÌFormat'Å•¶Žš—ñ'𐶐¬'Å'«'é'悤'É'µ'½'à'́B
class CXmlWriter
{
	_com_ptr_t<_com_IIID<IXmlWriter, &__uuidof(IXmlWriter)> > m_pWriter;
	HRESULT m_hr;

	inline HRESULT _SetError(HRESULT hr) { return m_hr = hr; }
#ifdef _DEBUG
#define SetError(expr) assert(SUCCEEDED(_SetError(expr)))
#else
#define SetError(expr) _SetError(expr)
#endif // DEBUG
public:
	CXmlWriter(IXmlWriter* ptr) : m_pWriter(ptr), m_hr(S_OK)
	{ }

	//printfŒ`Ž®'Å•¶Žš—ñƒf[ƒ^'ðì'é
	static std::vector<wchar_t> FormatV(LPCWSTR lpszFormat, va_list args);
	static std::vector<wchar_t> Format(LPCWSTR lpszFormat, ...);

	IXmlWriter* GetWriter();
	HRESULT GetError();

	//-----------------------------------------------------------------
	HRESULT SetOutput( _In_opt_  IUnknown *pOutput);
	HRESULT GetProperty( _In_  UINT nProperty, _Out_  LONG_PTR *ppValue);
	HRESULT SetProperty( _In_  UINT nProperty, _In_opt_  LONG_PTR pValue);
	HRESULT WriteAttributes( _In_  IXmlReader *pReader, _In_  BOOL fWriteDefaultAttributes);
	HRESULT WriteAttributeString( _In_opt_  LPCWSTR pwszPrefix, _In_opt_  LPCWSTR pwszLocalName, _In_opt_  LPCWSTR pwszNamespaceUri, _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteCData( _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteCharEntity( _In_  WCHAR wch);
	HRESULT WriteChars( _In_reads_opt_(cwch)  const WCHAR *pwch, _In_  UINT cwch);
	HRESULT WriteComment( _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteDocType( _In_opt_  LPCWSTR pwszName, _In_opt_  LPCWSTR pwszPublicId, _In_opt_  LPCWSTR pwszSystemId, _In_opt_  LPCWSTR pwszSubset);
	HRESULT WriteElementString( _In_opt_  LPCWSTR pwszPrefix, _In_  LPCWSTR pwszLocalName, _In_opt_  LPCWSTR pwszNamespaceUri, _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteEndDocument( void);
	HRESULT WriteEndElement( void);
	HRESULT WriteEntityRef( _In_  LPCWSTR pwszFormat, ...);
	HRESULT WriteFullEndElement( void);
	HRESULT WriteName( _In_  LPCWSTR pwszFormat, ...);
	HRESULT WriteNmToken( _In_  LPCWSTR pwszFormat, ...);
	HRESULT WriteNode( _In_  IXmlReader *pReader, _In_  BOOL fWriteDefaultAttributes);
	HRESULT WriteNodeShallow( _In_  IXmlReader *pReader, _In_  BOOL fWriteDefaultAttributes);
	HRESULT WriteProcessingInstruction( _In_  LPCWSTR pwszName, _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteQualifiedName( _In_  LPCWSTR pwszLocalName, _In_opt_  LPCWSTR pwszNamespaceUri);
	HRESULT WriteRaw( _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteRawChars( _In_reads_opt_(cwch)  const WCHAR *pwch, _In_  UINT cwch);
	HRESULT WriteStartDocument( _In_  XmlStandalone standalone);
	HRESULT WriteStartElement(	_In_opt_  LPCWSTR pwszPrefix, _In_  LPCWSTR pwszLocalName, _In_opt_  LPCWSTR pwszNamespaceUri);
	HRESULT WriteString( _In_opt_  LPCWSTR pwszFormat, ...);
	HRESULT WriteSurrogateCharEntity( _In_  WCHAR wchLow, _In_  WCHAR wchHigh);
	HRESULT WriteWhitespace( _In_opt_  LPCWSTR pwszWhitespace);
	HRESULT Flush( void);

};


text:
/*eslint-env mocha,node*/
/*global browser,by*/

//
// Imports
//
var chai = require("chai");
var assert = chai.assert;
var path = require("path");

var testsFile = path.join(__dirname, "e2e-debug.json");
var tests = require(testsFile).tests;
var servers = require(testsFile).server;
var ports = require(testsFile).ports;

//
// Functions
//
function run(testPath, file) {
	describe(testPath, function() {
		var fileName = file + ".html";

		it("Should pass " + testPath + "/" + fileName, function(done) {
			if (typeof browser.waitForAngularEnabled === "function") {
				browser.waitForAngularEnabled(false);
			}

			console.log(
				"Navigating to",
				"http://" + servers.main + ":" + ports.main + "/pages/" + testPath + "/" + fileName
			);

			browser.driver.executeScript("return navigator.userAgent;").then(function(ua) {
				console.log("User-Agent:", ua);
			});

			browser.driver.get("http://" + servers.main + ":" + ports.main + "/pages/" + testPath + "/" + fileName);

			// poll every 100ms for new logs or the test framework to note we're complete
			(function poll() {
				// get browser logs
				browser.manage().logs().get("browser").then(function(browserLog) {
					browserLog.forEach(function(log) {
						console.log("[" + new Date(log.timestamp).toLocaleTimeString() + "] " + log.message);
					});
				});

				// check if our element is there
				browser.isElementPresent(by.css("#BOOMR_test_complete"))
					.then(function(present) {
						if (!present) {
							setTimeout(poll, 100);

							return;
						}

						// get error messages
						browser.driver.executeScript("return BOOMR_test.isComplete()").then(function(complete) {
							assert.equal(complete, true, "BOOMR_test.isComplete()");

							console.log("Navigation complete");

							browser.driver.executeScript("return BOOMR_test.getTestFailureMessages()").then(function(testFailures) {
								if (testFailures.length > 0) {
									throw new Error(testFailures);
								}

								done();
							});
						});
					});
			})();
		});
	});
}

// NOTE: To use this, create a file e2e-debug.json (in this directory), the same format
// as e2e.json for the tests you want to run

//
// Run the tests in e2e-debug.json
//
for (var i = 0; i < tests.length; i++) {
	var data = tests[i];

	console.log("Running " + data.path + "/" + data.file);

	run(data.path, data.file);
}


text:
import { AutoSpatialMethodType } from "../Enums";
import { SpatialOptions } from "../Spatial";

export interface AutoSpatialOptions extends SpatialOptions {
    methodType: AutoSpatialMethodType;
    methodArguments: string[];
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using AutoMapper;
using Neemo.Orders;

namespace Neemo.CarParts.EntityFramework
{
    public class OrderRepository : IOrderRepository
    {
        public void CreateOrder(Order order)
        {
            using (var context = DbContextFactory.Create())
            {
                var dbOrder = Mapper.Map<Orders.Order, Models.OrderHeader>(order);

                // Hard code the db order here ( for the moment )
                dbOrder.OrderStatusID = 1;

                context.OrderHeaders.Add(dbOrder);

                context.SaveChanges();

                // Map the Id's back
                order.OrderId = dbOrder.OrderHeaderID;
            }
        }

        public IEnumerable<Order> GetOrdersForUser(string username)
        {
            using (var context = DbContextFactory.Create())
            {
                var dbOrders = context.OrderHeaders
                    .Where(o => o.UserName.Equals(username, StringComparison.OrdinalIgnoreCase) && o.Active)
                    .Include(o => o.OrderDetails)
                    .ToList();

                return dbOrders.Select(Mapper.Map<Models.OrderHeader, Orders.Order>);
            }
        }

        public Order GetOrder(int? orderId)
        {
            using (var context = DbContextFactory.Create())
            {
                var dbOrder = context.OrderHeaders
                    .Where(o => o.OrderHeaderID == orderId && o.Active == true)
                    .Include(o => o.OrderDetails)
                    .FirstOrDefault();

                if (dbOrder == null)
                {
                    return null;
                }

                return Mapper.Map<Models.OrderHeader, Orders.Order>(dbOrder);
            }
        }
    }
}


text:
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// import { getAllGuests } from 'actions/guest'
import { loadConfig } from 'actions/config'
import { requestListPersonGroups } from 'actions/group'

// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)

// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')

let render = () => {
  const routes = require('./routes/index').default(store)

  ReactDOM.render(
    <AppContainer store={store} routes={routes} />,
    MOUNT_NODE
  )
  // Kickoff some API calls
  // store.dispatch(getAllGuests())
  store.dispatch(loadConfig())
  store.dispatch(requestListPersonGroups())
}

// This code is excluded from production bundle
if (__DEV__) {
  window.__redux_store = store

  if (module.hot) {
    // Development render functions
    const renderApp = render
    const renderError = (error) => {
      const RedBox = require('redbox-react').default

      ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
    }

    // Wrap render in try/catch
    render = () => {
      try {
        renderApp()
      } catch (error) {
        console.error(error)
        renderError(error)
      }
    }

    // Setup hot module replacement
    module.hot.accept('./routes/index', () =>
      setImmediate(() => {
        ReactDOM.unmountComponentAtNode(MOUNT_NODE)
        render()
      })
    )
  }
}

// ========================================================
// Go!
// ========================================================
render()


text:
package alien4cloud.utils;

import java.util.HashMap;
import java.util.Map;

import alien4cloud.rest.utils.JsonUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Maps;

/**
 * Utility class to ease map manipulation.
 */
public final class MapUtil {
    private MapUtil() {
    }

    /**
     * Try to get a value following a path in the map. For example :
     * MapUtil.get(map, "a.b.c") correspond to:
     * map.get(a).get(b).get(c)
     *
     * @param map the map to search for path
     * @param path keys in the map separated by '.'
     */
    public static Object get(Map<String, ? extends Object> map, String path) {
        String[] tokens = path.split("\\.");
        if (tokens.length == 0) {
            return null;
        } else {
            Object value = map;
            for (String token : tokens) {
                if (!(value instanceof Map)) {
                    return null;
                } else {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> nested = (Map<String, Object>) value;
                    value = nested.get(token);
                    if (value == null) {
                        return null;
                    }
                }
            }
            return value;
        }
    }

    /**
     * Create a new hash map and fills it from the given keys and values (keys[index] -> values[index].
     *
     * @param keys The array of keys.
     * @param values The array of values.
     * @return A map that contains for each key element in the keys array a value from the values array at the same index.
     */
    public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
        Map<K, V> map = new HashMap<K, V>();
        if (keys == null || values == null || keys.length != values.length) {
            throw new IllegalArgumentException("keys and values must be non-null and have the same size.");
        }
        for (int i = 0; i < keys.length; i++) {
            map.put(keys[i], values[i]);
        }
        return map;
    }

    /**
     * Revert a map key --> value become value --> key
     *
     * @param map the map to revert
     * @param <K> the type of the key
     * @param <V> the type of the value
     * @return reverted map
     */
    public static <K, V> Map<V, K> revert(Map<K, V> map) {
        Map<V, K> reverted = new HashMap<V, K>();
        for (Map.Entry<K, V> entry : map.entrySet()) {
            reverted.put(entry.getValue(), entry.getKey());
        }
        return reverted;
    }

    /**
     * Remove the entry with 'oldKey' and put it (if exists) using 'newKey' unless if an entry already exist for 'newKey'.
     */
    public static <K, V> void replaceKey(Map<K, V> map, K oldKey, K newKey) {
        if (map == null || map.isEmpty()) {
            return;
        }
        if (map.containsKey(newKey)) {
            return;
        }
        V o = map.remove(oldKey);
        if (o != null) {
            map.put(newKey, o);
        }
    }

    public static Map<String, String> toString(Map<String, Object> stringObjectMap) throws JsonProcessingException {
        Map<String, String> stringStringMap = Maps.newHashMap();
        for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
            if (stringObjectEntry.getValue() != null) {
                if (stringObjectEntry.getValue() instanceof String) {
                    stringStringMap.put(stringObjectEntry.getKey(), (String) stringObjectEntry.getValue());
                } else {
                    stringStringMap.put(stringObjectEntry.getKey(), JsonUtil.toString(stringObjectEntry.getValue()));
                }
            } else {
                stringStringMap.put(stringObjectEntry.getKey(), null);
            }

        }
        return stringStringMap;
    }
}


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

        <title>Ordering notice - node.js test</title>

Ordering notice

        {{ "test" }}

Dear {{person_name}},

Thanks for placing an order from {{ company }}. It's scheduled to
        ship on {{ ship_date|date:"F j, Y" }}.

Here are the items you've ordered:

        {% for item in item_list %}

{{ forloop.revcounter0 }}: {{ item }} {{ forloop.counter|add:"1000" }}

        {% endfor %}

        {% if ordered_warranty or true or false %}

Your warranty information will be included in the packaging.

        {% else %}

You didn't order a warranty, so you're on your own when
            the products inevitably stop working.

        {% endif %}

        {{ship.name}}{{ ship.nationality.toUpperCase }}

Sincerely,
{{ company }}


text:
package org.apache.flink.runtime.util.jartestprogram;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;

/**
 * Similar to {@link FilterLambda1}, but the filter lambda is directly passed to {@link DataSet#filter(FilterFunction)}.
 */
public class FilterLambda2 {

	public static void main(String[] args) throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		DataSet<String> input = env.fromElements("Please filter", "the words", "but not this");

		DataSet<String> output = input.filter((v) -> WordFilter.filter(v));
		output.print();

		env.execute();
	}
}


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Slider;
use app\models\SliderSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\User;
use yii\web\UploadedFile;
use yii\imagine\Image;
use Imagine\Image\Box;

/**
 * SliderController implements the CRUD actions for Slider model.
 */
class SliderController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create','admin','update','delete'],
                'rules' => [
                    [
                        'actions' => ['create','admin','update','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return User::isAdmin();
                        }
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Slider models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SliderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $lol=[5,7];

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'lol'=>$lol
        ]);
    }

    /**
     * Displays a single Slider model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Slider model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Slider();
        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            if($model->imageFile){
                $imageName=time(). '.' . $model->imageFile->extension;
                $model->imageFile->saveAs('images/slider/' . $imageName);
                $model->image=$imageName;
                $this->resize($imageName);
            }
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Slider model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            if($model->imageFile){
                $imageName=time(). '.' . $model->imageFile->extension;
                $model->imageFile->saveAs('images/slider/' . $imageName);
                $model->image=$imageName;
                $this->resize($imageName);
            }
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    protected function resize($imageName){
        $webroot=Yii::getAlias('@webroot');
        $imagine=Image::getImagine()->open('images/slider/'.$imageName);
        $imagine->thumbnail(new Box(1170, 2000))->save($webroot.'/images/slider/'.$imageName);

        $imagine=Image::getImagine()->open('images/slider/'.$imageName);
        $height=$imagine->getSize()->getHeight();
        if($height>500) $cHeight=($height-500)/1.3; else $cHeight=0;
        Image::crop($webroot.'/images/slider/'.$imageName,1170,500,[0,$cHeight])->save($webroot.'/images/slider/'.$imageName);
        $imagine->thumbnail(new Box(180, 100))->save($webroot.'/images/slider/s_'.$imageName, ['quality' => 90]);
    }

    /**
     * Deletes an existing Slider model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Slider model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Slider the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Slider::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
**The Markdown2Social utility converts simple Markdown documents to Google+
posts ready to be shared on the social network.**  There is room for writing
output plugins for other target sites, but at the moment only Google+ is
supported.

This is not an official Google product.

## Why?

Long-form posts on social networks are more engaging than simply posting a bare
link to the exact same content hosted elsewhere.  However, composing long-form
posts on social networks is not a pleasant experience because their editors are
not designed to support long posts and because their formatting options are
severely limited.

What if you could write that same content in a more durable and flexible format,
say Markdown, and later export the text to the formats accepted by the networks
of your choice?  This would let you compose your posts using the myriad of
editors that support Markdown, would let you store those posts in a version
control system, and may even let you republish that same content directly on
your site with ease.

This is exactly the goal of Markdown2Social: to let you store your articles'
master copies in a version control system while providing a mechanism to extract
a simplified version that can be shared in a social network.  Does this work?
For the most part yes, but there are obvious limitations; keep reading.

## Download

The latest version of Markdown2Social is 0.3 and was released on
January 14th, 2016.

Download: [markdown2social-0.3](../../releases/tag/markdown2social-0.3)

See the [release notes](NEWS.md) for information about the changes in this and
all previous releases.

## Installation

Using `pip`:

```
$ pip install -r requirements.txt
$ pip install markdown2social
```

From sources after cloning the tree from GitHub:

```shell
$ pip install -r requirements.txt
$ ./setup.py install
```

See the [detailed installation instructions](INSTALL.md) for additional
information.

## Usage

1. Use `markdown2social` as a filter or with explicit file names to generate
   a `.gplus` file:

   ```shell
   $ markdown2social <doc.md >doc.gplus
   $ markdown2social -o doc.gplus doc.md
   ```

1. Open the `.gplus` file in your favorite editor.

1. Copy the whole contents to the clipboard.

1. Paste them into a new Google+ post.

1. Hit share and voilà!


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
	xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
			http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
	<description><![CDATA[
		Main entry point for spring configuration
	]]></description>

	<!-- context -->
	<context:component-scan base-package="com.highway2urhell" />
	<context:property-placeholder location="classpath:source.properties" />

	<context:annotation-config  />

	<!-- task -->
	<task:annotation-driven executor="myExecutor"
		scheduler="myScheduler" />
	<task:executor id="myExecutor" pool-size="5" />
	<task:scheduler id="myScheduler" pool-size="10" />

</beans>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="exclude">

<TITLE>
Uses of Interface java.lang.CharSequence (Java 2 Platform SE 5.0)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
java.lang.CharSequence

Packages that use CharSequence

java.io
Provides for system input and output through data streams,
serialization and the file system.

java.lang
Provides classes that are fundamental to the design of the Java
programming language.

java.nio
Defines buffers, which are containers for data, and provides an overview of the
other NIO packages.

java.nio.charset
Defines charsets, decoders, and encoders, for translating between bytes and
Unicode characters.

java.util.regex
Classes for matching character sequences against patterns specified by regular
expressions.

Uses of CharSequence in java.io

Methods in java.io with parameters of type CharSequence

 StringWriter
StringWriter.append(CharSequence csq)

          Appends the specified character sequence to this writer.

 CharArrayWriter
CharArrayWriter.append(CharSequence csq)

          Appends the specified character sequence to this writer.

 Writer
Writer.append(CharSequence csq)

          Appends the specified character sequence to this writer.

 PrintWriter
PrintWriter.append(CharSequence csq)

          Appends the specified character sequence to this writer.

 PrintStream
PrintStream.append(CharSequence csq)

          Appends the specified character sequence to this output stream.

 StringWriter
StringWriter.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this writer.

 CharArrayWriter
CharArrayWriter.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this writer.

 Writer
Writer.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this writer.

 PrintWriter
PrintWriter.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this writer.

 PrintStream
PrintStream.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this output
 stream.

Uses of CharSequence in java.lang

Classes in java.lang that implement CharSequence

 class
String

          The String class represents character strings.

 class
StringBuffer

          A thread-safe, mutable sequence of characters.

 class
StringBuilder

          A mutable sequence of characters.

Methods in java.lang that return CharSequence

 CharSequence
StringBuffer.subSequence(int start,
            int end)

 CharSequence
CharSequence.subSequence(int start,
            int end)

          Returns a new CharSequence that is a subsequence of this sequence.

 CharSequence
String.subSequence(int beginIndex,
            int endIndex)

          Returns a new character sequence that is a subsequence of this sequence.

Methods in java.lang with parameters of type CharSequence

 StringBuilder
StringBuilder.append(CharSequence s)

 StringBuffer
StringBuffer.append(CharSequence s)

          Appends the specified CharSequence to this
 sequence.

 Appendable
Appendable.append(CharSequence csq)

          Appends the specified character sequence to this <tt>Appendable</tt>.

 StringBuilder
StringBuilder.append(CharSequence s,
       int start,
       int end)

 StringBuffer
StringBuffer.append(CharSequence s,
       int start,
       int end)

 Appendable
Appendable.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the specified character sequence to this
 <tt>Appendable</tt>.

static int
Character.codePointAt(CharSequence seq,
            int index)

          Returns the code point at the given index of the
 CharSequence.

static int
Character.codePointBefore(CharSequence seq,
                int index)

          Returns the code point preceding the given index of the
 CharSequence.

static int
Character.codePointCount(CharSequence seq,
               int beginIndex,
               int endIndex)

          Returns the number of Unicode code points in the text range of
 the specified char sequence.

 boolean
String.contains(CharSequence s)

          Returns true if and only if this string contains the specified
 sequence of char values.

 boolean
String.contentEquals(CharSequence cs)

          Returns <tt>true</tt> if and only if this <tt>String</tt> represents
 the same sequence of char values as the specified sequence.

 StringBuilder
StringBuilder.insert(int dstOffset,
       CharSequence s)

 StringBuffer
StringBuffer.insert(int dstOffset,
       CharSequence s)

 StringBuilder
StringBuilder.insert(int dstOffset,
       CharSequence s,
       int start,
       int end)

 StringBuffer
StringBuffer.insert(int dstOffset,
       CharSequence s,
       int start,
       int end)

static int
Character.offsetByCodePoints(CharSequence seq,
                   int index,
                   int codePointOffset)

          Returns the index within the given char sequence that is offset
 from the given index by codePointOffset
 code points.

 String
String.replace(CharSequence target,
        CharSequence replacement)

          Replaces each substring of this string that matches the literal target
 sequence with the specified literal replacement sequence.

Constructors in java.lang with parameters of type CharSequence

StringBuffer(CharSequence seq)

          Constructs a string buffer that contains the same characters
 as the specified CharSequence.

StringBuilder(CharSequence seq)

          Constructs a string builder that contains the same characters
 as the specified CharSequence.

Uses of CharSequence in java.nio

Classes in java.nio that implement CharSequence

 class
CharBuffer

          A character buffer.

Methods in java.nio that return CharSequence

abstract  CharSequence
CharBuffer.subSequence(int start,
            int end)

          Creates a new character buffer that represents the specified subsequence
 of this buffer, relative to the current position.

Methods in java.nio with parameters of type CharSequence

 CharBuffer
CharBuffer.append(CharSequence csq)

          Appends the specified character sequence  to this
 buffer  (optional operation).

 CharBuffer
CharBuffer.append(CharSequence csq,
       int start,
       int end)

          Appends a subsequence of the  specified character sequence  to this
 buffer  (optional operation).

static CharBuffer
CharBuffer.wrap(CharSequence csq)

          Wraps a string into a buffer.

static CharBuffer
CharBuffer.wrap(CharSequence csq,
     int start,
     int end)

          Wraps a character sequence into a buffer.

Uses of CharSequence in java.nio.charset

Methods in java.nio.charset with parameters of type CharSequence

 boolean
CharsetEncoder.canEncode(CharSequence cs)

          Tells whether or not this encoder can encode the given character
 sequence.

Uses of CharSequence in java.util.regex

Methods in java.util.regex with parameters of type CharSequence

 Matcher
Pattern.matcher(CharSequence input)

          Creates a matcher that will match the given input against this pattern.

static boolean
Pattern.matches(String regex,
        CharSequence input)

          Compiles the given regular expression and attempts to match the given
 input against it.

 Matcher
Matcher.reset(CharSequence input)

          Resets this matcher with a new input sequence.

 String[]
Pattern.split(CharSequence input)

          Splits the given input sequence around matches of this pattern.

 String[]
Pattern.split(CharSequence input,
      int limit)

          Splits the given input sequence around matches of this pattern.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
const TWO_PI = Math.PI * 2;
const HALF_PI = Math.PI * 0.5;
// canvas settings
var viewWidth = screen.width,
    viewHeight = screen.height,
    viewCenterX = viewWidth * 0.5,
    viewCenterY = viewHeight * 0.5,
    drawingCanvas = document.getElementById("drawing_canvas"),
    ctx,
    timeStep = (1/60),
    time = 0;

var ppm = 18, // pixels per meter
    physicsWidth = viewWidth / ppm,
    physicsHeight = viewHeight / ppm,
    physicsCenterX = physicsWidth * 0.5,
    physicsCenterY = physicsHeight * 0.75;

var world;

var wheel,
    arrow,
    mouseBody,
    mouseConstraint;

var arrowMaterial,
    pinMaterial,
    contactMaterial;

var wheelSpinning = false,
    wheelStopped = true;

var particles = [];

var statusLabel = document.getElementById('status_label');

window.onload = function() {
    initDrawingCanvas();
    initPhysics();

    requestAnimationFrame(loop);

    statusLabel.innerHTML = 'Give it a good spin!';
};

function initDrawingCanvas() {
    drawingCanvas.width = viewWidth;
    drawingCanvas.height = viewHeight;
    ctx = drawingCanvas.getContext('2d');

    drawingCanvas.addEventListener('mousemove', updateMouseBodyPosition);
    drawingCanvas.addEventListener('mousedown', checkStartDrag);
    drawingCanvas.addEventListener('mouseup', checkEndDrag);
    drawingCanvas.addEventListener('mouseout', checkEndDrag);
}

function updateMouseBodyPosition(e) {
    var p = getPhysicsCoord(e);
    mouseBody.position[0] = p.x;
    mouseBody.position[1] = p.y;
}

function checkStartDrag(e) {
    if (world.hitTest(mouseBody.position, [wheel.body])[0]) {

        mouseConstraint = new p2.RevoluteConstraint(mouseBody, wheel.body, {
            worldPivot:mouseBody.position,
            collideConnected:false
        });

        world.addConstraint(mouseConstraint);
    }

    if (wheelSpinning === true) {
        wheelSpinning = false;
        wheelStopped = true;
        statusLabel.innerHTML = "Impatience will not be rewarded.";
    }
}

function checkEndDrag(e) {
    if (mouseConstraint) {
        world.removeConstraint(mouseConstraint);
        mouseConstraint = null;

        if (wheelSpinning === false && wheelStopped === true) {
            if ( Math.abs(wheel.body.angularVelocity) > 7.5) {
                wheelSpinning = true;
                wheelStopped = false;
                console.log('good spin');
                statusLabel.innerHTML = '...clack clack clack clack clack clack...'
            }
            else {
                console.log('sissy');
                statusLabel.innerHTML = 'Come on, you can spin harder than that.'
            }
        }
    }
}

function getPhysicsCoord(e) {
    var rect = drawingCanvas.getBoundingClientRect(),
        x = (e.clientX - rect.left) / ppm,
        y = physicsHeight - (e.clientY - rect.top) / ppm;

    return {x:x, y:y};
}

function initPhysics() {
    world = new p2.World();
    world.solver.iterations = 100;
    world.solver.tolerance = 0;

    arrowMaterial = new p2.Material();
    pinMaterial = new p2.Material();
    contactMaterial = new p2.ContactMaterial(arrowMaterial, pinMaterial, {
        friction:0.0,
        restitution:0.1
    });
    world.addContactMaterial(contactMaterial);

    var wheelRadius = 8,
        wheelX = physicsCenterX,
        wheelY = wheelRadius + 4,
        arrowX = wheelX,
        arrowY = wheelY + wheelRadius + 0.625;

//    wheel = new Wheel(wheelX, wheelY, wheelRadius, 32, 0.25, 7.5);
    wheel = new Wheel(wheelX, wheelY, wheelRadius, 3, 0.25, 7.5);

    wheel.body.angle = (Math.PI / 32.5);
    wheel.body.angularVelocity = 5;
    arrow = new Arrow(arrowX, arrowY, 0.5, 1.5);
    mouseBody = new p2.Body();

    world.addBody(mouseBody);
}

function spawnPartices() {
    for (var i = 0; i < 200; i++) {
        var p0 = new Point(viewCenterX, viewCenterY - 64);
        var p1 = new Point(viewCenterX, 0);
        var p2 = new Point(Math.random() * viewWidth, Math.random() * viewCenterY);
        var p3 = new Point(Math.random() * viewWidth, viewHeight + 64);

        particles.push(new Particle(p0, p1, p2, p3));
    }
}

function update() {
    particles.forEach(function(p) {
        p.update();
        if (p.complete) {
            particles.splice(particles.indexOf(p), 1);
        }
    });

    // p2 does not support continuous collision detection :(
    // but stepping twice seems to help
    // considering there are only a few bodies, this is ok for now.
    world.step(timeStep * 0.5);
    world.step(timeStep * 0.5);

    if (wheelSpinning === true && wheelStopped === false &&
        wheel.body.angularVelocity < 1 && arrow.hasStopped()) {

        var win = wheel.gotLucky();

        wheelStopped = true;
        wheelSpinning = false;

        wheel.body.angularVelocity = 0;

        if (win) {
            spawnPartices();
            statusLabel.innerHTML = 'Woop woop!'
        }
        else {
            statusLabel.innerHTML = 'Too bad! Invite a Facebook friend to try again!';
        }
    }
}

function draw() {
    // ctx.fillStyle = '#fff';
    ctx.clearRect(0, 0, viewWidth, viewHeight);

    wheel.draw();
    arrow.draw();

    particles.forEach(function(p) {
        p.draw();
    });
}

function loop() {
    update();
    draw();

    requestAnimationFrame(loop);
}

/////////////////////////////
// wheel of fortune
/////////////////////////////
function Wheel(x, y, radius, segments, pinRadius, pinDistance) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.segments = segments;
    this.pinRadius = pinRadius;
    this.pinDistance = pinDistance;

    this.pX = this.x * ppm;
    this.pY = (physicsHeight - this.y) * ppm;
    this.pRadius = this.radius * ppm;
    this.pPinRadius = this.pinRadius * ppm;
    this.pPinPositions = [];

    this.deltaPI = TWO_PI / this.segments;

    this.createBody();
    this.createPins();
}
Wheel.prototype = {
    createBody:function() {
        this.body = new p2.Body({mass:1, position:[this.x, this.y]});
        this.body.angularDamping = 0.0;
        this.body.addShape(new p2.Circle(this.radius));
        this.body.shapes[0].sensor = true; //TODO use collision bits instead

        var axis = new p2.Body({position:[this.x, this.y]});
        var constraint = new p2.LockConstraint(this.body, axis);
        constraint.collideConnected = false;

        world.addBody(this.body);
        world.addBody(axis);
        world.addConstraint(constraint);
    },
    createPins:function() {
        var l = this.segments,
            pin = new p2.Circle(this.pinRadius);

        pin.material = pinMaterial;

        for (var i = 0; i < l; i++) {
            var x = Math.cos(i / l * TWO_PI) * this.pinDistance,
                y = Math.sin(i / l * TWO_PI) * this.pinDistance;

            this.body.addShape(pin, [x, y]);
            this.pPinPositions[i] = [x * ppm, -y * ppm];
        }
    },
    gotLucky:function() {
        var currentRotation = wheel.body.angle % TWO_PI,
            currentSegment = Math.floor(currentRotation / this.deltaPI);

        return (currentSegment % 2 === 0);
    },
    draw:function() {
        // TODO this should be cached in a canvas, and drawn as an image
        // also, more doodads
        ctx.save();
        ctx.translate(this.pX, this.pY);

        ctx.beginPath();
        ctx.fillStyle = '#DB9E36';
        ctx.arc(0, 0, this.pRadius + 24, 0, TWO_PI);
        ctx.fill();
//        ctx.fillRect(-12, 0, 24, 400);

        ctx.rotate(-this.body.angle);

        for (var i = 0; i < this.segments; i++) {
//            ctx.fillStyle = (i % 2 === 0) ? '#BD4932' : '#FFFAD5';
                if(i==0){
                ctx.fillStyle ='#BD4932';
                }
                else if(i==1){
                ctx.fillStyle ='#FFFAD5';

                }
                else if(i==2){
                ctx.fillStyle ='#004878';

                }

            ctx.beginPath();
            ctx.arc(0, 0, this.pRadius, i * this.deltaPI, (i + 1) * this.deltaPI);
            ctx.lineTo(0, 0);
            ctx.closePath();
            ctx.fill();
        }

        ctx.fillStyle = '#401911';

        this.pPinPositions.forEach(function(p) {
            ctx.beginPath();
            ctx.arc(p[0], p[1], this.pPinRadius, 0, TWO_PI);
            ctx.fill();
        }, this);

        ctx.restore();
    }
};
/////////////////////////////
// arrow on top of the wheel of fortune
/////////////////////////////
function Arrow(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.verts = [];

    this.pX = this.x * ppm;
    this.pY = (physicsHeight - this.y) * ppm;
    this.pVerts = [];

    this.createBody();
}
Arrow.prototype = {
    createBody:function() {
        this.body = new p2.Body({mass:1, position:[this.x, this.y]});
        this.body.addShape(this.createArrowShape());

        var axis = new p2.Body({position:[this.x, this.y]});
        var constraint = new p2.RevoluteConstraint(this.body, axis, {
            worldPivot:[this.x, this.y]
        });
        constraint.collideConnected = false;

        var left = new p2.Body({position:[this.x - 2, this.y]});
        var right = new p2.Body({position:[this.x + 2, this.y]});
        var leftConstraint = new p2.DistanceConstraint(this.body, left, {
            localAnchorA:[-this.w * 2, this.h * 0.25],
            collideConnected:false
        });
        var rightConstraint = new p2.DistanceConstraint(this.body, right, {
            localAnchorA:[this.w * 2, this.h * 0.25],
            collideConnected:false
        });
        var s = 32,
            r = 4;

        leftConstraint.setStiffness(s);
        leftConstraint.setRelaxation(r);
        rightConstraint.setStiffness(s);
        rightConstraint.setRelaxation(r);

        world.addBody(this.body);
        world.addBody(axis);
        world.addConstraint(constraint);
        world.addConstraint(leftConstraint);
        world.addConstraint(rightConstraint);
    },

    createArrowShape:function() {
        this.verts[0] = [0, this.h * 0.25];
        this.verts[1] = [-this.w * 0.5, 0];
        this.verts[2] = [0, -this.h * 0.75];
        this.verts[3] = [this.w * 0.5, 0];

        this.pVerts[0] = [this.verts[0][0] * ppm, -this.verts[0][1] * ppm];
        this.pVerts[1] = [this.verts[1][0] * ppm, -this.verts[1][1] * ppm];
        this.pVerts[2] = [this.verts[2][0] * ppm, -this.verts[2][1] * ppm];
        this.pVerts[3] = [this.verts[3][0] * ppm, -this.verts[3][1] * ppm];

        var shape = new p2.Convex(this.verts);
        shape.material = arrowMaterial;

        return shape;
    },
    hasStopped:function() {
        var angle = Math.abs(this.body.angle % TWO_PI);

        return (angle < 1e-3 || (TWO_PI - angle) < 1e-3);
    },
    update:function() {

    },
    draw:function() {
        ctx.save();
        ctx.translate(this.pX, this.pY);
        ctx.rotate(-this.body.angle);

        ctx.fillStyle = '#401911';

        ctx.beginPath();
        ctx.moveTo(this.pVerts[0][0], this.pVerts[0][1]);
        ctx.lineTo(this.pVerts[1][0], this.pVerts[1][1]);
        ctx.lineTo(this.pVerts[2][0], this.pVerts[2][1]);
        ctx.lineTo(this.pVerts[3][0], this.pVerts[3][1]);
        ctx.closePath();
        ctx.fill();

        ctx.restore();
    }
};
/////////////////////////////
// your reward
/////////////////////////////
Particle = function(p0, p1, p2, p3) {
    this.p0 = p0;
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;

    this.time = 0;
    this.duration = 3 + Math.random() * 2;
    this.color =  'hsl(' + Math.floor(Math.random() * 360) + ',100%,50%)';

    this.w = 10;
    this.h = 7;

    this.complete = false;
};
Particle.prototype = {
    update:function() {
        this.time = Math.min(this.duration, this.time + timeStep);

        var f = Ease.outCubic(this.time, 0, 1, this.duration);
        var p = cubeBezier(this.p0, this.p1, this.p2, this.p3, f);

        var dx = p.x - this.x;
        var dy = p.y - this.y;

        this.r =  Math.atan2(dy, dx) + HALF_PI;
        this.sy = Math.sin(Math.PI * f * 10);
        this.x = p.x;
        this.y = p.y;

        this.complete = this.time === this.duration;
    },
    draw:function() {
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.rotate(this.r);
        ctx.scale(1, this.sy);

        ctx.fillStyle = this.color;
        ctx.fillRect(-this.w * 0.5, -this.h * 0.5, this.w, this.h);

        ctx.restore();
    }
};
Point = function(x, y) {
    this.x = x || 0;
    this.y = y || 0;
};
/////////////////////////////
// math
/////////////////////////////
/**
 * easing equations from http://gizma.com/easing/
 * t = current time
 * b = start value
 * c = delta value
 * d = duration
 */
var Ease = {
    inCubic:function (t, b, c, d) {
        t /= d;
        return c*t*t*t + b;
    },
    outCubic:function(t, b, c, d) {
        t /= d;
        t--;
        return c*(t*t*t + 1) + b;
    },
    inOutCubic:function(t, b, c, d) {
        t /= d/2;
        if (t < 1) return c/2*t*t*t + b;
        t -= 2;
        return c/2*(t*t*t + 2) + b;
    },
    inBack: function (t, b, c, d, s) {
        s = s || 1.70158;
        return c*(t/=d)*t*((s+1)*t - s) + b;
    }
};

function cubeBezier(p0, c0, c1, p1, t) {
    var p = new Point();
    var nt = (1 - t);

    p.x = nt * nt * nt * p0.x + 3 * nt * nt * t * c0.x + 3 * nt * t * t * c1.x + t * t * t * p1.x;
    p.y = nt * nt * nt * p0.y + 3 * nt * nt * t * c0.y + 3 * nt * t * t * c1.y + t * t * t * p1.y;

    return p;
}


text:
//
//  Copyright (c) 2014-2015 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <XCTest/XCTestDefines.h>

NS_ASSUME_NONNULL_BEGIN

#if XCT_UI_TESTING_AVAILABLE

/*!
 * @enum XCUIRemoteButton
 *
 * A button on a physical remote control.
 */
typedef NS_ENUM(NSUInteger, XCUIRemoteButton) {
    XCUIRemoteButtonUp          = 0,
    XCUIRemoteButtonDown        = 1,
    XCUIRemoteButtonLeft        = 2,
    XCUIRemoteButtonRight       = 3,

    XCUIRemoteButtonSelect      = 4,
    XCUIRemoteButtonMenu        = 5,
    XCUIRemoteButtonPlayPause   = 6,
};

#if TARGET_OS_TV

/*!
 * @class XCUIRemote
 *
 * Simulates interaction with a physical remote control.
 */
NS_CLASS_AVAILABLE_IOS(9_0)
@interface XCUIRemote : NSObject

/*!
 * The simulated physical remote control.
 */
+ (instancetype)sharedRemote;

/*!
 * Sends a momentary press of a button on a physical remote control.
 *
 * @param remoteButton
 * The button on the physical remote control for which to synthesize a press.
 */
- (void)pressButton:(XCUIRemoteButton)remoteButton;

/*!
 * Sends a press and hold of a button on a physical remote control, holding for the specified duration.
 *
 * @param remoteButton
 * The button on the physical remote control for which to synthesize a press.
 *
 * @param duration
 * Duration in seconds.
 */
- (void)pressButton:(XCUIRemoteButton)remoteButton forDuration:(NSTimeInterval)duration;

@end

#endif

#endif

NS_ASSUME_NONNULL_END