text:
\documentclass[aspectratio=169]{beamer}
% \RequirePackage[T2A]{fontenc}

\usepackage{listings}
\usepackage{courier}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage{algorithmic}
\usepackage{algorithm}
\usepackage{float}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{longtable}

%\usepackage{algorithm2e}

\usetikzlibrary{shapes,arrows}

%\usetheme{CambridgeUS}%{Warsaw}
%\usetheme {Madrid}
%\useoutertheme {shadow}
%\usecolortheme{beaver}%{structure черный}%{seagull серый}%{lily желтый}%{beaver красный}
%\usefonttheme{structurebold}
%\setbeamerfont{framesubtitle}{size=\large}
%\useoutertheme{infolines}
%\useoutertheme{split}
%I DONT WANT TO SEE THOSE NAVIGATION SYMBOLS
%\setbeamertemplate{navigation symbols}{}

% \mode<presentation>
% {
%     \usefonttheme[onlymath]{serif}
% \usetheme {Madrid}
% %\useoutertheme {shadow}
% %\usecolortheme{volverine}%{structure черный}%{seagull серый}%{lily желтый}%{beaver красный}
% \usefonttheme{structurebold}
% \setbeamerfont{framesubtitle}{size=\large}
% \useoutertheme{infolines}
% %\useoutertheme{split}
% %I DONT WANT TO SEE THOSE NAVIGATION SYMBOLS
% \setbeamertemplate{navigation symbols}{}
% \setbeamertemplate{footline}
% }
\usetheme{Warsaw}
\usecolortheme{crane}
\beamertemplatenavigationsymbolsempty

\hypersetup{
    bookmarks=true,         % show bookmarks bar?
    unicode=true,           % non-Latin characters in Acrobat's bookmarks
    pdftoolbar=false,        % show Acrobat's toolbar?
    pdfmenubar=false,        % show Acrobat's menu?
    pdffitwindow=false,     % window fit to page when opened
    pdfstartview={FitH},    % fits the width of the page to the window
    pdftitle={Компьютерная алгебра в задачах оптимизации},    % title
    pdfauthor={Evgeny Cherkashin, Seseg Badmatsyrenova},     % author
    pdfsubject={symbolic computations},   % subject of the document
    pdfnewwindow=true,      % links in new PDF window
    colorlinks=true,       % false: boxed links; true: colored links
    linkcolor=red,          % color of internal links (change box color with linkbordercolor)
    citecolor=green,        % color of links to bibliography
    filecolor=magenta,      % color of file links
    urlcolor=blue           % color of external links
}

\usepackage{iftex,ifxetex}
\ifPDFTeX
  \usepackage[utf8]{inputenc}
  %\usepackage[T1]{fontenc}
  %\usepackage[russian]{babel}
  \usepackage{lmodern}
  \usefonttheme{serif}
\else
  \ifluatex
    \usepackage{unicode-math}
    \defaultfontfeatures{Ligatures=TeX,Numbers=OldStyle}
    \setmathfont{Latin Modern Math}
    \setsansfont{Linux Biolinum O}
    \usefonttheme{professionalfonts}
    \setmathfont[
        Ligatures=TeX,
        Scale=MatchLowercase,
        math-style=upright,
        vargreek-shape=unicode
        ]{euler.otf}
  \fi
\fi

%\setbeamercolor{color1}{bg=red!40!green,fg=black}
%\setbeamercolor{uppercol}{fg=white,bg=brown}
%\setbeamertemplate{background canvas}[vertical shading][bottom=white!80!cyan!20,top=cyan!10]

\title{Positive Constructed Formulas Preprocessing\\ for Automatic Deduction}

\author[A.~Davydov]{\textbf{Artem~Davydov}, \textbf{Alexander~Larionov}, \underline{Evgeny~Cherkashin}, Savely~Arlyapov\\\texttt{\scriptsize{ethrik@gmail.com, bootfrost@zoho.com eugeneai@icc.ru}}}

\institute[ISDCT SB RAS, INRTU]
{Matrosov Institute for System Dynamics and Control Theory of Siberian Branch of Russian Academy of Sciences; \\[0.5em]
Irkutsk National Research Technical University,\\
Irkutsk, Russian Federation
}

\date{\scriptsize{
\\
    \vspace{0.3cm}}
ISDCT SB RAS, INRTU
\\
31 May 2016
\\
Opatija, Croatia
}
\begin{document}
\maketitle{}
\newpage
\begin{frame}

\frametitle{Introduction: Automated Theorem Proving}
\begin{block}{Automated theorem proving (ATP)}
ATP is a part of artificial intelligence; it is based on methods of mathematical logic and realized as computer programs called provers (or solvers, or systems of ATP).
\end{block}
\begin{block}{Theorem}
<<Theorem>> describes a domain and a problem to be solved on some logical language (predicate language, clause language etc.).
\end{block}
\begin{block}{Prover}
A prover finds out whether some formula is a theorem.
\end{block}
\end{frame}

\begin{frame}

\frametitle{Introduction: Application of provers}

\begin{enumerate}
\item Solving of mathematical problems. There are examples of solving some open mathematical problems\footnote{W.McCune. Solution of the Robbins problem;};
\item Software and hardware verification;
\item Program synthesis;
\item Expert systems;
\item Problem solving;
\item There are examples of the provers in areas of natural language processing, computer vision etc.
\end{enumerate}
\begin{block}{}
The most famous and efficient provers: Vampire, E, Prover9, Otter, SPASS, EQP, Isabelle, ACL2 etc.
\end{block}
\end{frame}

\begin{frame}
\frametitle{Features of PCF}
The PCF calculus is both \textbf{machine-oriented}, and \textbf{human-oriented}, naturally it was aimed at solving the problems of \textbf{control of dynamic systems}.

Features of PCFs follows:
\begin{enumerate}
\item unique inference rule and simple scheme of axioms;
\item modifyability
  of semantics (constructive, monotonic, temporal, etc.);
\item
  it is possible to construct intuitionistic inferences of some
  non-Horn formulas;
\item explicit usage of $\forall$-- and
  $\exists$--quantifiers;
\item scolemization procedure is not required.

\end{enumerate}
The calculi of PCFs preserve heuristic structure of the original PC\footnote{Predicate calculus.} presentation of the theorem to be proved.
\end{frame}

\begin{frame}

\frametitle{Positively Constructed Formulae: an example}

\begin{figure}
\includegraphics[width=0.8\linewidth]{pics/ex1}
\end{figure}

\end{frame}

%%----------example 2--------------
\begin{frame}
\frametitle{Positively Constructed Formulae: Semantics}
\begin{figure}
\includegraphics[width=0.8\linewidth]{pics/branching}
\end{figure}

\end{frame}

%%----METHODS--------
\begin{frame}

\frametitle{Research in the field}
The research deals with adopting various nowadays techniques such as:
\begin{itemize}
\item data structures for formulae representation;
\item sharing of data structures, garbage collection;
\item efficient structure manipulation;
\item term indexing (relations: inst/2, gen/2, unif/2, var/2);
\item inference search process control and guiding;
\item parallel implementations of the inference rule;
\item testing on TPTP library of first--order theorems.
\end{itemize}
Application areas are (a little progress):
\begin{itemize}
\item Logical driven imitation modeling;
\item Control synthesis;
\item PCFs based programming language.
\end{itemize}
\end{frame}

%%----------Methods----------
\begin{frame}

\frametitle{Formal part: PC to PCF conversion}
\begin{block}{source predicate calculus formula}
$$F = \forall x\forall y(S(x,y)\leftrightarrow\forall z(I(z,x)\rightarrow I(z,y))).$$
\end{block}
The transformations should preserve a heuristic structure of the original formula.
\begin{block}{Connection $\leftrightarrow$ and $\to$ elimination}
$$\begin{array}{l}
F = \forall x\forall y( F_1 \& F_2 );\\
\quad F_1 = \neg S(x,y)\vee\forall z(\neg I(z,x)\vee I(z,y));\\
    \quad F_2 = \neg\forall z(\neg I(z,x)\vee I(z,y)) \vee S(x,y) =\\
    \quad F_2^\prime = \exists z( I(z,x)\&\neg I(z,y) ) \vee S(x,y).
\end{array}
$$
\end{block}
\end{frame}

\begin{frame}

\frametitle{PC to PCF conversion}
\begin{block}{Translated formula}
\begin{center}
\Tree[. $\forall x$ [. $\forall y$ [. $\&$ $F_1$ $F_2$ ] ] ]
\Tree[. \hspace{5mm} ]
\Tree[. $F_1$ [. $\vee$ $\neg S(x,y)$ [. $\forall z$ [. $\vee$ $\neg I(z,x)$ $I(x,y)$ ] ] ] ]
\Tree[. $F_2$ [. $\vee$ [. $\exists z$ [. $\&$ $I(z,x)$ $\neg I(z,y)$ ] ] $S(x,y)$ ] ]
\end{center}
\end{block}
\end{frame}

\begin{frame}
\frametitle{Conversion algorithm (FOL $\to$ PCF) $F^\pi(N)^P$}
%\begin{block}{}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
\begin{figure}[H]
  \footnotesize\centering
%\begin{algorithm}
% %\caption{FOF to PCF conversion algoritm}\label{alg:conv}
\begin{algorithmic}
  \REQUIRE Node $N$ is the root of a tree $T$ for $F$; \\
  $P \in \{\forall,\exists\}$, $P=\forall$ by default.
\ENSURE $F^{\pi}$ is a PCF image of FOL $F$.
\IF [Node $N$ has children.] {$N = Qx \& P\neq Q$}
\RETURN  $F^{\pi} = Qx\colon\varnothing ( (G_{N'}^{\pi})^{P} )$
\ENDIF
\IF [Node $N$ has children.] {$N=\vee$}
  \RETURN  $F^{\pi} = \forall\varnothing \bigl( (G_{N'_1}^{\pi})^{\exists},\ldots,(G_{N'_k}^{\pi})^{\exists}\bigr)$
\ENDIF
\IF [Node $N$ has children.] {$N=\&$}
  \RETURN  $F^{\pi} = \exists\varnothing \bigl( (G_{N'_1}^{\pi})^{\forall},\ldots,(G_{N'_k}^{\pi})^{\forall}\bigr)$
\ENDIF
\IF[$R$ is an atom] {$N=R$}
  \RETURN  $F^{\pi} = \exists\varnothing\colon R$
\ENDIF
\IF[$R$ is an atom] {$N=\neg R$}
  \RETURN  $F^{\pi} = \forall\varnothing\colon R$
\ENDIF
\end{algorithmic}
%\end{algorithm}
\end{figure}
%\end{block}
%\begin{figure}
%\includegraphics[scale=0.45]{pics/pic3}
%\caption{path indexing}
\end{frame}

\begin{frame}
\frametitle{Result of conversion for our example}
%\begin{figure}
\begin{tikzpicture} \small
\tikzset{grow'=right}
%\tikzset{execute at begin node=\strut}
\tikzset{level distance=35pt}
\tikzset{every tree node/.style={align=left,anchor=west}}
\Tree [. $\forall x\colon\varnothing$ [. $\exists\varnothing$ [. $\forall y\colon\varnothing$ [. $\exists\varnothing$
[. $\forall\varnothing$ [. $\exists\varnothing$ $\forall\colon S(x,y)$ ]
			[. $\exists\varnothing$ [. $\forall z\colon\varnothing$ [. $\exists\varnothing$  $\forall\colon I(z,x)$ ] $\exists\colon I(x,y)$  ] ] ]
[. $\forall\varnothing$ [. $\exists z\colon\varnothing$ [. $\forall\varnothing$ $\exists\colon I(z,x)$ ] $\forall\colon I(z,y)$ ] $\exists\colon S(x,y)$ ] ] ] ] ]
\end{tikzpicture}
% \end{figure}

Now, the formula is to be reduced.
\end{frame}

%%----------Methods----------
\begin{frame}

\frametitle{Theorem: Reduction rule}
\begin{block}{Input}
\begin{tikzpicture}\footnotesize\centering
\tikzset{grow'=right}
%\tikzset{execute at begin node=\strut}
\tikzset{level distance=70pt}
\tikzset{every tree node/.style={align=left,anchor=west}}
\Tree [. $F_1=Q_X\colon A$ [. $P_Y\colon B$ [. $Q\colon C$ [. $P_{Z_1}\colon C_1$ $\Phi_1$ ] $\cdots$ [. $P_{Z_k}\colon C_k$ $\Phi_k$ ] ] $\Psi$ ] $\Phi$ ]
\end{tikzpicture}
\end{block}

Quantifiers $P,Q\in\{\forall,\exists\}, P\neq Q$, $A,C,B$ are conjunctions, $C\subseteq B$, $\Phi,\Psi,\Phi_i$ are sets of formulae. After conversion $F_2\leftrightarrow F_1$.

\begin{block}{Result}\footnotesize
\begin{tikzpicture}
\tikzset{grow'=right}
%\tikzset{execute at begin node=\strut}
\tikzset{level distance=80pt}
\tikzset{every tree node/.style={align=left,anchor=west}}
\Tree [. $F_2=Q_X\colon A$ [. $P_{Y,Z_1}\colon B,C_1$ $\Phi_1\cup\Psi$ ] $\cdots$ [. $P_{Y,Z_k}\colon B,C_k$ $\Phi_k\cup\Psi$ ] $\Phi$ ]
\end{tikzpicture}
\end{block}
\end{frame}

%%----------Methods----------
\begin{frame}

\frametitle{Reduction rule applied to the example}
\begin{block}{Reduced PCF}
\begin{tikzpicture}
\tikzset{grow'=right}
%\tikzset{execute at begin node=\strut}
%\tikzset{level distance=70pt}
\tikzset{level 1/.style={level distance=60pt}}
\tikzset{level 2/.style={level distance=40pt}}
\tikzset{level 3/.style={level distance=100pt}}
\tikzset{level 4+/.style={level distance=60pt}}
\tikzset{every tree node/.style={align=left,anchor=west}}
\Tree [. $\forall x,y\colon\varnothing$ [. $\exists\varnothing$ [. $\forall z\colon S(x,y),I(z,x)$ $\exists\colon I(x,y)$ ] [. $\forall\varnothing$ [. $\exists z\colon I(z,x)$ $\forall\colon I(x,y)$ ] $\exists\colon S(x,y)$ ] ] ]
\end{tikzpicture}
\end{block}
There are two reduction options: eliminate $\exists\emptyset$ or $\forall\emptyset$, the latter applied.
\begin{block}{The final result}
\begin{tikzpicture}
\tikzset{grow'=right}
%\tikzset{execute at begin node=\strut}
%\tikzset{level distance=70pt}
\tikzset{level 1/.style={level distance=30pt}}
\tikzset{level 2/.style={level distance=130pt}}
\tikzset{level 3+/.style={level distance=60pt}}
\tikzset{every tree node/.style={align=left,anchor=west}}
\Tree [. $\exists\varnothing$ [. $\forall x,y,z\colon S(x,y),I(z,x)$ $\exists\colon I(x,y)$ ] [. $\forall x,y\colon\varnothing$ [. $\exists z\colon I(z,x)$ $\forall\colon I(x,y)$ ] $\exists\colon S(x,y)$ ] ]
\end{tikzpicture}
\end{block}
\end{frame}

%%----------Methods----------
\begin{frame}

\frametitle{Further development of the conversion engine}
The algorithm and the software is being developed further.
\begin{block}{}
  \begin{itemize}
  \item Adaptation to TPTP syntax;
  \item Conjunctive Normal Form (CNF) support;
  \item Reconstruct the heuristic structure of CNF;
  \item Implement it in Rust programming language as it
    \begin{itemize}
    \item does not include a garbage collector in compiled code;
    \item supports a strong memory control technique;
    \item has reasonable compatibility with C and C++.
    \end{itemize}
  \end{itemize}
\end{block}
We already have a version of the algorithm for CNF having no existential variables.
\end{frame}

\begin{frame}
\frametitle{Results of prover development}
TPTP. www.tptp.org
We developed a D-language version of prover, where implemented
\begin{enumerate}
\item memory data sharing;
\item two indexing techniques;
\item basic support of simple constraints and strategies;
\item connection to outer world via Python classes;
\item tested on all FOL theorems from TPTP library.
\end{enumerate}
\end{frame}

\begin{frame}
\frametitle{TPTP test results}
\begin{block}{Total number of solved problems}
\begin{longtable}{|p{0.35\linewidth}|p{0.25\linewidth}|p{0.15\linewidth}|}
\hline
\textbf{Complexity} & \textbf{Total number} & \textbf{Solved} \\
\hline
\endhead
0,0-0,03 & 192 & 181 \\
\hline
0,04-0,20 & 435 & 373 \\
\hline
0,21-0,32 & 128 & 79 \\
\hline
0,33-0,49 & 115 & 44 \\
\hline
0,5-0,67 & 223 & 21 \\
\hline
0,68-0,92 & 72 & 6 \\
\hline
0,93-1,0 & 56 & 0\\
\hline
\end{longtable}
\end{block}
Our rating is about 0,1--0,15.
\end{frame}

\begin{frame}
  \frametitle{Testing results}
  \begin{block}{Results by domains}
    \begin{longtable}[H]{|l|p{0.2\linewidth}|p{0.15\linewidth}|}
\hline
\textbf{Domain} & \textbf{Total number} & \textbf{Solved} \\
\hline
Geometry (GEO) & 242 & 204 \\
\hline
Management (MGT) & 22 & 22 \\
\hline
Syntax (SYN) & 275 & 180 \\
\hline
Semantic web (SWB) & 25 & 22 \\
\hline
\end{longtable}
\end{block}
\begin{block}{Most complex solved (not checked)}
  \begin{longtable}{|p{0.3\linewidth}|p{0.2\linewidth}|p{0.15\linewidth}|p{0.2\linewidth}|}
\hline
\textbf{Problem} & \textbf{Complexity} & \textbf{Time,s} & \textbf{Step count} \\
\hline
%\hline
%LCL662+1.005 & 1,0 & 1,02 & 7772 \\
LCL652+1.015 & 0,92 & 32,1 & 185\,{}253 \\
\hline
LCL656+1.020 & 0,92 & 1,24 & 845 \\
\hline
\end{longtable}
\end{block}
\end{frame}

\begin{frame}

\frametitle{Research target: Logical-dynamic imitation modeling}

\begin{figure}
\includegraphics[width=0.7\linewidth]{pics/elevbetter}
\end{figure}
\vspace{-4em}
\begin{enumerate}\small
\item Intuitionistic inference in non--Horn formalization.
\item Utilization of prover engine in forward-chaining inference.
\item Constraint satisfaction.
\item Independent mostly asynchronous inference.
\end{enumerate}
\end{frame}

%%----------application------------
\begin{frame}

\frametitle{Conclusion}
The software development of method of the PCF has a number of challenges, which are under research, but the progress we made shows that the inference method is meaningful to research further.
\begin{block}{}
  \begin{itemize}
  \item Something different to Resolutional methods and Tabbling;
  \item It has direct technical origins (Theory of Control);
  \item Constructive inference of non--Horn clauses;
  \item Heuristic structure presentation.
  \end{itemize}
\end{block}
\end{frame}
  \maketitle
\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% TeX-engine: pdftex
%%% End:


text:
editAreaLoader.lang["fi"]={
new_document: "uusi tyhjä dokumentti",
search_button: "etsi ja korvaa",
search_command: "etsi seuraava / avaa etsintävalikko",
search: "etsi",
replace: "korvaa",
replace_command: "korvaa / avaa etsintävalikko",
find_next: "etsi seuraava",
replace_all: "korvaa kaikki",
reg_exp: "säännölliset lausekkeet",
match_case: "täsmää kirjainkokoon",
not_found: "ei löytynyt.",
occurrence_replaced: "esiintymää korvattu.",
search_field_empty: "Haettava merkkijono on tyhjä",
restart_search_at_begin: "Alueen loppu saavutettiin. Aloitetaan alusta.",
move_popup: "siirrä etsintävalikkoa",
font_size: "--Fontin koko--",
go_to_line: "siirry riville",
go_to_line_prompt: "mene riville:",
undo: "peruuta",
redo: "tee uudelleen",
change_smooth_selection: "kytke/sammuta joitakin näyttötoimintoja (Älykkäämpi toiminta, mutta suurempi CPU kuormitus)",
highlight: "kytke syntaksikorostus päälle/pois",
reset_highlight: "resetoi syntaksikorostus (jos teksti ei ole synkassa korostuksen kanssa)",
word_wrap: "toggle word wrapping mode",
help: "tietoja",
save: "tallenna",
load: "lataa",
line_abbr: "Rv",
char_abbr: "Pos",
position: "Paikka",
total: "Yhteensä",
close_popup: "sulje valikko",
shortcuts: "Pikatoiminnot",
add_tab: "lisää sisennys tekstiin",
remove_tab: "poista sisennys tekstistä",
about_notice: "Huomautus: syntaksinkorostus toimii vain pienelle tekstille",
toggle: "Kytke editori",
accesskey: "Pikanäppäin",
tab: "Tab",
shift: "Shift",
ctrl: "Ctrl",
esc: "Esc",
processing: "Odota...",
fullscreen: "koko ruutu",
syntax_selection: "--Syntaksi--",
close_tab: "Sulje tiedosto"
};

redpajama_set_name: RedPajamaGithub


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

// Add two key value pairs
func TestAccComputeProjectMetadata_basic(t *testing.T) {
	t.Parallel()

	org := getTestOrgFromEnv(t)
	billingId := getTestBillingAccountFromEnv(t)
	projectID := fmt.Sprintf("tf-test-%d", randInt(t))

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeProjectMetadataDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccComputeProject_basic0_metadata(projectID, pname, org, billingId),
			},
			{
				ResourceName:      "google_compute_project_metadata.fizzbuzz",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

// Add three key value pairs, then replace one and modify a second
func TestAccComputeProjectMetadata_modify_1(t *testing.T) {
	t.Parallel()

	org := getTestOrgFromEnv(t)
	billingId := getTestBillingAccountFromEnv(t)
	projectID := fmt.Sprintf("tf-test-%d", randInt(t))

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeProjectMetadataDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccComputeProject_modify0_metadata(projectID, pname, org, billingId),
			},
			{
				ResourceName:      "google_compute_project_metadata.fizzbuzz",
				ImportState:       true,
				ImportStateVerify: true,
			},

			{
				Config: testAccComputeProject_modify1_metadata(projectID, pname, org, billingId),
			},
			{
				ResourceName:      "google_compute_project_metadata.fizzbuzz",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

// Add two key value pairs, and replace both
func TestAccComputeProjectMetadata_modify_2(t *testing.T) {
	t.Parallel()

	org := getTestOrgFromEnv(t)
	billingId := getTestBillingAccountFromEnv(t)
	projectID := fmt.Sprintf("tf-test-%d", randInt(t))

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeProjectMetadataDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccComputeProject_basic0_metadata(projectID, pname, org, billingId),
			},
			{
				ResourceName:      "google_compute_project_metadata.fizzbuzz",
				ImportState:       true,
				ImportStateVerify: true,
			},

			{
				Config: testAccComputeProject_basic1_metadata(projectID, pname, org, billingId),
			},
			{
				ResourceName:      "google_compute_project_metadata.fizzbuzz",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccCheckComputeProjectMetadataDestroyProducer(t *testing.T) func(s *terraform.State) error {
	return func(s *terraform.State) error {
		config := googleProviderConfig(t)

		for _, rs := range s.RootModule().Resources {
			if rs.Type != "google_compute_project_metadata" {
				continue
			}

			project, err := config.NewComputeClient(config.userAgent).Projects.Get(rs.Primary.ID).Do()
			if err == nil && len(project.CommonInstanceMetadata.Items) > 0 {
				return fmt.Errorf("Error, metadata items still exist in %s", rs.Primary.ID)
			}
		}

		return nil
	}
}

func testAccComputeProject_basic0_metadata(projectID, name, org, billing string) string {
	return fmt.Sprintf(`
resource "google_project" "project" {
  project_id      = "%s"
  name            = "%s"
  org_id          = "%s"
  billing_account = "%s"
}

resource "google_project_service" "compute" {
  project = google_project.project.project_id
  service = "compute.googleapis.com"
}

resource "google_compute_project_metadata" "fizzbuzz" {
  project = google_project.project.project_id
  metadata = {
    banana = "orange"
    sofa   = "darwinism"
  }
  depends_on = [google_project_service.compute]
}
`, projectID, name, org, billing)
}

func testAccComputeProject_basic1_metadata(projectID, name, org, billing string) string {
	return fmt.Sprintf(`
resource "google_project" "project" {
  project_id      = "%s"
  name            = "%s"
  org_id          = "%s"
  billing_account = "%s"
}

resource "google_project_service" "compute" {
  project = google_project.project.project_id
  service = "compute.googleapis.com"
}

resource "google_compute_project_metadata" "fizzbuzz" {
  project = google_project.project.project_id
  metadata = {
    kiwi    = "papaya"
    finches = "darwinism"
  }
  depends_on = [google_project_service.compute]
}
`, projectID, name, org, billing)
}

func testAccComputeProject_modify0_metadata(projectID, name, org, billing string) string {
	return fmt.Sprintf(`
resource "google_project" "project" {
  project_id      = "%s"
  name            = "%s"
  org_id          = "%s"
  billing_account = "%s"
}

resource "google_project_service" "compute" {
  project = google_project.project.project_id
  service = "compute.googleapis.com"
}

resource "google_compute_project_metadata" "fizzbuzz" {
  project = google_project.project.project_id
  metadata = {
    paper        = "pen"
    genghis_khan = "french bread"
    happy        = "smiling"
  }
  depends_on = [google_project_service.compute]
}
`, projectID, name, org, billing)
}

func testAccComputeProject_modify1_metadata(projectID, name, org, billing string) string {
	return fmt.Sprintf(`
resource "google_project" "project" {
  project_id      = "%s"
  name            = "%s"
  org_id          = "%s"
  billing_account = "%s"
}

resource "google_project_service" "compute" {
  project = google_project.project.project_id
  service = "compute.googleapis.com"
}

resource "google_compute_project_metadata" "fizzbuzz" {
  project = google_project.project.project_id
  metadata = {
    paper = "pen"
    paris = "french bread"
    happy = "laughing"
  }
  depends_on = [google_project_service.compute]
}
`, projectID, name, org, billing)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/alert_dialog_btn_right_bg" />
    <item android:state_pressed="true" android:drawable="@drawable/alert_dialog_btn_right_pressed_bg" />
    <item android:state_focused="true" android:drawable="@drawable/alert_dialog_btn_right_pressed_bg" />
    <item android:drawable="@drawable/alert_dialog_btn_right_bg" />
</selector>


text:
class Service::Redmine < Service
  def receive_push
    http.ssl[:verify] = false
    http.url_prefix = data['address']
    http_get "sys/fetch_changesets" do |req|
      req.params['key'] = data['api_key']
      req.params['id']  = data['project']
    end
  end
end


text:
package initialize

import (
	"fmt"

	"github.com/coreos/nova-agent-watcher/Godeps/_workspace/src/github.com/coreos/coreos-cloudinit/system"
)

func SSHImportGithubUser(system_user string, github_user string) error {
	url := fmt.Sprintf("https://api.github.com/users/%s/keys", github_user)
	keys, err := fetchUserKeys(url)
	if err != nil {
		return err
	}

	key_name := fmt.Sprintf("github-%s", github_user)
	return system.AuthorizeSSHKeys(system_user, key_name, keys)
}


text:
// -*- C++ -*-

#ifndef DATA_H_
#define DATA_H_

#include <fstream>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <set>
#include <string>
//#define EIGEN2_SUPPORT
#include <Eigen/Core>
//#include <Eigen/Array>

// DATA CLASSES
class Sample {
public:
    Eigen::VectorXd x;
    int y;
    double w;
    int id;
};

class DataSet {
 public:
    void findFeatRange();

    void load(const std::string& x_filename, const std::string& y_filename);

    std::vector<Sample> m_samples;
    int m_numSamples;
    int m_numFeatures;
    int m_numClasses;

    Eigen::VectorXd m_minFeatRange;
    Eigen::VectorXd m_maxFeatRange;
};

class Result {
 public:
    Result();
    Result(const int& numClasses);

    Eigen::VectorXd confidence;
    int prediction;
};

class Cache {
public:
    Cache();
    Cache(const Sample& sample, const int& numBases, const int& numClasses);

    Sample cacheSample;
    double margin;
    int yPrime; // Class with closest margin to the sample
};

#endif /* DATA_H_ */


text:
/*
 * Problem 5. Sort by string length
 * You are given an array of strings. Write a method that sorts the array by the length of its elements (the number of characters composing them).
 */

using System;

class SortByStringLength
{
    static void Main()
    {

    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-boton-navegacion',
  templateUrl: './boton-navegacion.component.html',
  styleUrls: ['./boton-navegacion.component.css']
})
export class BotonNavegacionComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  navegar() {
    window.location.href = 'https://google.es';
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 377 (1887)

#### Original name
Agaricus rivulorum Pat. & Doass.

### Remarks
null


text:
package com.redhat.et.silex.feature.extractor.spark

import org.scalatest._

class SparkFeatureSeqSpec extends FlatSpec with Matchers {
  import com.redhat.et.silex.feature.extractor._
  import com.redhat.et.silex.feature.extractor.spark.implicits._

  import com.redhat.et.silex.feature.extractor.FeatureSeqSpecSupport._
  import com.redhat.et.silex.scalatest.matchers._

  import org.apache.spark.mllib.linalg._
  import org.apache.spark.mllib.regression.LabeledPoint

  def vectorType(v: Vector) = v match {
    case _: DenseVector => 'dense
    case _: SparseVector => 'sparse
    case _ => 'undefined
  }

  it should "construct a FeatureSeq from a Spark DenseVector" in {
    identityTest(FeatureSeq(new DenseVector(Array[Double]())))
    val s1 = FeatureSeq(new DenseVector(Array(3.14, 2.72)))
    s1.length should be (2)
    s1.density should be (1.0)
    xyTest(s1, (0, 3.14), (1, 2.72))
    propertyTest(
      FeatureSeq(new DenseVector(Array(3.14, 2.72))),
      FeatureSeq(new DenseVector(Array(1.1, 2.2))),
      FeatureSeq(new DenseVector(Array(7.77, 8.88))))
  }

  it should "construct a FeatureSeq from a Spark SparseVector" in {
    identityTest(FeatureSeq(new SparseVector(0, Array[Int](), Array[Double]())))
    val s1 = FeatureSeq(new SparseVector(5, Array(1, 3), Array(3.14, 2.72)))
    s1.length should be (5)
    s1.density should be (0.4 +- densityEpsilon)
    xyTest(s1, (0, 0.0), (1, 3.14), (2, 0.0), (3, 2.72), (4, 0.0))
    propertyTest(
      FeatureSeq(new SparseVector(5, Array(1, 3), Array(3.14, 2.72))),
      FeatureSeq(new SparseVector(4, Array(1, 2), Array(3.33, 4.44))),
      FeatureSeq(new SparseVector(10, Array(4, 9), Array(5.0, 9.0))))
  }

  it should "construct a FeatureSeq from a Spark LabeledPoint" in {
    identityTest(
      FeatureSeq(new LabeledPoint(1.0, new SparseVector(0, Array[Int](), Array[Double]()))))
    val s1 = FeatureSeq(new LabeledPoint(1.0, new SparseVector(5, Array(1, 3), Array(3.14, 2.72))))
    s1.length should be (5)
    s1.density should be (0.4 +- densityEpsilon)
    xyTest(s1, (0, 0.0), (1, 3.14), (2, 0.0), (3, 2.72), (4, 0.0))
    propertyTest(
      FeatureSeq(new LabeledPoint(1.0, new SparseVector(5, Array(1, 3), Array(3.14, 2.72)))),
      FeatureSeq(new LabeledPoint(1.0, new DenseVector(Array(1.1, 2.2)))),
      FeatureSeq(new LabeledPoint(1.0, new SparseVector(10, Array(4, 9), Array(5.0, 9.0)))))
  }

  it should "construct a FeatureSeq from mixed Spark vectors" in {
    propertyTest(
      FeatureSeq(Array(8.88, 9.99)),
      FeatureSeq(new LabeledPoint(1.0, new DenseVector(Array(1.1, 2.2)))),
      FeatureSeq(new DenseVector(Array(1.1, 2.2))),
      FeatureSeq(new DenseVector(Array(7.77, 8.88))),
      FeatureSeq(new SparseVector(5, Array(1, 3), Array(3.14, 2.72))),
      FeatureSeq(new SparseVector(10, Array(4, 9), Array(5.0, 9.0))))
  }

  it should "support the toSpark enriched method" in {
    val t1 = new DenseVector(Array(1.1, 2.2))
    val v1 = FeatureSeq(t1).toSpark
    v1.equals(t1) should be (true)
    vectorType(v1) should equal ('dense)

    val t2 = new SparseVector(5, Array(1, 3), Array(1.1, 2.2))
    val v2 = FeatureSeq(t2).toSpark
    v2.equals(t2) should be (true)
    vectorType(v2) should equal ('sparse)

    val t3 = new SparseVector(3, Array(1, 2), Array(1.1, 2.2))
    val v3 = FeatureSeq(t3).toSpark
    v3.equals(t3) should be (true)
    vectorType(v3) should equal ('dense)
  }

  it should "support the toLabeledPoint enriched method" in {
    val t1 = new LabeledPoint(0.0, new DenseVector(Array(1.1, 2.2)))
    val v1 = FeatureSeq(t1).toLabeledPoint(1.0)
    v1.label should be (1.0)
    v1.features.equals(t1.features) should be (true)
    vectorType(v1.features) should equal ('dense)

    val t2 = new LabeledPoint(0.0, new SparseVector(5, Array(1, 3), Array(1.1, 2.2)))
    val v2 = FeatureSeq(t2).toLabeledPoint(2.0)
    v2.label should be (2.0)
    v2.features.equals(t2.features) should be (true)
    vectorType(v2.features) should equal ('sparse)

    val t3 = new LabeledPoint(0.0, new SparseVector(3, Array(1, 2), Array(1.1, 2.2)))
    val v3 = FeatureSeq(t3).toLabeledPoint(3.0)
    v3.label should be (3.0)
    v3.features.equals(t3.features) should be (true)
    vectorType(v3.features) should equal ('dense)
  }
}


text:
package com.eschao.android.widget.elasticlistview;

/**
 * Listener class for loading operation
 *
 * @author chao
 */
public interface OnLoadListener {

    /**
     * Handles loading operation
     */
    void onLoad();
}


text:
import { browser, by, element } from 'protractor';

export class Ejemplo0032Page {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}


text:
<?php
namespace Siegelion\Application\Api\Action\Customer;

use Siegelion\System\Framework\BaseBundle\Action;
use Siegelion\System\Framework\BaseBundle\RestfulActionInterface;
use Siegelion\Service\Business\CustomerManager;
use Siegelion\System\Framework\UtilityBundle\JsonUtils;

class UserInfoById extends Action implements RestfulActionInterface
{
    // [GET] /user/:id
    public function get($aParams, $aQuery)
    {
        if (isset($aParams['customerId'])) {
            $oCustomerManager = new CustomerManager($aParams['customerId']);
            if ($oCustomerManager->has()) {
                return JsonUtils::parseObject($oCustomerManager->get());
            }
            return JsonUtils::parseError(20, 'customer not found');
        }
        return JsonUtils::parseError(10, 'missing params');
    }

    public function post($aParams, $aQuery, $aRequest)
    {

    }

    public function put($aParams, $aQuery, $aRequest)
    {

    }

    public function patch($aParams, $aQuery, $aRequest)
    {

    }

    public function delete($aParams, $aQuery, $aRequest)
    {

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Drawing.Design;

namespace CodeTorch.Core
{

    [Serializable]
    public class MultiComboDropDownListControl : Widget
    {
        public bool AutoPostBack { get; set; }
        public bool IncludeAdditionalListItem { get; set; }
        public bool CausesValidation { get; set; }

        public string EmptyMessage { get; set; }
        public string AdditionalListItemText { get; set; }
        public string AdditionalListItemValue { get; set; }

        bool _ShowToggleImage = true;
        public bool ShowToggleImage
        {
            get
            {
                return _ShowToggleImage;
            }
            set
            {
                _ShowToggleImage = value;
            }
        }

         [Category("Data")]
        [TypeConverter("CodeTorch.Core.Design.ScreenDataCommandTypeConverter,CodeTorch.Core.Design")]
        public string SelectDataCommand { get; set; }

        public string RelatedControl { get; set; }

         [Category("Data")]
        [TypeConverter("CodeTorch.Core.Design.DataCommandColumnTypeConverter,CodeTorch.Core.Design")]
        public string DataTextField { get; set; }

         [Category("Data")]
        [TypeConverter("CodeTorch.Core.Design.DataCommandColumnTypeConverter,CodeTorch.Core.Design")]
        public string DataValueField { get; set; }

        [Category("Load On Demand")]
        public bool EnableLoadOnDemand { get; set; }

        [Category("Load On Demand")]
        public bool EnableItemCaching { get; set; }
        [Category("Load On Demand")]
        public bool EnableVirtualScrolling { get; set; }

        public bool MarkFirstMatch { get; set; }
        public bool IsCaseSensitive { get; set; }
        public DropDownListFilterMode FilterMode { get; set; }
        public DropDownListRenderingMode RenderingMode { get; set; }
        public string DropDownWidth { get; set; }

        [Category("Appearance")]
        public string Skin { get; set; }

        public override string Type
        {
            get
            {
                return "MultiComboDropDownList";
            }
            set
            {
                base.Type = value;
            }
        }

        List<MultiComboDropDownListColumn> _Columns = new List<MultiComboDropDownListColumn>();

        [Category("Data")]
        [XmlArray("Columns")]
        [XmlArrayItem("Column")]
        [Description("List of dropdown columns for multi combo")]
        public List<MultiComboDropDownListColumn> Columns
        {
            get
            {
                return _Columns;
            }
            set
            {
                _Columns = value;
            }

        }

        public static IEnumerable<ResourceItem> GetResourceKeys(Screen Screen, MultiComboDropDownListControl Control, String Prefix)
        {
            List<ResourceItem> retVal = new List<ResourceItem>();

            //add title
            AddResourceKey(retVal, Screen, Control, Prefix, "EmptyMessage", Control.EmptyMessage);
            AddResourceKey(retVal, Screen, Control, Prefix, "AdditionalListItemText", Control.AdditionalListItemText);

            foreach (MultiComboDropDownListColumn column in Control.Columns)
            {
                string resourceKey = String.Format("Columns.{0}.HeaderText", column.DataField);
                AddResourceKey(retVal, Screen, Control, Prefix, resourceKey, column.HeaderText);
            }

            return retVal;
        }
    }
}


text:
import Ember from 'ember';
import defaultMessages from 'ember-cli-data-validation/messages';

function dictionary() {
	var dict = Object.create(null);
	dict['_dict'] = null;
	delete dict['_dict'];
	return dict;
}

/**
 * Resolver used to resolve and locate the validation messages
 * for Validators.
 *
 * By default this would load the messages that are
 * defined by this Addon.
 *
 * To implement your own message lookup, you just
 * need to redefine this class.
 *
 * @class  MessageResolver
 * @extends {Ember.Object}
 */
export default Ember.Object.extend({

	init: function() {
		this._cache = dictionary(null);
	},

	/**
	 * Resolve the Message for the given Validator and Attribute.
	 *
	 * It would first try to locate the message with it's full name,
	 * which is constructed like `validatorType.attributeType`
	 *
	 * @example
	 * DS.Model.extend({
	 * 		name: DS.attr('string', {
	 * 			validation: {
	 * 				required: true
	 * 			}
	 * 		})
	 * 	});
	 *
	 * The full name would be `required.string`.
	 * If the message with full name is not found it would
	 * then try to find with just the Validator type, in this
	 * case it would be just `required`.
	 *
	 * @method resolve
	 * @param  {Validator} validator
	 * @param  {Attribute} attribute
	 * @return {String}
	 */
	resolve: function(validator, attribute) {
		var parsedName = this.parseName(validator, attribute);
		var lookupKeys = ['modelPath', 'validatorPath', 'validatorType'];

		var message;

		lookupKeys.forEach(function(key) {
			if (Ember.isPresent(message)) {
				return;
			}

			var name = parsedName[key];

			Ember.assert(key + ' must be a string, you passed `' + typeof name + '`', typeof name === 'string');

			message = this._cache[name];

			if(!message) {
				message = this._cache[name] = this.resolveMessage(name);
			}
		}, this);

		Ember.assert('Could not resolve message for `' + parsedName.validatorType +
			'` Validator and  `' + parsedName.attributeType + '` ', Ember.isPresent(message));

		return message;
	},

	/**
	 * This method is doing the real lookup of the Validation message.
	 *
	 * This would be the best place to implement your own lookup
	 * logic.
	 *
	 * @method resolveMessage
	 * @param  {String} key The validation Message key
	 * @return {String}
	 */
	resolveMessage: function(key) {
		return Ember.get(defaultMessages, key);
	},

	/**
	 * Used to format the lookup paramters.
	 *
	 * @method parseName
	 * @param  {Validator} validator
	 * @param  {Attribute} attribute
	 * @return {String}
	 */
	parseName: function(validator, attribute) {
		var attributeType = this._parseAttributeType(attribute),
			modelType = this._parseModelType(attribute),
			validatorType = this._parseValidatorType(validator);

		return {
			attributeType,
			validatorType,
			modelType,
			validatorPath: validatorType + '.' + attributeType,
			modelPath: modelType + '.' + attribute.name + '.' + validatorType
		};
	},

	/**
	 * Resolve the Model name from the attribute.
	 *
	 * @private
	 * @method _parseModelType
	 * @param  {Attribute} attribute
	 * @return {String}
	 */
	_parseModelType: function(attribute) {
		return attribute.parentTypeKey;
	},

	/**
	 * Find the Validator type name.
	 *
	 * This is normaly located in the Validators constructor
	 * method property `typeKey`.
	 *
	 * @private
	 * @method _parseValidatorType
	 * @param  {Validator} validator
	 * @return {String}
	 */
	_parseValidatorType: function(validator) {
		return validator.typeKey ||
			validator.constructor && validator.constructor.typeKey || '';
	},

	/**
	 * Find the type of the Attribute from it's definition.
	 *
	 * @example
	 * 	DS.Model.extend({
	 * 		name: DS.attr('string') // type is string
	 * 	})
	 *
	 * @private
	 * @method _parseAttributeType
	 * @param  {Attribute} attribute
	 * @return {String}
	 */
	_parseAttributeType: function(attribute) {
		return attribute.type;
	},

	/**
	 * Clears the Message cache
	 *
	 * @method clearCache
	 */
	clearCache: function() {
		this._cache = dictionary(null);
	}

});


text:
package gov.va.hmp.workspace;

/**
 * Created with IntelliJ IDEA. User: sblaz Date: 9/1/13 Time: 4:36 PM To change this template use File | Settings | File
 * Templates.
 */
public class WorkspaceService {
}


text:
<!doctype html>

    <title>Code coverage report for lib/jwt/</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files lib/jwt/

        86.44%
        Statements
        51/59

        81.25%
        Branches
        13/16

        72.73%
        Functions
        8/11

        86.21%
        Lines
        50/58

   File

   Statements

   Branches

   Functions

   Lines

	jwt-authentication-result.js

	90.91%
	20/22
	83.33%
	5/6
	75%
	3/4
	90.48%
	19/21

	jwt-authenticator.js

	83.78%
	31/37
	80%
	8/10
	71.43%
	5/7
	83.78%
	31/37

  Code coverage
  generated by istanbul at Mon Feb 22 2016 14:15:19 GMT-0800 (PST)


text:
<?xml version="1.0" encoding="UTF-8"?>

<FLOW VERSION="3.0" CLEANUP="true">
  <COMMENT></COMMENT>

  <!-- nodes -->

<INVOKE TIMEOUT="" SERVICE="SimpleFTP.schedule:ftp_transport_get" VALIDATE-IN="$none" VALIDATE-OUT="$none">
  <COMMENT></COMMENT>

  <!-- nodes -->

<MAP MODE="INPUT">
  <MAPTARGET>

<Values version="2.0">
  <record name="xml" javaclass="com.wm.util.Values">
    <value name="node_type">record</value>
    <value name="field_type">record</value>
    <value name="field_dim">0</value>
    <value name="nillable">true</value>
    <array name="rec_fields" type="record" depth="1">
      <record javaclass="com.wm.util.Values">
        <value name="node_type">record</value>
        <value name="field_name">ftpalias</value>
        <value name="field_type">string</value>
        <value name="field_dim">0</value>
        <value name="nillable">true</value>
      </record>
    </array>
  </record>
</Values>
</MAPTARGET>
  <MAPSOURCE>

<Values version="2.0">
  <record name="xml" javaclass="com.wm.util.Values">
    <value name="node_type">record</value>
    <value name="field_type">record</value>
    <value name="field_dim">0</value>
    <value name="nillable">true</value>
    <array name="rec_fields" type="record" depth="1">
    </array>
  </record>
</Values>
</MAPSOURCE>

  <!-- nodes -->

<MAPSET NAME="Setter" OVERWRITE="true" VARIABLES="false" FIELD="/ftpalias;1;0">
  <DATA ENCODING="XMLValues" I18N="true">

<Values version="2.0">
  <value name="xml">DEV1</value>
  <record name="type" javaclass="com.wm.util.Values">
    <value name="node_type">record</value>
    <value name="field_name">ftpalias</value>
    <value name="field_type">string</value>
    <value name="field_dim">0</value>
    <value name="nillable">true</value>
  </record>
</Values>
</DATA>
</MAPSET>
</MAP>

<MAP MODE="OUTPUT">
</MAP>
</INVOKE>
</FLOW>


text:
'use strict';

var dashcore = require('@dashevo/dashcore-lib');
var _ = dashcore.deps._;
var colors = require('colors/safe');

/**
 * Wraps console.log with some special magic
 * @constructor
 */
function Logger(options) {
  if (!options) {
    options = {};
  }
  this.formatting = _.isUndefined(options.formatting) ? Logger.DEFAULT_FORMATTING : options.formatting;
}

Logger.DEFAULT_FORMATTING = true;

/**
 * Prints an info message
 * #info
 */
Logger.prototype.info = function() {
  this._log.apply(this, ['blue', 'info'].concat(Array.prototype.slice.call(arguments)));
};

/**
 * Prints an error message
 * #error
 */
Logger.prototype.error = function() {
  this._log.apply(this, ['red', 'error'].concat(Array.prototype.slice.call(arguments)));
};

/**
 * Prints an debug message
 * #debug
 */
Logger.prototype.debug = function() {
  this._log.apply(this, ['magenta', 'debug'].concat(Array.prototype.slice.call(arguments)));
};

/**
 * Prints an warn message
 * #warn
 */
Logger.prototype.warn = function() {
  this._log.apply(this, ['yellow', 'warn'].concat(Array.prototype.slice.call(arguments)));
};

/**
 * Proxies console.log with color and arg parsing magic
 * #_log
 */
Logger.prototype._log = function(color) {
  var args = Array.prototype.slice.call(arguments);
  args = args.slice(1);
  var level = args.shift();

  if (this.formatting) {
    var date = new Date();
    var typeString = colors[color].italic(level + ':');
    args[0] = '[' + date.toISOString() + ']' + ' ' + typeString + ' ' + args[0];
  }
  var fn = console[level] || console.log;
  fn.apply(console, args);
};

module.exports = Logger;


text:
package com.antwerkz.afton;

public enum Status {
  OPEN, CLOSED, NOT_TRACKING, NONEXISTENT
}


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/croatia/procurement/" />
</head></html>


text:
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// MIT X11 license, Copyright (c) 2005-2006 by:                               //
//                                                                            //
// Authors:                                                                   //
//      Michael Dominic K. <michaldominik@gmail.com>                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included    //
// in all copies or substantial portions of the Software.                     //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS    //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                 //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN  //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  //
// USE OR OTHER DEALINGS IN THE SOFTWARE.                                     //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

/* An interface that defines a media item that can is timeable -- has a fixed
 * length. A typical video/audio clip is timeable. On the contrary, stock items
 * are not timeable (they can be any length). Another example -- a photo (ie. jpeg
 * file) is not timeable as well.
 */

#include "GdvTimeableInterface.h"
#include "GdvTimeableInterfacePrivate.h"

/* GObject type */
GType                           gdv_timeable_get_type (void)
{
        static GType interfacetype = 0;

        if (! interfacetype) {

                static const GTypeInfo info = {
                        sizeof (GdvTimeableInterface),
                        (GBaseInitFunc) gdv_timeable_base_init,
                        NULL,
                        NULL,
                        NULL,
                        NULL,
                        0,
                        0,
                        NULL,
                };
                interfacetype = g_type_register_static
                    (G_TYPE_INTERFACE, "GdvTimeableInterface", &info, 0);
        }
        return interfacetype;
}

/* GObject base init */
static void                     gdv_timeable_base_init (GdvTimeableInterface *interface)
{
          static gboolean initialized = FALSE;

          if (! initialized) {

                  g_object_interface_install_property ((gpointer) interface,
                                                       g_param_spec_uint64
                                                       ("length", "Length",
                                                        "Length in nanoseconds",
                                                        0, G_MAXUINT64, 0, G_PARAM_READABLE));

                  initialized = TRUE;
          }
}


text:
package com.cloudbase;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.AbstractHttpEntity;

public class CBMultipartEntity extends AbstractHttpEntity implements Cloneable {
	/* package */ static final String CRLF = "\r\n";    //$NON-NLS-1$

    private List<CBPart> parts = new ArrayList<CBPart>();

    private CBBoundary boundary;

    public CBMultipartEntity(String boundaryStr) {
        super();
        boundary = new CBBoundary(boundaryStr);
        setContentType("multipart/form-data; boundary=\"" + boundary.getBoundary() + '"');  //$NON-NLS-1$
    }

    public CBMultipartEntity() {
        this(null);
    }

    public void addPart(CBPart part) {
        parts.add(part);
    }

    public boolean isRepeatable() {
        return true;
    }

    public long getContentLength() {
        long result = 0;
        for (CBPart part : parts) {
            result += part.getContentLength(boundary);
        }
        result += boundary.getClosingBoundary().length;
        return result;
    }

    /**
     * Returns null since it's not designed to be used for server responses.
     */
    public InputStream getContent() throws IOException {
        return null;
    }

    public void writeTo(final OutputStream out) throws IOException {
        if (out == null) {
            throw new IllegalArgumentException("Output stream may not be null");    //$NON-NLS-1$
        }
        for (CBPart part : parts) {
            part.writeTo(out, boundary);
        }
        out.write(boundary.getClosingBoundary());
        out.flush();
    }

    /**
     * Tells that this entity is not streaming.
     *
     * @return false
     */
    public boolean isStreaming() {
        return false;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("MultipartEntity does not support cloning"); //$NON-NLS-1$ // TODO
    }
}


text:
A framework for effectively defining and raising localized errors.

[![Build Status](https://travis-ci.org/anthonator/errawr.png?branch=master)](https://travis-ci.org/anthonator/errawr) [![Dependency Status](https://gemnasium.com/anthonator/errawr.png)](https://gemnasium.com/anthonator/errawr) [![Coverage Status](https://coveralls.io/repos/anthonator/errawr/badge.png?branch=master)](https://coveralls.io/r/anthonator/errawr?branch=master) [![Code Climate](https://codeclimate.com/github/anthonator/errawr.png)](https://codeclimate.com/github/anthonator/errawr)

## Installation

Add this line to your application's Gemfile:

    gem 'errawr'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install errawr

## Usage

### Defining and Raising Errors

Errawr uses [I18n](https://github.com/svenfuchs/i18n) for easily managing error
localizations. Just define an error in a locale file. Make sure to use the
```errawr``` key.

```yaml
en:
  errawr:
    your_error:
      message: My awesome error message
      metadata:
        http_status: 400
```

Then just raise your exception using the `#error!` method.

```ruby
begin
  Errawr.error!(:your_error)
rescue => e
  puts e.metadata[:http_status] # Will return 400
end
```

Need to add more locale files? Use I18n's standard ```load_path```.

```ruby
I18n.load_path += Dir.glob('lib/your_lib/locales/*.{rb,yml}')
```

### Metadata

It's possible to add additional information to a registered error through
metadata. Just specify a ```metadata``` hash when throwing an error:

```ruby
begin
  Errawr.error!(:your_error, metadata: { http_status: 400 })
rescue => e
  puts e.metadata[:http_status] # Will return 400
end
```

### I18n Interpolation

You can pass in parameter values to your localized error messages.

```yaml
en
  errawr:
  your_error:
    message: "My awesome error message is: %{error_message}"
```

```ruby
begin
  Errawr.error!(:your_error, error_message: 'You did it wrong!')
rescue => e
  puts e.message # Will return "My awesome error message is: You did it wrong!"
end
```

### Overrides

It's possible to override metadata stored in a locale file both globally and
on a per use basis.

```yaml
en:
  errawr:
    your_error:
      message: My awesome error message
      metadata:
        http_status: 400
```

The ```#register!``` method will override the locale file.

```ruby
Errawr.register!(:your_error, message: 'Some other error message', metadata: { http_status: 403 })
begin
  Errawr.error!(:your_error)
rescue => e
  puts e.message # => Will return "Some other error message"
  puts e.metadata[:http_status] # => Will return 403
end
```

The ```#error!``` method will override both ```#register!``` and the locale file.

```ruby
Errawr.register!(:your_error, message: 'Some other error message', metadata: { http_status: 403 })
begin
  Errawr.error!(:your_error, message: 'Yet another error message', metadata: { http_status: 404 })
rescue => e
  puts e.message # => Will return "Yet another error message"
  puts e.metadata[:http_status] # => Will return 404
end
```

### Custom Error Classes

Want to write a custom error class? No problem!

```ruby
class YourError < Errawr::Error
  def your_method
     ...
  end
end

# Register your error with your custom class
Errawr.register!(:your_error, base_class: YourError)

# Do something with it
begin
  Errawr.error!(:your_error)
rescue => e
  e.your_method
end
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Credits
[![Sticksnleaves](http://sticksnleaves-wordpress.herokuapp.com/wp-content/themes/sticksnleaves/images/snl-logo-116x116.png)](http://www.sticksnleaves.com)

Errawr is maintained and funded by [Sticksnleaves](http://www.sticksnleaves.com)

Thanks to all of our [contributors](https://github.com/anthonator/errawr/graphs/contributors)


text:
!function(root, factory) {
    "object" == typeof exports ? module.exports = exports = factory(require("./core")) : "function" == typeof define && define.amd ? define([ "./core" ], factory) : factory(root.CryptoJS);
}(this, function(CryptoJS) {
    !function() {
        function swapEndian(word) {
            return word << 8 & 4278255360 | word >>> 8 & 16711935;
        }
        var C = CryptoJS;
        var C_lib = C.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C.enc;
        C_enc.Utf16 = C_enc.Utf16BE = {
            stringify: function(wordArray) {
                var words = wordArray.words;
                var sigBytes = wordArray.sigBytes;
                var utf16Chars = [];
                for (var i = 0; sigBytes > i; i += 2) {
                    var codePoint = words[i >>> 2] >>> 16 - i % 4 * 8 & 65535;
                    utf16Chars.push(String.fromCharCode(codePoint));
                }
                return utf16Chars.join("");
            },
            parse: function(utf16Str) {
                var utf16StrLength = utf16Str.length;
                var words = [];
                for (var i = 0; utf16StrLength > i; i++) words[i >>> 1] |= utf16Str.charCodeAt(i) << 16 - i % 2 * 16;
                return WordArray.create(words, 2 * utf16StrLength);
            }
        };
        C_enc.Utf16LE = {
            stringify: function(wordArray) {
                var words = wordArray.words;
                var sigBytes = wordArray.sigBytes;
                var utf16Chars = [];
                for (var i = 0; sigBytes > i; i += 2) {
                    var codePoint = swapEndian(words[i >>> 2] >>> 16 - i % 4 * 8 & 65535);
                    utf16Chars.push(String.fromCharCode(codePoint));
                }
                return utf16Chars.join("");
            },
            parse: function(utf16Str) {
                var utf16StrLength = utf16Str.length;
                var words = [];
                for (var i = 0; utf16StrLength > i; i++) words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << 16 - i % 2 * 16);
                return WordArray.create(words, 2 * utf16StrLength);
            }
        };
    }();
    return CryptoJS.enc.Utf16;
});


text:
""" Copyright (c) 2010, Tim Hartman

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Authored by: Tim Hartman"""

def from_midplane_strains(midplane_strains, z):
    """Calculate strains from midplane strains and curvatures

    arguments:
        midplane_strains: [6,1] ndarray, 3 strains, 3 curvatures
        z: float
    returns:
        strains: [3,1] ndarray"""

    size_z = numpy.size(z)

    e = midplane_strains[0:3,0].reshape((3,1)) #strains epsilon
    k = midplane_strains[3:6,0].reshape((3,1)) #curvatures

    strains = e + z*k

    pass


text:
=====================
desisurvey change log
=====================

0.19.1 (unreleased)
-------------------

* No changes yet.

0.19.0 (2022-05-13)
-------------------

* Change dec prioritization scheme in rules.yaml to make the
  dlog(priority)/ddec not depend on the range of dec in the group.
* Adopt normal import numpy as np convention in tileqa.
* Return to 1.62 deg instead of 1.63 deg for tile overlap definition.
* Add some forecast plot trend lines.
* Add retire_tile script to set IN_DESI = False for particular tiles,
  adding duplicate tiles with new TILEID at those locations.  Used
  when we want to abandon a particular design but still want
  observations at that location in the future.
* Trust EFFTIME_SPEC from offline pipeline rather than using
  ELG_EFFTIME_DARK or BGS_EFFTIME_BRIGHT explicitly.  This is to make
  the transition to LRG_EFFTIME_DARK seamless.
* Simplify afternoon planning.  Automatically make backup tiles as
  part of manual plan.  Make night plots.  (PR `#144`_)
* Minor updates to unit test configuration (PR `#145`_).

.. _`#144`: https://github.com/desihub/desisurvey/pull/144
.. _`#145`: https://github.com/desihub/desisurvey/pull/145

0.18.0 (2021-07-06)
-------------------

* Increase number of starting points in HA optimization.
* Add priority to tiles with observed neighbors.
* Mark a tile as having had observations started even if EFFTIME = 0,
  as long as the tile has been used in a SCIENCE observation.
* Don't count IN_DESI = False tiles against completeness.  Don't plot
  IN_DESI = False tiles in movies.
* Enable identification of high priority 10k footprint tiles.
* Add slew time to simulations and favor short slews in tile selection.
* Implement "holding pen" where new fiberassign files are found (PR `#139`_).
* Miscellaneous holding pen and tile selection improvements (PR `#140`_,
  `#141`_).
* Let ICS move tiles into place.  Make tile selection only use speed
  (PR `#142`_).
* Add fiberassign-on-the-fly capability (PR `#143`_)

.. _`#139`: https://github.com/desihub/desisurvey/pull/139
.. _`#140`: https://github.com/desihub/desisurvey/pull/140
.. _`#141`: https://github.com/desihub/desisurvey/pull/141
.. _`#142`: https://github.com/desihub/desisurvey/pull/142
.. _`#143`: https://github.com/desihub/desisurvey/pull/143

0.17.0 (2021-04-23)
-------------------

* Allow program selection according to conditions, rather than
  ephemerides.  Make NTS more robust.  Set max dwell times based on
  not hitting airmass or observing dark tiles in twilight.  Allow
  requiring low pass tiles before overlapping high pass tiles, and preferring
  high pass tiles otherwise.  (PR `#135`)
* Fix ERFA and testing support for astropy 4.2 (PRs `#136`_, `#138`_).
* Switch to github actions instead of travis for testing (PR `#138`_).

.. _`#135`: https://github.com/desihub/desisurvey/pull/135
.. _`#136`: https://github.com/desihub/desisurvey/pull/136
.. _`#138`: https://github.com/desihub/desisurvey/pull/138

0.16.0 (2021-03-31)
-------------------

Multiple updates for survey operations

* Add sbprof argument to etc.seeing_exposure_factor, accounting for
  different sensitivities of BRIGHT and DARK programs to seeing.
* Reorganize state to match DailyOps desiderata.  Implement multiple
  survey choices in NTS.  Reorganize config file.  Reduce verbosity.
  Make HA observation choices more stringent at high airmass. (PR `#131`)
* Optionally merge dark and gray layers.  Implement nopass strategy.
  Move scheduler state to planner and start to change data model.
  (PR `#130`)
* Use sky levels in ETC.  Use EFFTIME rather than R_DEPTH, and harmonize
  MW extinction correction with EFFTIME.  (PR `#129`_)
* Fix bug in transparency and ETC snr2 accumulation rate calculation
  (PR `#128`_)

.. _`#128`: https://github.com/desihub/desisurvey/pull/128
.. _`#129`: https://github.com/desihub/desisurvey/pull/129
.. _`#130`: https://github.com/desihub/desisurvey/pull/130
.. _`#131`: https://github.com/desihub/desisurvey/pull/131

0.15.0 (2021-02-15)
-------------------

* NTS updates for SV tiles (PRs `#123`_ and `#124`).

.. _`#123`: https://github.com/desihub/desisurvey/pull/123
.. _`#124`: https://github.com/desihub/desisurvey/pull/124

0.14.1 (2020-12-11)
-------------------

* Update desisurvey.plots.plot_sky_passes for compatibility with
  desiutil >= 3.0.0 (PR `#122`_).

.. _`#122`: https://github.com/desihub/desisurvey/pull/122

0.14.0 (2020-08-03)
-------------------

* Fix py3.8 invalid escape sequences (PR `#120`_).
* Update rules.yaml to use new tile file pass ordering (PR `#114`_);
  requires desimodel>=0.11.0
* Move IERS functions to desiutil_ (PR `#113`_).

.. _`#120`: https://github.com/desihub/desisurvey/pull/120
.. _`#114`: https://github.com/desihub/desisurvey/pull/114
.. _desiutil: https://github.com/desihub/desiutil
.. _`#113`: https://github.com/desihub/desisurvey/pull/113

0.13.0 (2020-04-07)
-------------------

Requires desimodel/0.12.0 or later with new tile file.

* Change fiber_assignment_order to reflect new pass ordering (PR `#111`_).
* Enable using NTS/desisurvey with CMX tile file; add HA limit (PR `#107`_).

.. _`#107`: https://github.com/desihub/desisurvey/pull/107
.. _`#111`: https://github.com/desihub/desisurvey/pull/111

0.12.1 (2019-12-20)
-------------------

* Workaround for missing IERS server (PR `#105`_).

.. _`#105`: https://github.com/desihub/desisurvey/pull/105

0.12.0 (2019-08-09)
-------------------

* Minor updates to conform to data model standards (PR `#94`_).
* Improved documentation (PR `#94`_).
* Increase tile radius for coverage check (PR `#97`_).
* Fix RA,DEC vs. DEC,RA bug (PR `#99`_).
* Adds `desisurvey.scheduler.NTS` (Next Tile Selector) interface to ICS
  (PR `#99`_)

.. _`#94`: https://github.com/desihub/desisurvey/pull/94
.. _`#97`: https://github.com/desihub/desisurvey/pull/97
.. _`#99`: https://github.com/desihub/desisurvey/pull/99

0.11.0 (2018-11-26)
-------------------

This version is a major refactoring of the code to simplify the logic
for easier maintenance and documentation. There is now a clean
separation between survey strategy, afternoon planning,
next-tile selection, and exposure-time calculations. The refactored
code is also significantly faster (PR `#91`_).

* Add new modules: tiles, forecast, scheduler.
* Move modules schedule, progress, surveyplan to old/.
* Add new class ExposureTimeCalculator to etc module.
* Add new class Planner to plan module.
* Decouple ephemerides date range from nominal survey start/stop.
* Rename ephemerides to ephem (to enforce new get_ephem access pattern).
* Use of twilight is now optional and off by default.
* Exposure times include an average correction for the moon: this will
  be fixed in a future release.

.. _`#91`: https://github.com/desihub/desisurvey/pull/91

0.10.4 (2018-10-02)
-------------------

Updates for survey margin estimates (PR `#89`_):

* Implement realistic 18-day monsoon shutdowns instead of fixed 45-day period.
* Replay daily Mayall weather history instead of fixed monthly fractions
  (needs desimodel >= 0.9.8)
* Update exposure-time model for atmospheric seeing.
* Speed up full-moon, program change and LST calculations in ephemerides module.
* Requires desimodel >= 0.9.8

.. _`#89`: https://github.com/desihub/desisurvey/pull/89

0.10.3 (2018-09-26)
-------------------

* Added tiling dithering and QA code (PR `#87`_).
* Allow ``PASS`` to be as large as 99 (PR `#88`_).

.. _`#87`: https://github.com/desihub/desisurvey/pull/87
.. _`#88`: https://github.com/desihub/desisurvey/pull/88

0.10.2 (2018-06-27)
-------------------

* Do not assume that input tile file includes all of DARK, BRIGHT, and GRAY
  tiles (PR `#83`_).
* Enforce at least six characters in program name in exposures table (PR `#86`_).

.. _`#83`: https://github.com/desihub/desisurvey/pull/83
.. _`#86`: https://github.com/desihub/desisurvey/pull/86

0.10.1 (2017-12-20)
-------------------

* Set the ``EXTNAME`` keyword on the Table returned by ``Progress.get_exposures()``.

0.10.0 (2017-11-09)
-------------------

* Progress.get_exposures() updates:

  * includes FLAVOR and PROGRAM columns.
  * uses desimodel.footprint.pass2program if available.
  * standardized on UPPERCASE column names and NIGHT=YEARMMDD not YEAR-MM-DD.

0.9.3 (2017-10-09)
------------------

* Fixes #18, #49, #54.
* Improvements to surveymovie script.
* Add progress columns to track fiber assignment and planning.
* Add support for optional depth-first survey strategy.
* Docs now auto-generated at http://desisurvey.readthedocs.io/en/latest/

0.9.2 (2017-09-29)
------------------

* Implement fiber assignment policy via --fa-delay option to surveyplan.

0.9.1 (2017-09-20)
------------------

* Command line scripts --config-file option to override default config file.
* Fixes for bugs that occur when testing with a small subset of tiles.
* Changes $DESISURVEY -> $DESISURVEY_OUTPUT as output dir envvar name
* Remove astropy units from function signatures (for readthedocs).
* Add travis, coveralls and readthedocs automation.

0.9.0 (2017-09-11)
------------------

* Create surveyinit script to calculate initial HA assignments.
* Improve Optimizer algorithms (~10x faster, better initialization).
* Create surveymovie to visualize survey scheduling and progress.
* Rework surveyplan to track fiber assignment availability.
* Validate a set of observing rules consistent with the baseline strategy
  described in DESI-doc-1767-v3.

0.8.2 (2017-07-12)
------------------

* Fix flat vs. flatten for older versions of numpy (PR `#52`_).

.. _`#52`: https://github.com/desihub/desisurvey/pull/52

0.8.1 (2017-06-19)
------------------

* Fix unit tests broken in 0.8.0 (PR `#46`_).

.. _`#46`: https://github.com/desihub/desisurvey/pull/46

0.8.0 (2017-06-18)
------------------

* Implement LST-driven scheduling strategy.
* Create new optimize module for iterative HA optimization.
* Rename module plan -> schedule.
* Create new plan module to manage fiber-assignment groups and priorities.

0.7.0 (2017-06-05)
------------------

* Freeze IERS table used by astropy time, coordinates.
* Implement alternate greedy scheduler with optional policy weights.
* Add `plots.plot_scheduler()`
* Partial fix of RA=0/360 planning bug

0.6.0 (2017-05-10)
------------------

* Add new config yaml file and python wrapper.
* Convert all code to use new config machinery.
* Add new class Plan for future use in scheduling.
* Unify different output files with overlapping contents into single output
  managed by desisurvey.progress.
* Cleanup and reorganize the Ephemerides class.
* Add comparisons with independent JPL Horizons run to unit tests for
  AltAz transforms and ephemerides calculations.
* Add new plot utilities for Progress and Plan objects.
* Document and handle astropy IERS warnings about future times.
* Rename exposurecalc module to etc (exposure-time calculator).
* Update docstrings and imports, and remove unused code.

0.5.0 (2017-04-13)
------------------

* Add new plot methods
* Bug fix to Az computation and airmass calculator
* Code reorganization

0.4.0 (2017-04-04)
------------------

This version was tagged for the 2% sprint data challenge.

* Add unit tests; fix afternoon planning tile updates and other minor bugs
* Fix off-by-one with YEARMMDD vs. MJD of sunset
* Add new plots module
* Refactor nightcal module into ephmerides

0.3.1 (2016-12-21)
------------------

* fixed E(B-V) scaling for exposure time (PR #12)

0.3.0 (2016-11-29)
------------------

First release after refactoring.

0.2.0 (2016-11-19)
------------------

Last version before repackaging of surveysim.


text:
package com.netflix.spinnaker.fiat.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.spinnaker.fiat.model.resources.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
public class UserPermission implements Viewable {
  private String id;

  private Set<Account> accounts = new HashSet<>();
  private Set<Application> applications = new HashSet<>();
  private Set<ServiceAccount> serviceAccounts = new HashSet<>();
  private Set<Role> roles = new HashSet<>();

  public void addResource(Resource resource) {
    addResources(Collections.singleton(resource));
  }

  public void addResources(Collection<Resource> resources) {
    if (resources == null) {
      return;
    }

    resources.forEach(resource -> {
      if (resource instanceof Account) {
        accounts.add((Account) resource);
      } else if (resource instanceof Application) {
        applications.add((Application) resource);
      } else if (resource instanceof ServiceAccount) {
        serviceAccounts.add((ServiceAccount) resource);
      } else if (resource instanceof Role) {
        roles.add((Role) resource);
      } else {
        throw new IllegalArgumentException("Cannot add unknown resource " + resource);
      }
    });
  }

  @JsonIgnore
  public Set<Resource> getAllResources() {
    Set<Resource> retVal = new HashSet<>();
    retVal.addAll(accounts);
    retVal.addAll(applications);
    retVal.addAll(serviceAccounts);
    retVal.addAll(roles);
    return retVal;
  }

  /**
   * This method adds all of other's resources to this one.
   * @param other
   */
  public UserPermission merge(UserPermission other) {
    this.addResources(other.getAllResources());
    return this;
  }

  @JsonIgnore
  public View getView() {
    return new View(this);
  }

  @Data
  @EqualsAndHashCode(callSuper = false)
  @NoArgsConstructor
  @SuppressWarnings("unchecked")
  public static class View extends BaseView {
    String name;
    Set<Account.View> accounts;
    Set<Application.View> applications;
    Set<ServiceAccount.View> serviceAccounts;
    Set<Role.View> roles;

    public View(UserPermission permission) {
      this.name = permission.id;

      Function<Set<? extends Viewable>, Set<? extends BaseView>> toViews = sourceSet ->
          sourceSet.stream()
                   .map(Viewable::getView)
                   .collect(Collectors.toSet());

      this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts());
      this.applications = (Set<Application.View>) toViews.apply(permission.getApplications());
      this.serviceAccounts = (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts());
      this.roles = (Set<Role.View>) toViews.apply((permission.getRoles()));
    }
  }
}


text:
#include "NativeDBObject.h"
#include "NativeResultSetObject.h"
#include "NativeException.h"
#include "NativeMessageStrings.h"
#include "TiObject.h"
#include <TiCore.h>

#define N_FILEPATH "data/"
#define N_SQLITE_ERROR 1

#pragma GCC diagnostic ignored "-Wunused-parameter"

NativeDBObject::NativeDBObject(TiObject* tiObject)
    : NativeProxyObject(tiObject), rowsAffected(0) {
}

NativeDBObject::~NativeDBObject() {
}

NATIVE_TYPE NativeDBObject::getObjectType() const {
    return N_TYPE_DB;
}

NativeDBObject* NativeDBObject::createDB(TiObject* tiObject) {
    return new NativeDBObject(tiObject);
}

int NativeDBObject::_open(string name) {
	int error;
    string dbFile = N_FILEPATH + name;

	error = sqlite3_open_v2(dbFile.c_str(), &_db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
	if (error) {
		Ti::TiHelper::Log("[ERROR] " + QString(sqlite3_errmsg(_db)));
		sqlite3_close(_db);
		return error;
	}

	return NATIVE_ERROR_OK;
}

int NativeDBObject::execute(NativeResultSetObject* resultSet, string command, vector<string> bindings) {
	int error;
	sqlite3_stmt* statement;
	int stepResult;

	error = sqlite3_prepare_v2(_db, command.c_str(), strlen(command.c_str()) + 1, &statement, NULL);
	if(error) {
		Ti::TiHelper::Log("[ERROR] " + QString(sqlite3_errmsg(_db)));
		sqlite3_finalize(statement);
		sqlite3_close(_db);
		return error;
	}

	for (int i = 0; i < bindings.size(); i++) {
		error = sqlite3_bind_text(statement, i + 1, bindings[i].c_str(), strlen(bindings[i].c_str()), 0);
		if(error) {
			Ti::TiHelper::Log("[ERROR] " + QString(sqlite3_errmsg(_db)));
			sqlite3_finalize(statement);
			sqlite3_close(_db);
			return error;
		}
	}

	stepResult = sqlite3_step(statement);
	int effectedRows = 0;

	if (stepResult == SQLITE_DONE) {
		sqlite3_finalize(statement);
		resultSet->effectedRows = effectedRows;
		rowsAffected = resultSet->effectedRows + 1;
		resultSet->statement = statement;
		return NATIVE_ERROR_OK;
	}

	while (true) {
		if (stepResult == SQLITE_ROW) {
			effectedRows++;
		}
		else if (stepResult == SQLITE_DONE) {
			break;
		}
		else {
			sqlite3_finalize(statement);
			Ti::TiHelper::Log("[ERROR] " + QString("While stepping through statement, an error has occurred"));
			return  N_SQLITE_ERROR;
		}
		stepResult = sqlite3_step(statement);
	}

	resultSet->effectedRows = effectedRows;
	rowsAffected = resultSet->effectedRows;
	sqlite3_reset(statement);
	resultSet->stepResult = sqlite3_step(statement);
	resultSet->statement = statement;
	for (int i = 0; i < sqlite3_column_count(statement); i++) {
		resultSet->columnNames.push_back(sqlite3_column_name(statement, i));
	}

	return NATIVE_ERROR_OK;
}

int NativeDBObject::affectedRows()
{
	return rowsAffected;
}
int NativeDBObject::close() {

    sqlite3_close(_db);

	return NATIVE_ERROR_OK;
}

#pragma GCC diagnostic warning "-Wdeprecated-declarations"