text:
\hypertarget{client_8h}{\section{/home/emeric/projets/\-C\-Bay/sources/client.h File Reference}
\label{client_8h}\index{/home/emeric/projets/\-C\-Bay/sources/client.\-h@{/home/emeric/projets/\-C\-Bay/sources/client.\-h}}
}

This file provides function for a B\-E\-E\-P client. It also contains fonction to send data using other methods than connect (typically G\-E\-T, P\-U\-T and D\-E\-L\-E\-T\-E) or function to split and extract data from incoming answer from the server.

This graph shows which files directly or indirectly include this file\-:
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
int \hyperlink{client_8h_abe1049a65b4c371391d44856b02e03d9}{Init} (char $\ast$server)
\begin{DoxyCompactList}\small\item\em Connection to the server. \end{DoxyCompactList}\item
int \hyperlink{client_8h_a47e4b0a69e690abdcc95a08fa660c819}{receive\-Binary} (char $\ast$donnees, size\-\_\-t taille\-Max)
\begin{DoxyCompactList}\small\item\em receive binary datas from the server and store them in a character array \end{DoxyCompactList}\item
int \hyperlink{client_8h_a89f1959ce9abb4013dd6a8e6a26a08f7}{send\-Binary} (char $\ast$donnees, size\-\_\-t taille)
\begin{DoxyCompactList}\small\item\em send to the server datas from a character array \end{DoxyCompactList}\item
int \hyperlink{client_8h_ad43491844975cb6318cf40550b62e54d}{send\-Get\-Object\-Bid} (\hyperlink{struct_object_bid}{Object\-Bid} $\ast$object)
\begin{DoxyCompactList}\small\item\em send a request to the server to get an object \end{DoxyCompactList}\item
int \hyperlink{client_8h_a6749551ed05b3290335d8100c0ec0072}{send\-Get\-All\-Object\-Bid} ()
\begin{DoxyCompactList}\small\item\em send a request to the server to get all the objects \end{DoxyCompactList}\item
int \hyperlink{client_8h_a8adfc5e934eb14484a855e5436ca528b}{send\-Put\-Object\-Bid} (\hyperlink{struct_object_bid}{Object\-Bid} $\ast$object)
\begin{DoxyCompactList}\small\item\em send a request to the server to store an object in it \end{DoxyCompactList}\item
int \hyperlink{client_8h_ac0af861680d0c9ae7d0c347137f8c1b1}{send\-Delete\-Object\-Bid} (\hyperlink{struct_object_bid}{Object\-Bid} $\ast$object)
\begin{DoxyCompactList}\small\item\em send a request to the server to delete an object \end{DoxyCompactList}\item
int \hyperlink{client_8h_a3c93f98fe4a9853dba34b5415627afaa}{send\-Get\-User\-Account} (\hyperlink{struct_user_account}{User\-Account} $\ast$account)
\begin{DoxyCompactList}\small\item\em send a request to the server to get an user account \end{DoxyCompactList}\item
int \hyperlink{client_8h_aa299cb38810025467a6515bfcc834321}{send\-Put\-User\-Account} (\hyperlink{struct_user_account}{User\-Account} $\ast$account)
\begin{DoxyCompactList}\small\item\em send a request to the server to store an user account in it \end{DoxyCompactList}\item
int \hyperlink{client_8h_a2ebe477642298bc447e6be2cc8d6fb9f}{send\-Delete\-User\-Account} (\hyperlink{struct_user_account}{User\-Account} $\ast$account)
\begin{DoxyCompactList}\small\item\em send a request to the server to delete an user account \end{DoxyCompactList}\item
int \hyperlink{client_8h_a8791da4cdcf01088069bea80b08eb91d}{send\-Connect} (char $\ast$login, char $\ast$password)
\begin{DoxyCompactList}\small\item\em send a request to the server to connect an user to the C\-Bay service \end{DoxyCompactList}\item
int \hyperlink{client_8h_aef64283b800d91d6c1a57586f91d6616}{split\-Status\-Line} (char $\ast$status\-Line, int $\ast$status\-Code, char $\ast$status\-Message)
\begin{DoxyCompactList}\small\item\em take a status line and cut it in a status code and a reason phrase \end{DoxyCompactList}\item
int \hyperlink{client_8h_a371a71d09e39732a17a971f549ba695b}{split\-Response\-Header} (char $\ast$response\-Header\-Field, int $\ast$content\-Length, char $\ast$content\-Type)
\begin{DoxyCompactList}\small\item\em take the response header fields and extract the value of fields content-\/length and content-\/type \end{DoxyCompactList}\item
int \hyperlink{client_8h_a433c2400c9c9705371b55c7ec51f31f9}{account\-Creation} ()
\begin{DoxyCompactList}\small\item\em Asks the user for some informations and create a new \hyperlink{struct_user_account}{User\-Account} then send it to the server. \end{DoxyCompactList}\item
int \hyperlink{client_8h_a2204bb5da49d6ebcb2e203855ab2627d}{connection} (\hyperlink{struct_user_account}{User\-Account} $\ast$user)
\begin{DoxyCompactList}\small\item\em Asks the user for a login and a password and try to connect to the server. \end{DoxyCompactList}\item
int \hyperlink{client_8h_a7c273f6fdfa010393ee40637b0795c90}{list\-Objects} (\hyperlink{struct_object_bid}{Object\-Bid} $\ast$$\ast$list, int $\ast$list\-Size)
\item
int \hyperlink{client_8h_a6f10e34ceac93601a3c8caf82f94957a}{search\-Object} (\hyperlink{struct_object_bid}{Object\-Bid} $\ast$list, int list\-Size)
\item
int \hyperlink{client_8h_ae3cd8f1e077cc2a30ae2655d9208775d}{bid\-Object} (\hyperlink{struct_user_account}{User\-Account} client, \hyperlink{struct_object_bid}{Object\-Bid} $\ast$$\ast$list, int list\-Size)
\begin{DoxyCompactList}\small\item\em Asks the user for a bid and send it to the server. Display the result. \end{DoxyCompactList}\item
int \hyperlink{client_8h_aecf6a7972f0be2f1fa93ca0b63dcd255}{enter\-Object} (\hyperlink{struct_user_account}{User\-Account} $\ast$user)
\begin{DoxyCompactList}\small\item\em Add an object into the list of available objects. \end{DoxyCompactList}\item
void \hyperlink{client_8h_ac7ef540969b7383da220fee7814ab22b}{Terminaison} ()
\begin{DoxyCompactList}\small\item\em End the connection. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
This file provides function for a B\-E\-E\-P client. It also contains fonction to send data using other methods than connect (typically G\-E\-T, P\-U\-T and D\-E\-L\-E\-T\-E) or function to split and extract data from incoming answer from the server.

\subsection{Function Documentation}
\hypertarget{client_8h_a433c2400c9c9705371b55c7ec51f31f9}{\index{client.\-h@{client.\-h}!account\-Creation@{account\-Creation}}
\index{account\-Creation@{account\-Creation}!client.h@{client.\-h}}
\subsubsection[{account\-Creation}]{\setlength{\rightskip}{0pt plus 5cm}int account\-Creation (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{client_8h_a433c2400c9c9705371b55c7ec51f31f9}

Asks the user for some informations and create a new \hyperlink{struct_user_account}{User\-Account} then send it to the server.

\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_ae3cd8f1e077cc2a30ae2655d9208775d}{\index{client.\-h@{client.\-h}!bid\-Object@{bid\-Object}}
\index{bid\-Object@{bid\-Object}!client.h@{client.\-h}}
\subsubsection[{bid\-Object}]{\setlength{\rightskip}{0pt plus 5cm}int bid\-Object (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account}}]{client, }
\item[{{\bf Object\-Bid} $\ast$$\ast$}]{list, }
\item[{int}]{list\-Size}
\end{DoxyParamCaption}
)}}\label{client_8h_ae3cd8f1e077cc2a30ae2655d9208775d}

Asks the user for a bid and send it to the server. Display the result.

\begin{DoxyParams}{Parameters}
{\em client} & is the connected user who want to bid for the object, list is the list of object the client will chose from and list\-Size the number of objects in the list \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a2204bb5da49d6ebcb2e203855ab2627d}{\index{client.\-h@{client.\-h}!connection@{connection}}
\index{connection@{connection}!client.h@{client.\-h}}
\subsubsection[{connection}]{\setlength{\rightskip}{0pt plus 5cm}int connection (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account} $\ast$}]{user}
\end{DoxyParamCaption}
)}}\label{client_8h_a2204bb5da49d6ebcb2e203855ab2627d}

Asks the user for a login and a password and try to connect to the server.

\begin{DoxyParams}{Parameters}
{\em user} & is the account sent back by the server if the connection is ok \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
the result (S\-U\-C\-C\-E\-S\-S or C\-O\-N\-N\-E\-C\-T\-I\-O\-N\-\_\-\-D\-E\-N\-I\-E\-D)
\end{DoxyReturn}
\hypertarget{client_8h_aecf6a7972f0be2f1fa93ca0b63dcd255}{\index{client.\-h@{client.\-h}!enter\-Object@{enter\-Object}}
\index{enter\-Object@{enter\-Object}!client.h@{client.\-h}}
\subsubsection[{enter\-Object}]{\setlength{\rightskip}{0pt plus 5cm}int enter\-Object (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account} $\ast$}]{user}
\end{DoxyParamCaption}
)}}\label{client_8h_aecf6a7972f0be2f1fa93ca0b63dcd255}

Add an object into the list of available objects.

\begin{DoxyParams}{Parameters}
{\em user} & is the vendor's account, \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_abe1049a65b4c371391d44856b02e03d9}{\index{client.\-h@{client.\-h}!Init@{Init}}
\index{Init@{Init}!client.h@{client.\-h}}
\subsubsection[{Init}]{\setlength{\rightskip}{0pt plus 5cm}int Init (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{machine}
\end{DoxyParamCaption}
)}}\label{client_8h_abe1049a65b4c371391d44856b02e03d9}

Connection to the server.

initialise the server

\begin{DoxyParams}{Parameters}
{\em server} & is the server's adress \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
S\-U\-C\-C\-E\-S\-S or E\-R\-R\-O\-R\-\_\-\-U\-N\-K\-N\-O\-W\-N
\end{DoxyReturn}

\begin{DoxyParams}{Parameters}
{\em port} & is the port which will be used by the server \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation.
\end{DoxyReturn}
\hypertarget{client_8h_a7c273f6fdfa010393ee40637b0795c90}{\index{client.\-h@{client.\-h}!list\-Objects@{list\-Objects}}
\index{list\-Objects@{list\-Objects}!client.h@{client.\-h}}
\subsubsection[{list\-Objects}]{\setlength{\rightskip}{0pt plus 5cm}int list\-Objects (
\begin{DoxyParamCaption}
\item[{{\bf Object\-Bid} $\ast$$\ast$}]{list, }
\item[{int $\ast$}]{list\-Size}
\end{DoxyParamCaption}
)}}\label{client_8h_a7c273f6fdfa010393ee40637b0795c90}
\hypertarget{client_8h_a47e4b0a69e690abdcc95a08fa660c819}{\index{client.\-h@{client.\-h}!receive\-Binary@{receive\-Binary}}
\index{receive\-Binary@{receive\-Binary}!client.h@{client.\-h}}
\subsubsection[{receive\-Binary}]{\setlength{\rightskip}{0pt plus 5cm}int receive\-Binary (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{donnees, }
\item[{size\-\_\-t}]{taille\-Max}
\end{DoxyParamCaption}
)}}\label{client_8h_a47e4b0a69e690abdcc95a08fa660c819}

receive binary datas from the server and store them in a character array

\begin{DoxyParams}{Parameters}
{\em donnees} & is an array in which we store the incoming data and taille\-Max is the maximum character the function will stock in donnees \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
the number of received bytes, 0 for a closed connection and a negative number in case of an error
\end{DoxyReturn}
\hypertarget{client_8h_a6f10e34ceac93601a3c8caf82f94957a}{\index{client.\-h@{client.\-h}!search\-Object@{search\-Object}}
\index{search\-Object@{search\-Object}!client.h@{client.\-h}}
\subsubsection[{search\-Object}]{\setlength{\rightskip}{0pt plus 5cm}int search\-Object (
\begin{DoxyParamCaption}
\item[{{\bf Object\-Bid} $\ast$}]{list, }
\item[{int}]{list\-Size}
\end{DoxyParamCaption}
)}}\label{client_8h_a6f10e34ceac93601a3c8caf82f94957a}
\hypertarget{client_8h_a89f1959ce9abb4013dd6a8e6a26a08f7}{\index{client.\-h@{client.\-h}!send\-Binary@{send\-Binary}}
\index{send\-Binary@{send\-Binary}!client.h@{client.\-h}}
\subsubsection[{send\-Binary}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Binary (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{donnees, }
\item[{size\-\_\-t}]{taille}
\end{DoxyParamCaption}
)}}\label{client_8h_a89f1959ce9abb4013dd6a8e6a26a08f7}

send to the server datas from a character array

send binary data to the client

\begin{DoxyParams}{Parameters}
{\em donnees} & is an array containing the data we will send and taille\-Max is the maximum character the function will stock in donnees \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
the number of sent bytes, 0 for a closed connection and a negative number in case of an error
\end{DoxyReturn}

\begin{DoxyParams}{Parameters}
{\em data} & binary data to send to the client \\
\hline
{\em size} & data's size \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code for this operation.
\end{DoxyReturn}
\hypertarget{client_8h_a8791da4cdcf01088069bea80b08eb91d}{\index{client.\-h@{client.\-h}!send\-Connect@{send\-Connect}}
\index{send\-Connect@{send\-Connect}!client.h@{client.\-h}}
\subsubsection[{send\-Connect}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Connect (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{login, }
\item[{char $\ast$}]{password}
\end{DoxyParamCaption}
)}}\label{client_8h_a8791da4cdcf01088069bea80b08eb91d}

send a request to the server to connect an user to the C\-Bay service

\begin{DoxyParams}{Parameters}
{\em a} & character array for the login and one for the password \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_ac0af861680d0c9ae7d0c347137f8c1b1}{\index{client.\-h@{client.\-h}!send\-Delete\-Object\-Bid@{send\-Delete\-Object\-Bid}}
\index{send\-Delete\-Object\-Bid@{send\-Delete\-Object\-Bid}!client.h@{client.\-h}}
\subsubsection[{send\-Delete\-Object\-Bid}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Delete\-Object\-Bid (
\begin{DoxyParamCaption}
\item[{{\bf Object\-Bid} $\ast$}]{object}
\end{DoxyParamCaption}
)}}\label{client_8h_ac0af861680d0c9ae7d0c347137f8c1b1}

send a request to the server to delete an object

\begin{DoxyParams}{Parameters}
{\em an} & object \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a2ebe477642298bc447e6be2cc8d6fb9f}{\index{client.\-h@{client.\-h}!send\-Delete\-User\-Account@{send\-Delete\-User\-Account}}
\index{send\-Delete\-User\-Account@{send\-Delete\-User\-Account}!client.h@{client.\-h}}
\subsubsection[{send\-Delete\-User\-Account}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Delete\-User\-Account (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account} $\ast$}]{account}
\end{DoxyParamCaption}
)}}\label{client_8h_a2ebe477642298bc447e6be2cc8d6fb9f}

send a request to the server to delete an user account

\begin{DoxyParams}{Parameters}
{\em an} & user account \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a6749551ed05b3290335d8100c0ec0072}{\index{client.\-h@{client.\-h}!send\-Get\-All\-Object\-Bid@{send\-Get\-All\-Object\-Bid}}
\index{send\-Get\-All\-Object\-Bid@{send\-Get\-All\-Object\-Bid}!client.h@{client.\-h}}
\subsubsection[{send\-Get\-All\-Object\-Bid}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Get\-All\-Object\-Bid (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{client_8h_a6749551ed05b3290335d8100c0ec0072}

send a request to the server to get all the objects

\begin{DoxyParams}{Parameters}
{\em an} & object \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_ad43491844975cb6318cf40550b62e54d}{\index{client.\-h@{client.\-h}!send\-Get\-Object\-Bid@{send\-Get\-Object\-Bid}}
\index{send\-Get\-Object\-Bid@{send\-Get\-Object\-Bid}!client.h@{client.\-h}}
\subsubsection[{send\-Get\-Object\-Bid}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Get\-Object\-Bid (
\begin{DoxyParamCaption}
\item[{{\bf Object\-Bid} $\ast$}]{object}
\end{DoxyParamCaption}
)}}\label{client_8h_ad43491844975cb6318cf40550b62e54d}

send a request to the server to get an object

\begin{DoxyParams}{Parameters}
{\em an} & object \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a3c93f98fe4a9853dba34b5415627afaa}{\index{client.\-h@{client.\-h}!send\-Get\-User\-Account@{send\-Get\-User\-Account}}
\index{send\-Get\-User\-Account@{send\-Get\-User\-Account}!client.h@{client.\-h}}
\subsubsection[{send\-Get\-User\-Account}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Get\-User\-Account (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account} $\ast$}]{account}
\end{DoxyParamCaption}
)}}\label{client_8h_a3c93f98fe4a9853dba34b5415627afaa}

send a request to the server to get an user account

\begin{DoxyParams}{Parameters}
{\em an} & user account \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a8adfc5e934eb14484a855e5436ca528b}{\index{client.\-h@{client.\-h}!send\-Put\-Object\-Bid@{send\-Put\-Object\-Bid}}
\index{send\-Put\-Object\-Bid@{send\-Put\-Object\-Bid}!client.h@{client.\-h}}
\subsubsection[{send\-Put\-Object\-Bid}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Put\-Object\-Bid (
\begin{DoxyParamCaption}
\item[{{\bf Object\-Bid} $\ast$}]{object}
\end{DoxyParamCaption}
)}}\label{client_8h_a8adfc5e934eb14484a855e5436ca528b}

send a request to the server to store an object in it

\begin{DoxyParams}{Parameters}
{\em an} & object \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_aa299cb38810025467a6515bfcc834321}{\index{client.\-h@{client.\-h}!send\-Put\-User\-Account@{send\-Put\-User\-Account}}
\index{send\-Put\-User\-Account@{send\-Put\-User\-Account}!client.h@{client.\-h}}
\subsubsection[{send\-Put\-User\-Account}]{\setlength{\rightskip}{0pt plus 5cm}int send\-Put\-User\-Account (
\begin{DoxyParamCaption}
\item[{{\bf User\-Account} $\ast$}]{account}
\end{DoxyParamCaption}
)}}\label{client_8h_aa299cb38810025467a6515bfcc834321}

send a request to the server to store an user account in it

\begin{DoxyParams}{Parameters}
{\em an} & user account \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_a371a71d09e39732a17a971f549ba695b}{\index{client.\-h@{client.\-h}!split\-Response\-Header@{split\-Response\-Header}}
\index{split\-Response\-Header@{split\-Response\-Header}!client.h@{client.\-h}}
\subsubsection[{split\-Response\-Header}]{\setlength{\rightskip}{0pt plus 5cm}int split\-Response\-Header (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{response\-Header\-Field, }
\item[{int $\ast$}]{content\-Length, }
\item[{char $\ast$}]{content\-Type}
\end{DoxyParamCaption}
)}}\label{client_8h_a371a71d09e39732a17a971f549ba695b}

take the response header fields and extract the value of fields content-\/length and content-\/type

\begin{DoxyParams}{Parameters}
{\em the} & response\-Header\-Field to cut and the content\-Length and content\-Type to extract \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_aef64283b800d91d6c1a57586f91d6616}{\index{client.\-h@{client.\-h}!split\-Status\-Line@{split\-Status\-Line}}
\index{split\-Status\-Line@{split\-Status\-Line}!client.h@{client.\-h}}
\subsubsection[{split\-Status\-Line}]{\setlength{\rightskip}{0pt plus 5cm}int split\-Status\-Line (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{status\-Line, }
\item[{int $\ast$}]{status\-Code, }
\item[{char $\ast$}]{status\-Message}
\end{DoxyParamCaption}
)}}\label{client_8h_aef64283b800d91d6c1a57586f91d6616}

take a status line and cut it in a status code and a reason phrase

\begin{DoxyParams}{Parameters}
{\em the} & status line to cut, the status code and the status\-Message to extract \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
status code of this operation
\end{DoxyReturn}
\hypertarget{client_8h_ac7ef540969b7383da220fee7814ab22b}{\index{client.\-h@{client.\-h}!Terminaison@{Terminaison}}
\index{Terminaison@{Terminaison}!client.h@{client.\-h}}
\subsubsection[{Terminaison}]{\setlength{\rightskip}{0pt plus 5cm}void Terminaison (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{client_8h_ac7ef540969b7383da220fee7814ab22b}

End the connection.

\begin{DoxyReturn}{Returns}
nothing
\end{DoxyReturn}


text:
package diplomacy.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class PasswordUtil {
	public static String sha1(String data) {
		String ret = "";
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA1");
			digest.update(data.getBytes("UTF-8"));
			ret = hex(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			ret = "NoSuchAlgorithmException SHA1";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			ret = "UnsupportedEncodingException UTF-8";
		}
		return ret;
	}
	public static String hex(byte[] data) {
		StringBuilder buf = new StringBuilder();
		for (byte i : data) {
			buf.append(String.format("%02x", i));
		}
		return buf.toString();
	}
	public static String randomString(int length, String table) {
		StringBuilder buf = new StringBuilder();
		Random r = new Random();
		for(int i = 0; i < length; i += 1) {
			int m = r.nextInt(table.length());
			buf.append(table.charAt(m));
		}
		return buf.toString();
	}
	public static String randomString(int length) {
		return randomString(length,
				"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
	}
	public static String password(String raw_password, String salt) {
		String password = sha1(raw_password + salt);
		return String.format("SHA1$%s$%s", salt, password);
	}
	public static String password() {
		return password(randomString(30));
	}
	public static String password(String raw_password) {
		return password(raw_password, randomString(8));
	}
	public static boolean check(String passwd, String raw_passwd) {
		String[] raw = passwd.split("\\$");
		boolean ret = false;
		if (raw.length == 3 && raw[0].equals("SHA1")) {
			ret = passwd.equals(password(raw_passwd, raw[1]));
		}
		return ret;
	}
	public static String invateHash(Long userId) {
		String key = String.format("%dINVITEKEY", userId);
		return sha1(key).substring(0, 7);
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const { Buffer } = require('buffer')
const { URL } = require('iso-url')
const Bignumber = require('bignumber.js').BigNumber

const utils = require('./utils')
const constants = require('./constants')
const MT = constants.MT
const NUMBYTES = constants.NUMBYTES
const SHIFT32 = constants.SHIFT32
const SYMS = constants.SYMS
const TAG = constants.TAG
const HALF = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.TWO
const FLOAT = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.FOUR
const DOUBLE = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.EIGHT
const TRUE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.TRUE
const FALSE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.FALSE
const UNDEFINED = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.UNDEFINED
const NULL = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.NULL

const MAXINT_BN = new Bignumber('0x20000000000000')
const BUF_NAN = Buffer.from('f97e00', 'hex')
const BUF_INF_NEG = Buffer.from('f9fc00', 'hex')
const BUF_INF_POS = Buffer.from('f97c00', 'hex')

function toType (obj) {
  // [object Type]
  // --------8---1
  return ({}).toString.call(obj).slice(8, -1)
}

/**
 * Transform JavaScript values into CBOR bytes
 *
 */
class Encoder {
  /**
   * @param {Object} [options={}]
   * @param {function(Buffer)} options.stream
   */
  constructor (options) {
    options = options || {}

    this.streaming = typeof options.stream === 'function'
    this.onData = options.stream

    this.semanticTypes = [
      [URL, this._pushUrl],
      [Bignumber, this._pushBigNumber]
    ]

    const addTypes = options.genTypes || []
    const len = addTypes.length
    for (let i = 0; i < len; i++) {
      this.addSemanticType(
        addTypes[i][0],
        addTypes[i][1]
      )
    }

    this._reset()
  }

  addSemanticType (type, fun) {
    const len = this.semanticTypes.length
    for (let i = 0; i < len; i++) {
      const typ = this.semanticTypes[i][0]
      if (typ === type) {
        const old = this.semanticTypes[i][1]
        this.semanticTypes[i][1] = fun
        return old
      }
    }
    this.semanticTypes.push([type, fun])
    return null
  }

  push (val) {
    if (!val) {
      return true
    }

    this.result[this.offset] = val
    this.resultMethod[this.offset] = 0
    this.resultLength[this.offset] = val.length
    this.offset++

    if (this.streaming) {
      this.onData(this.finalize())
    }

    return true
  }

  pushWrite (val, method, len) {
    this.result[this.offset] = val
    this.resultMethod[this.offset] = method
    this.resultLength[this.offset] = len
    this.offset++

    if (this.streaming) {
      this.onData(this.finalize())
    }

    return true
  }

  _pushUInt8 (val) {
    return this.pushWrite(val, 1, 1)
  }

  _pushUInt16BE (val) {
    return this.pushWrite(val, 2, 2)
  }

  _pushUInt32BE (val) {
    return this.pushWrite(val, 3, 4)
  }

  _pushDoubleBE (val) {
    return this.pushWrite(val, 4, 8)
  }

  _pushNaN () {
    return this.push(BUF_NAN)
  }

  _pushInfinity (obj) {
    const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS
    return this.push(half)
  }

  _pushFloat (obj) {
    const b2 = Buffer.allocUnsafe(2)

    if (utils.writeHalf(b2, obj)) {
      if (utils.parseHalf(b2) === obj) {
        return this._pushUInt8(HALF) && this.push(b2)
      }
    }

    const b4 = Buffer.allocUnsafe(4)
    b4.writeFloatBE(obj, 0)
    if (b4.readFloatBE(0) === obj) {
      return this._pushUInt8(FLOAT) && this.push(b4)
    }

    return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj)
  }

  _pushInt (obj, mt, orig) {
    const m = mt << 5
    if (obj < 24) {
      return this._pushUInt8(m | obj)
    }

    if (obj <= 0xff) {
      return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj)
    }

    if (obj <= 0xffff) {
      return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj)
    }

    if (obj <= 0xffffffff) {
      return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj)
    }

    if (obj <= Number.MAX_SAFE_INTEGER) {
      return this._pushUInt8(m | NUMBYTES.EIGHT) &&
        this._pushUInt32BE(Math.floor(obj / SHIFT32)) &&
        this._pushUInt32BE(obj % SHIFT32)
    }

    if (mt === MT.NEG_INT) {
      return this._pushFloat(orig)
    }

    return this._pushFloat(obj)
  }

  _pushIntNum (obj) {
    if (obj < 0) {
      return this._pushInt(-obj - 1, MT.NEG_INT, obj)
    } else {
      return this._pushInt(obj, MT.POS_INT)
    }
  }

  _pushNumber (obj) {
    switch (false) {
      case (obj === obj): // eslint-disable-line
        return this._pushNaN(obj)
      case isFinite(obj):
        return this._pushInfinity(obj)
      case ((obj % 1) !== 0):
        return this._pushIntNum(obj)
      default:
        return this._pushFloat(obj)
    }
  }

  _pushString (obj) {
    const len = Buffer.byteLength(obj, 'utf8')
    return this._pushInt(len, MT.UTF8_STRING) && this.pushWrite(obj, 5, len)
  }

  _pushBoolean (obj) {
    return this._pushUInt8(obj ? TRUE : FALSE)
  }

  _pushUndefined (obj) {
    return this._pushUInt8(UNDEFINED)
  }

  _pushArray (gen, obj) {
    const len = obj.length
    if (!gen._pushInt(len, MT.ARRAY)) {
      return false
    }
    for (let j = 0; j < len; j++) {
      if (!gen.pushAny(obj[j])) {
        return false
      }
    }
    return true
  }

  _pushTag (tag) {
    return this._pushInt(tag, MT.TAG)
  }

  _pushDate (gen, obj) {
    // Round date, to get seconds since 1970-01-01 00:00:00 as defined in
    // Sec. 2.4.1 and get a possibly more compact encoding. Note that it is
    // still allowed to encode fractions of seconds which can be achieved by
    // changing overwriting the encode function for Date objects.
    return gen._pushTag(TAG.DATE_EPOCH) && gen.pushAny(Math.round(obj / 1000))
  }

  _pushBuffer (gen, obj) {
    return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj)
  }

  _pushNoFilter (gen, obj) {
    return gen._pushBuffer(gen, obj.slice())
  }

  _pushRegexp (gen, obj) {
    return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source)
  }

  _pushSet (gen, obj) {
    if (!gen._pushInt(obj.size, MT.ARRAY)) {
      return false
    }
    for (const x of obj) {
      if (!gen.pushAny(x)) {
        return false
      }
    }
    return true
  }

  _pushUrl (gen, obj) {
    return gen._pushTag(TAG.URI) && gen.pushAny(obj.format())
  }

  _pushBigint (obj) {
    let tag = TAG.POS_BIGINT
    if (obj.isNegative()) {
      obj = obj.negated().minus(1)
      tag = TAG.NEG_BIGINT
    }
    let str = obj.toString(16)
    if (str.length % 2) {
      str = '0' + str
    }
    const buf = Buffer.from(str, 'hex')
    return this._pushTag(tag) && this._pushBuffer(this, buf)
  }

  _pushBigNumber (gen, obj) {
    if (obj.isNaN()) {
      return gen._pushNaN()
    }
    if (!obj.isFinite()) {
      return gen._pushInfinity(obj.isNegative() ? -Infinity : Infinity)
    }
    if (obj.isInteger()) {
      return gen._pushBigint(obj)
    }
    if (!(gen._pushTag(TAG.DECIMAL_FRAC) &&
      gen._pushInt(2, MT.ARRAY))) {
      return false
    }

    const dec = obj.decimalPlaces()
    const slide = obj.multipliedBy(new Bignumber(10).pow(dec))
    if (!gen._pushIntNum(-dec)) {
      return false
    }
    if (slide.abs().isLessThan(MAXINT_BN)) {
      return gen._pushIntNum(slide.toNumber())
    } else {
      return gen._pushBigint(slide)
    }
  }

  _pushMap (gen, obj) {
    if (!gen._pushInt(obj.size, MT.MAP)) {
      return false
    }

    return this._pushRawMap(
      obj.size,
      Array.from(obj)
    )
  }

  _pushObject (obj) {
    if (!obj) {
      return this._pushUInt8(NULL)
    }

    const len = this.semanticTypes.length
    for (let i = 0; i < len; i++) {
      if (obj instanceof this.semanticTypes[i][0]) {
        return this.semanticTypes[i][1].call(obj, this, obj)
      }
    }

    const f = obj.encodeCBOR
    if (typeof f === 'function') {
      return f.call(obj, this)
    }

    const keys = Object.keys(obj)
    const keyLength = keys.length
    if (!this._pushInt(keyLength, MT.MAP)) {
      return false
    }

    return this._pushRawMap(
      keyLength,
      keys.map((k) => [k, obj[k]])
    )
  }

  _pushRawMap (len, map) {
    // Sort keys for canoncialization
    // 1. encode key
    // 2. shorter key comes before longer key
    // 3. same length keys are sorted with lower
    //    byte value before higher

    map = map.map(function (a) {
      a[0] = Encoder.encode(a[0])
      return a
    }).sort(utils.keySorter)

    for (let j = 0; j < len; j++) {
      if (!this.push(map[j][0])) {
        return false
      }

      if (!this.pushAny(map[j][1])) {
        return false
      }
    }

    return true
  }

  /**
   * Alias for `.pushAny`
   *
   * @param {*} obj
   * @returns {boolean} true on success
   */
  write (obj) {
    return this.pushAny(obj)
  }

  /**
   * Push any supported type onto the encoded stream
   *
   * @param {any} obj
   * @returns {boolean} true on success
   */
  pushAny (obj) {
    const typ = toType(obj)

    switch (typ) {
      case 'Number':
        return this._pushNumber(obj)
      case 'String':
        return this._pushString(obj)
      case 'Boolean':
        return this._pushBoolean(obj)
      case 'Object':
        return this._pushObject(obj)
      case 'Array':
        return this._pushArray(this, obj)
      case 'Uint8Array':
        return this._pushBuffer(this, Buffer.isBuffer(obj) ? obj : Buffer.from(obj))
      case 'Null':
        return this._pushUInt8(NULL)
      case 'Undefined':
        return this._pushUndefined(obj)
      case 'Map':
        return this._pushMap(this, obj)
      case 'Set':
        return this._pushSet(this, obj)
      case 'URL':
        return this._pushUrl(this, obj)
      case 'BigNumber':
        return this._pushBigNumber(this, obj)
      case 'Date':
        return this._pushDate(this, obj)
      case 'RegExp':
        return this._pushRegexp(this, obj)
      case 'Symbol':
        switch (obj) {
          case SYMS.NULL:
            return this._pushObject(null)
          case SYMS.UNDEFINED:
            return this._pushUndefined(undefined)
          // TODO: Add pluggable support for other symbols
          default:
            throw new Error('Unknown symbol: ' + obj.toString())
        }
      default:
        throw new Error('Unknown type: ' + typeof obj + ', ' + (obj ? obj.toString() : ''))
    }
  }

  finalize () {
    if (this.offset === 0) {
      return null
    }

    const result = this.result
    const resultLength = this.resultLength
    const resultMethod = this.resultMethod
    const offset = this.offset

    // Determine the size of the buffer
    let size = 0
    let i = 0

    for (; i < offset; i++) {
      size += resultLength[i]
    }

    const res = Buffer.allocUnsafe(size)
    let index = 0
    let length = 0

    // Write the content into the result buffer
    for (i = 0; i < offset; i++) {
      length = resultLength[i]

      switch (resultMethod[i]) {
        case 0:
          result[i].copy(res, index)
          break
        case 1:
          res.writeUInt8(result[i], index, true)
          break
        case 2:
          res.writeUInt16BE(result[i], index, true)
          break
        case 3:
          res.writeUInt32BE(result[i], index, true)
          break
        case 4:
          res.writeDoubleBE(result[i], index, true)
          break
        case 5:
          res.write(result[i], index, length, 'utf8')
          break
        default:
          throw new Error('unkown method')
      }

      index += length
    }

    const tmp = res

    this._reset()

    return tmp
  }

  _reset () {
    this.result = []
    this.resultMethod = []
    this.resultLength = []
    this.offset = 0
  }

  /**
   * Encode the given value
   *
   * @param {*} o
   * @returns {Buffer}
   */
  static encode (o) {
    const enc = new Encoder()
    const ret = enc.pushAny(o)
    if (!ret) {
      throw new Error('Failed to encode input')
    }

    return enc.finalize()
  }
}

module.exports = Encoder


text:
class InvitationMailer < ActionMailer::Base
  default from: "noreply@ponglords.com"

  def invite_player(invitation)
    @invitation = invitation
    mail(to: @invitation.email, subject: "You've been invited to join Pong Lords")
  end
end


text:
/* Write a program that reads from the console a positive integer number n (1 ≤ n ≤ 20) and prints a matrix like in the examples below. Use two nested loops. */

using System;

class Program
{
    static void Main(string[] args)
    {
        int n;
        do
        {
            Console.Write("Enter N: ");
            n = int.Parse(Console.ReadLine());
        } while (n < 1 || n > 20);
        int num = 0;
        for (int column = 0; column < n; column++)
        {
            for (int row = 1; row <= n; row++)
            {
                Console.Write("{0} ",(row+num));
            }
            num++;
            Console.WriteLine();
        }
    }
}


text:
package nomad

import (
	"context"
	"errors"
	"fmt"
	"net"
	"time"

	"github.com/armon/go-metrics"
	memdb "github.com/hashicorp/go-memdb"
	"github.com/hashicorp/nomad/nomad/structs"
	"github.com/hashicorp/raft"
	"github.com/hashicorp/serf/serf"
)

const (
	// failedEvalUnblockInterval is the interval at which failed evaluations are
	// unblocked to re-enter the scheduler. A failed evaluation occurs under
	// high contention when the schedulers plan does not make progress.
	failedEvalUnblockInterval = 1 * time.Minute
)

// monitorLeadership is used to monitor if we acquire or lose our role
// as the leader in the Raft cluster. There is some work the leader is
// expected to do, so we must react to changes
func (s *Server) monitorLeadership() {
	var stopCh chan struct{}
	for {
		select {
		case isLeader := <-s.leaderCh:
			if isLeader {
				stopCh = make(chan struct{})
				go s.leaderLoop(stopCh)
				s.logger.Printf("[INFO] nomad: cluster leadership acquired")
			} else if stopCh != nil {
				close(stopCh)
				stopCh = nil
				s.logger.Printf("[INFO] nomad: cluster leadership lost")
			}
		case <-s.shutdownCh:
			return
		}
	}
}

// leaderLoop runs as long as we are the leader to run various
// maintence activities
func (s *Server) leaderLoop(stopCh chan struct{}) {
	// Ensure we revoke leadership on stepdown
	defer s.revokeLeadership()

	var reconcileCh chan serf.Member
	establishedLeader := false

RECONCILE:
	// Setup a reconciliation timer
	reconcileCh = nil
	interval := time.After(s.config.ReconcileInterval)

	// Apply a raft barrier to ensure our FSM is caught up
	start := time.Now()
	barrier := s.raft.Barrier(0)
	if err := barrier.Error(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to wait for barrier: %v", err)
		goto WAIT
	}
	metrics.MeasureSince([]string{"nomad", "leader", "barrier"}, start)

	// Check if we need to handle initial leadership actions
	if !establishedLeader {
		if err := s.establishLeadership(stopCh); err != nil {
			s.logger.Printf("[ERR] nomad: failed to establish leadership: %v",
				err)
			goto WAIT
		}
		establishedLeader = true
	}

	// Reconcile any missing data
	if err := s.reconcile(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to reconcile: %v", err)
		goto WAIT
	}

	// Initial reconcile worked, now we can process the channel
	// updates
	reconcileCh = s.reconcileCh

WAIT:
	// Wait until leadership is lost
	for {
		select {
		case <-stopCh:
			return
		case <-s.shutdownCh:
			return
		case <-interval:
			goto RECONCILE
		case member := <-reconcileCh:
			s.reconcileMember(member)
		}
	}
}

// establishLeadership is invoked once we become leader and are able
// to invoke an initial barrier. The barrier is used to ensure any
// previously inflight transactions have been committed and that our
// state is up-to-date.
func (s *Server) establishLeadership(stopCh chan struct{}) error {
	// Disable workers to free half the cores for use in the plan queue and
	// evaluation broker
	if numWorkers := len(s.workers); numWorkers > 1 {
		// Disabling 3/4 of the workers frees CPU for raft and the
		// plan applier which uses 1/2 the cores.
		for i := 0; i < (3 * numWorkers / 4); i++ {
			s.workers[i].SetPause(true)
		}
	}

	// Enable the plan queue, since we are now the leader
	s.planQueue.SetEnabled(true)

	// Start the plan evaluator
	go s.planApply()

	// Enable the eval broker, since we are now the leader
	s.evalBroker.SetEnabled(true)

	// Enable the blocked eval tracker, since we are now the leader
	s.blockedEvals.SetEnabled(true)

	// Restore the eval broker state
	if err := s.restoreEvals(); err != nil {
		return err
	}

	// Activate the vault client
	s.vault.SetActive(true)
	if err := s.restoreRevokingAccessors(); err != nil {
		return err
	}

	// Enable the periodic dispatcher, since we are now the leader.
	s.periodicDispatcher.SetEnabled(true)
	s.periodicDispatcher.Start()

	// Restore the periodic dispatcher state
	if err := s.restorePeriodicDispatcher(); err != nil {
		return err
	}

	// Scheduler periodic jobs
	go s.schedulePeriodic(stopCh)

	// Reap any failed evaluations
	go s.reapFailedEvaluations(stopCh)

	// Reap any duplicate blocked evaluations
	go s.reapDupBlockedEvaluations(stopCh)

	// Periodically unblock failed allocations
	go s.periodicUnblockFailedEvals(stopCh)

	// Setup the heartbeat timers. This is done both when starting up or when
	// a leader fail over happens. Since the timers are maintained by the leader
	// node, effectively this means all the timers are renewed at the time of failover.
	// The TTL contract is that the session will not be expired before the TTL,
	// so expiring it later is allowable.
	//
	// This MUST be done after the initial barrier to ensure the latest Nodes
	// are available to be initialized. Otherwise initialization may use stale
	// data.
	if err := s.initializeHeartbeatTimers(); err != nil {
		s.logger.Printf("[ERR] nomad: heartbeat timer setup failed: %v", err)
		return err
	}

	// COMPAT 0.4 - 0.4.1
	// Reconcile the summaries of the registered jobs. We reconcile summaries
	// only if the server is 0.4.1 since summaries are not present in 0.4 they
	// might be incorrect after upgrading to 0.4.1 the summaries might not be
	// correct
	if err := s.reconcileJobSummaries(); err != nil {
		return fmt.Errorf("unable to reconcile job summaries: %v", err)
	}
	return nil
}

// restoreEvals is used to restore pending evaluations into the eval broker and
// blocked evaluations into the blocked eval tracker. The broker and blocked
// eval tracker is maintained only by the leader, so it must be restored anytime
// a leadership transition takes place.
func (s *Server) restoreEvals() error {
	// Get an iterator over every evaluation
	ws := memdb.NewWatchSet()
	iter, err := s.fsm.State().Evals(ws)
	if err != nil {
		return fmt.Errorf("failed to get evaluations: %v", err)
	}

	for {
		raw := iter.Next()
		if raw == nil {
			break
		}
		eval := raw.(*structs.Evaluation)

		if eval.ShouldEnqueue() {
			s.evalBroker.Enqueue(eval)
		} else if eval.ShouldBlock() {
			s.blockedEvals.Block(eval)
		}
	}
	return nil
}

// restoreRevokingAccessors is used to restore Vault accessors that should be
// revoked.
func (s *Server) restoreRevokingAccessors() error {
	// An accessor should be revoked if its allocation or node is terminal
	ws := memdb.NewWatchSet()
	state := s.fsm.State()
	iter, err := state.VaultAccessors(ws)
	if err != nil {
		return fmt.Errorf("failed to get vault accessors: %v", err)
	}

	var revoke []*structs.VaultAccessor
	for {
		raw := iter.Next()
		if raw == nil {
			break
		}

		va := raw.(*structs.VaultAccessor)

		// Check the allocation
		alloc, err := state.AllocByID(ws, va.AllocID)
		if err != nil {
			return fmt.Errorf("failed to lookup allocation %q: %v", va.AllocID, err)
		}
		if alloc == nil || alloc.Terminated() {
			// No longer running and should be revoked
			revoke = append(revoke, va)
			continue
		}

		// Check the node
		node, err := state.NodeByID(ws, va.NodeID)
		if err != nil {
			return fmt.Errorf("failed to lookup node %q: %v", va.NodeID, err)
		}
		if node == nil || node.TerminalStatus() {
			// Node is terminal so any accessor from it should be revoked
			revoke = append(revoke, va)
			continue
		}
	}

	if len(revoke) != 0 {
		if err := s.vault.RevokeTokens(context.Background(), revoke, true); err != nil {
			return fmt.Errorf("failed to revoke tokens: %v", err)
		}
	}

	return nil
}

// restorePeriodicDispatcher is used to restore all periodic jobs into the
// periodic dispatcher. It also determines if a periodic job should have been
// created during the leadership transition and force runs them. The periodic
// dispatcher is maintained only by the leader, so it must be restored anytime a
// leadership transition takes place.
func (s *Server) restorePeriodicDispatcher() error {
	ws := memdb.NewWatchSet()
	iter, err := s.fsm.State().JobsByPeriodic(ws, true)
	if err != nil {
		return fmt.Errorf("failed to get periodic jobs: %v", err)
	}

	now := time.Now()
	for i := iter.Next(); i != nil; i = iter.Next() {
		job := i.(*structs.Job)
		s.periodicDispatcher.Add(job)

		// If the periodic job has never been launched before, launch will hold
		// the time the periodic job was added. Otherwise it has the last launch
		// time of the periodic job.
		launch, err := s.fsm.State().PeriodicLaunchByID(ws, job.ID)
		if err != nil || launch == nil {
			return fmt.Errorf("failed to get periodic launch time: %v", err)
		}

		// nextLaunch is the next launch that should occur.
		nextLaunch := job.Periodic.Next(launch.Launch)

		// We skip force launching the job if  there should be no next launch
		// (the zero case) or if the next launch time is in the future. If it is
		// in the future, it will be handled by the periodic dispatcher.
		if nextLaunch.IsZero() || !nextLaunch.Before(now) {
			continue
		}

		if _, err := s.periodicDispatcher.ForceRun(job.ID); err != nil {
			msg := fmt.Sprintf("force run of periodic job %q failed: %v", job.ID, err)
			s.logger.Printf("[ERR] nomad.periodic: %s", msg)
			return errors.New(msg)
		}
		s.logger.Printf("[DEBUG] nomad.periodic: periodic job %q force"+
			" run during leadership establishment", job.ID)
	}

	return nil
}

// schedulePeriodic is used to do periodic job dispatch while we are leader
func (s *Server) schedulePeriodic(stopCh chan struct{}) {
	evalGC := time.NewTicker(s.config.EvalGCInterval)
	defer evalGC.Stop()
	nodeGC := time.NewTicker(s.config.NodeGCInterval)
	defer nodeGC.Stop()
	jobGC := time.NewTicker(s.config.JobGCInterval)
	defer jobGC.Stop()

	// getLatest grabs the latest index from the state store. It returns true if
	// the index was retrieved successfully.
	getLatest := func() (uint64, bool) {
		snapshotIndex, err := s.fsm.State().LatestIndex()
		if err != nil {
			s.logger.Printf("[ERR] nomad: failed to determine state store's index: %v", err)
			return 0, false
		}

		return snapshotIndex, true
	}

	for {

		select {
		case <-evalGC.C:
			if index, ok := getLatest(); ok {
				s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobEvalGC, index))
			}
		case <-nodeGC.C:
			if index, ok := getLatest(); ok {
				s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobNodeGC, index))
			}
		case <-jobGC.C:
			if index, ok := getLatest(); ok {
				s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobJobGC, index))
			}
		case <-stopCh:
			return
		}
	}
}

// coreJobEval returns an evaluation for a core job
func (s *Server) coreJobEval(job string, modifyIndex uint64) *structs.Evaluation {
	return &structs.Evaluation{
		ID:          structs.GenerateUUID(),
		Priority:    structs.CoreJobPriority,
		Type:        structs.JobTypeCore,
		TriggeredBy: structs.EvalTriggerScheduled,
		JobID:       job,
		Status:      structs.EvalStatusPending,
		ModifyIndex: modifyIndex,
	}
}

// reapFailedEvaluations is used to reap evaluations that
// have reached their delivery limit and should be failed
func (s *Server) reapFailedEvaluations(stopCh chan struct{}) {
	for {
		select {
		case <-stopCh:
			return
		default:
			// Scan for a failed evaluation
			eval, token, err := s.evalBroker.Dequeue([]string{failedQueue}, time.Second)
			if err != nil {
				return
			}
			if eval == nil {
				continue
			}

			// Update the status to failed
			newEval := eval.Copy()
			newEval.Status = structs.EvalStatusFailed
			newEval.StatusDescription = fmt.Sprintf("evaluation reached delivery limit (%d)", s.config.EvalDeliveryLimit)
			s.logger.Printf("[WARN] nomad: eval %#v reached delivery limit, marking as failed", newEval)

			// Update via Raft
			req := structs.EvalUpdateRequest{
				Evals: []*structs.Evaluation{newEval},
			}
			if _, _, err := s.raftApply(structs.EvalUpdateRequestType, &req); err != nil {
				s.logger.Printf("[ERR] nomad: failed to update failed eval %#v: %v", newEval, err)
				continue
			}

			// Ack completion
			s.evalBroker.Ack(eval.ID, token)
		}
	}
}

// reapDupBlockedEvaluations is used to reap duplicate blocked evaluations and
// should be cancelled.
func (s *Server) reapDupBlockedEvaluations(stopCh chan struct{}) {
	for {
		select {
		case <-stopCh:
			return
		default:
			// Scan for duplicate blocked evals.
			dups := s.blockedEvals.GetDuplicates(time.Second)
			if dups == nil {
				continue
			}

			cancel := make([]*structs.Evaluation, len(dups))
			for i, dup := range dups {
				// Update the status to cancelled
				newEval := dup.Copy()
				newEval.Status = structs.EvalStatusCancelled
				newEval.StatusDescription = fmt.Sprintf("existing blocked evaluation exists for job %q", newEval.JobID)
				cancel[i] = newEval
			}

			// Update via Raft
			req := structs.EvalUpdateRequest{
				Evals: cancel,
			}
			if _, _, err := s.raftApply(structs.EvalUpdateRequestType, &req); err != nil {
				s.logger.Printf("[ERR] nomad: failed to update duplicate evals %#v: %v", cancel, err)
				continue
			}
		}
	}
}

// periodicUnblockFailedEvals periodically unblocks failed, blocked evaluations.
func (s *Server) periodicUnblockFailedEvals(stopCh chan struct{}) {
	ticker := time.NewTicker(failedEvalUnblockInterval)
	defer ticker.Stop()
	for {
		select {
		case <-stopCh:
			return
		case <-ticker.C:
			// Unblock the failed allocations
			s.blockedEvals.UnblockFailed()
		}
	}
}

// revokeLeadership is invoked once we step down as leader.
// This is used to cleanup any state that may be specific to a leader.
func (s *Server) revokeLeadership() error {
	// Disable the plan queue, since we are no longer leader
	s.planQueue.SetEnabled(false)

	// Disable the eval broker, since it is only useful as a leader
	s.evalBroker.SetEnabled(false)

	// Disable the blocked eval tracker, since it is only useful as a leader
	s.blockedEvals.SetEnabled(false)

	// Disable the periodic dispatcher, since it is only useful as a leader
	s.periodicDispatcher.SetEnabled(false)

	// Disable the Vault client as it is only useful as a leader.
	s.vault.SetActive(false)

	// Clear the heartbeat timers on either shutdown or step down,
	// since we are no longer responsible for TTL expirations.
	if err := s.clearAllHeartbeatTimers(); err != nil {
		s.logger.Printf("[ERR] nomad: clearing heartbeat timers failed: %v", err)
		return err
	}

	// Unpause our worker if we paused previously
	if len(s.workers) > 1 {
		for i := 0; i < len(s.workers)/2; i++ {
			s.workers[i].SetPause(false)
		}
	}
	return nil
}

// reconcile is used to reconcile the differences between Serf
// membership and what is reflected in our strongly consistent store.
func (s *Server) reconcile() error {
	defer metrics.MeasureSince([]string{"nomad", "leader", "reconcile"}, time.Now())
	members := s.serf.Members()
	for _, member := range members {
		if err := s.reconcileMember(member); err != nil {
			return err
		}
	}
	return nil
}

// reconcileMember is used to do an async reconcile of a single serf member
func (s *Server) reconcileMember(member serf.Member) error {
	// Check if this is a member we should handle
	valid, parts := isNomadServer(member)
	if !valid || parts.Region != s.config.Region {
		return nil
	}
	defer metrics.MeasureSince([]string{"nomad", "leader", "reconcileMember"}, time.Now())

	// Do not reconcile ourself
	if member.Name == fmt.Sprintf("%s.%s", s.config.NodeName, s.config.Region) {
		return nil
	}

	var err error
	switch member.Status {
	case serf.StatusAlive:
		err = s.addRaftPeer(member, parts)
	case serf.StatusLeft, StatusReap:
		err = s.removeRaftPeer(member, parts)
	}
	if err != nil {
		s.logger.Printf("[ERR] nomad: failed to reconcile member: %v: %v",
			member, err)
		return err
	}
	return nil
}

// reconcileJobSummaries reconciles the summaries of all the jobs registered in
// the system
// COMPAT 0.4 -> 0.4.1
func (s *Server) reconcileJobSummaries() error {
	index, err := s.fsm.state.LatestIndex()
	if err != nil {
		return fmt.Errorf("unable to read latest index: %v", err)
	}
	s.logger.Printf("[DEBUG] leader: reconciling job summaries at index: %v", index)

	args := &structs.GenericResponse{}
	msg := structs.ReconcileJobSummariesRequestType | structs.IgnoreUnknownTypeFlag
	if _, _, err = s.raftApply(msg, args); err != nil {
		return fmt.Errorf("reconciliation of job summaries failed: %v", err)
	}

	return nil
}

// addRaftPeer is used to add a new Raft peer when a Nomad server joins
func (s *Server) addRaftPeer(m serf.Member, parts *serverParts) error {
	// Do not join ourselfs
	if m.Name == s.config.NodeName {
		s.logger.Printf("[DEBUG] nomad: adding self (%q) as raft peer skipped", m.Name)
		return nil
	}

	// Check for possibility of multiple bootstrap nodes
	if parts.Bootstrap {
		members := s.serf.Members()
		for _, member := range members {
			valid, p := isNomadServer(member)
			if valid && member.Name != m.Name && p.Bootstrap {
				s.logger.Printf("[ERR] nomad: '%v' and '%v' are both in bootstrap mode. Only one node should be in bootstrap mode, not adding Raft peer.", m.Name, member.Name)
				return nil
			}
		}
	}

	// TODO (alexdadgar) - This will need to be changed once we support node IDs.
	addr := (&net.TCPAddr{IP: m.Addr, Port: parts.Port}).String()

	// See if it's already in the configuration. It's harmless to re-add it
	// but we want to avoid doing that if possible to prevent useless Raft
	// log entries.
	configFuture := s.raft.GetConfiguration()
	if err := configFuture.Error(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to get raft configuration: %v", err)
		return err
	}
	for _, server := range configFuture.Configuration().Servers {
		if server.Address == raft.ServerAddress(addr) {
			return nil
		}
	}

	// Attempt to add as a peer
	addFuture := s.raft.AddPeer(raft.ServerAddress(addr))
	if err := addFuture.Error(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to add raft peer: %v", err)
		return err
	} else if err == nil {
		s.logger.Printf("[INFO] nomad: added raft peer: %v", parts)
	}
	return nil
}

// removeRaftPeer is used to remove a Raft peer when a Nomad server leaves
// or is reaped
func (s *Server) removeRaftPeer(m serf.Member, parts *serverParts) error {
	// TODO (alexdadgar) - This will need to be changed once we support node IDs.
	addr := (&net.TCPAddr{IP: m.Addr, Port: parts.Port}).String()

	// See if it's already in the configuration. It's harmless to re-remove it
	// but we want to avoid doing that if possible to prevent useless Raft
	// log entries.
	configFuture := s.raft.GetConfiguration()
	if err := configFuture.Error(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to get raft configuration: %v", err)
		return err
	}
	for _, server := range configFuture.Configuration().Servers {
		if server.Address == raft.ServerAddress(addr) {
			goto REMOVE
		}
	}
	return nil

REMOVE:
	// Attempt to remove as a peer.
	future := s.raft.RemovePeer(raft.ServerAddress(addr))
	if err := future.Error(); err != nil {
		s.logger.Printf("[ERR] nomad: failed to remove raft peer '%v': %v",
			parts, err)
		return err
	}
	return nil
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="41dp"
        android:layout_marginTop="71dp"
        android:text="Enter a Number" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="21dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Check" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignLeft="@+id/button1"
        android:layout_marginLeft="43dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="90dp"
        android:layout_toLeftOf="@+id/editText1"
        android:text="TextView" />

</RelativeLayout>


text:
module ModelFromTable
end


text:
/*
 * CBR.java
 *
 * Created on August 28, 2004, 6:56 PM
 */

package org.dhs.chrislee.manetbuilder.application;
import java.awt.*;
import java.awt.geom.*;
/**
 *
 * @author  chris
 */
public class CBR extends Application {
    public double starttime = 0;
    public double endtime = 600;
    public double packetInterval = 1.0;
    public int packetSize = 500;
    public int packetCount = 600;
    public double throughput = 300000;
    org.dhs.chrislee.manetbuilder.Node targetnode;

    /** Creates a new instance of CBR */
    public CBR() {
    }

    public void draw(java.awt.Graphics2D g, org.dhs.chrislee.manetbuilder.Node node, java.util.ArrayList nodes, java.awt.Color color, double zoom, double time) {
        g.setColor( color );
        float[] dashpattern = { 3, 3 };
        Stroke stroke = g.getStroke();
        g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, dashpattern, 0 ));
        Point2D.Double p1 = node.getCurrentLocation( time );
        Point2D.Double p2 = targetnode.getCurrentLocation( time );
        g.draw( new Line2D.Double( p1.getX()/zoom, p1.getY()/zoom, p2.getX()/zoom, p2.getY()/zoom ) );
        g.drawString( this.getName(), (float)((p1.getX()+p2.getX())/(2*zoom)), (float)((p1.getY()+p2.getY())/(2*zoom)) );
        g.setStroke( stroke );
    }

    public String getName() {
        return ( "CBR" );
    }

    public boolean isConfigurable() {
        return true;
    }

    public void showConfigurationDialog(java.awt.Frame frame, org.dhs.chrislee.manetbuilder.Node node, java.util.ArrayList nodes) {
        CBRDialog cbrd = new CBRDialog( frame, true, node, nodes );
        cbrd.setVisible( true );
        if ( cbrd.returncode == CBRDialog.OK ) {
            targetnode = (org.dhs.chrislee.manetbuilder.Node)nodes.get( cbrd.targetnodeid );
            starttime = cbrd.starttime;
            endtime = cbrd.endtime;
            packetCount = cbrd.packetCount;
            packetSize = cbrd.packetSize;
            packetInterval = cbrd.packetInterval;
            System.out.println("CBRDialog props: "+targetnode.nodeId );
        }
    }

    public boolean isPlottable() {
        return ( true );
    }

}


text:
namespace chromeos::settings {

namespace {
class TestPrivacyHubHandler : public PrivacyHubHandler {
 public:
  using content::WebUIMessageHandler::set_web_ui;

  using PrivacyHubHandler::HandleInitialAvailabilityOfMicrophoneForSimpleUsage;
  using PrivacyHubHandler::HandleInitialCameraSwitchState;
  using PrivacyHubHandler::HandleInitialMicrophoneSwitchState;
};

using cps = cros::mojom::CameraPrivacySwitchState;
}  // namespace

class PrivacyHubHandlerTest : public testing::Test {
  // This has to go before privacy_hub_handler_ because in the
  // CameraHalDispatcherImpl constructor a call to
  // base::SequencedTaskRunnerHandle::Get() is made which requires a
  // task_environment. Initialization order of the members takes care
  // of providing this before privacy_hub_handler_ is constructed.
  base::test::SingleThreadTaskEnvironment task_environment_;

  // This has to go before privacy_hub_handler_ because PrivacyHubHandler
  // constructor  requires CrasAudioHandler to be initialized.
  // ScopedCrasAudioHandlerForTesting is a helper class that initializes
  // CrasAudioHandler in it's constructor.
  ash::ScopedCrasAudioHandlerForTesting cras_audio_handler_;

  // Has to go before privacy_hub_handler_ as it references its
  // address and destruction order guarantees no invalid pointers.
  content::TestWebUI web_ui_;

 public:
  PrivacyHubHandlerTest()
      : this_test_name_(
            testing::UnitTest::GetInstance()->current_test_info()->name()) {
    privacy_hub_handler_.set_web_ui(&web_ui_);
    privacy_hub_handler_.AllowJavascriptForTesting();
  }

  [[nodiscard]] base::Value GetLastWebUIListenerData(
      const std::string& callback) const {
    return GetLastWebUIData("cr.webUIListenerCallback", callback);
  }

  [[nodiscard]] base::Value GetLastWebUIResponse(
      const std::string& callback) const {
    return GetLastWebUIData("cr.webUIResponse", callback);
  }

  TestPrivacyHubHandler privacy_hub_handler_;
  const std::string this_test_name_;

 protected:
  void ExpectValueMatchesBoolParam(bool param, const base::Value& value) const {
    ASSERT_TRUE(value.is_bool());
    EXPECT_EQ(param, value.GetBool());
  }

 private:
  [[nodiscard]] base::Value GetLastWebUIData(
      const std::string& function_name,
      const std::string& callback_name) const {
    for (const auto& data : base::Reversed(web_ui_.call_data())) {
      const std::string* name = data->arg1()->GetIfString();

      if (data->function_name() != function_name || !name ||
          *name != callback_name) {
        continue;
      }

      // Assume that the data is stored in the last valid arg.
      for (const auto& arg : base::Reversed(data->args())) {
        if (&arg != data->arg1())
          return arg.Clone();
      }
    }

    ADD_FAILURE() << "None of the " << web_ui_.call_data().size()
                  << " CallData objects matched for function '" << function_name
                  << "' and callback '" << callback_name
                  << "' with a valid arg";
    return base::Value();
  }
};

class PrivacyHubHandlerMicrophoneTest
    : public PrivacyHubHandlerTest,
      public testing::WithParamInterface<bool> {
 public:
  void SetParamValueMicrophoneMute() const {
    // Have to set it to not-param once before to ensure the observers are
    // triggered from MicrophoneMuteSwitchMonitor.
    ui::MicrophoneMuteSwitchMonitor::Get()->SetMicrophoneMuteSwitchValue(
        !GetParam());
    ui::MicrophoneMuteSwitchMonitor::Get()->SetMicrophoneMuteSwitchValue(
        GetParam());
  }

  void ExpectValueMatchesBoolParam(const base::Value& value) const {
    PrivacyHubHandlerTest::ExpectValueMatchesBoolParam(GetParam(), value);
  }
};

class PrivacyHubHandlerCameraTest : public PrivacyHubHandlerTest,
                                    public testing::WithParamInterface<cps> {
 public:
  void ExpectValueMatchesEnumParam(const base::Value& value) const {
    if (GetParam() == cps::UNKNOWN) {
      EXPECT_TRUE(value.is_none());
    } else {
      ExpectValueMatchesBoolParam(GetParam() == cps::ON, value);
    }
  }
};

TEST_P(PrivacyHubHandlerCameraTest, CameraHardwareToggleChanged) {
  privacy_hub_handler_.CameraHardwareToggleChanged(GetParam());

  const base::Value data =
      GetLastWebUIListenerData("camera-hardware-toggle-changed");

  ExpectValueMatchesEnumParam(data);
}

INSTANTIATE_TEST_SUITE_P(HardwareSwitchStates,
                         PrivacyHubHandlerCameraTest,
                         testing::Values(cps::ON, cps::OFF, cps::UNKNOWN),
                         testing::PrintToStringParamName());

TEST_F(PrivacyHubHandlerCameraTest, HandleInitialCameraSwitchState) {
  base::Value::List args;
  args.Append(this_test_name_);

  privacy_hub_handler_.HandleInitialCameraSwitchState(args);

  const base::Value data = GetLastWebUIResponse(this_test_name_);

  // The initial state is always UNKNOWN which is communicated as NONE
  EXPECT_TRUE(data.is_none());
}

TEST_P(PrivacyHubHandlerMicrophoneTest,
       MicrophoneHardwarePrivacySwitchChanged) {
  privacy_hub_handler_.MicrophoneHardwareToggleChanged(GetParam());

  const base::Value data =
      GetLastWebUIListenerData("microphone-hardware-toggle-changed");

  ExpectValueMatchesBoolParam(data);
}

TEST_P(PrivacyHubHandlerMicrophoneTest, HandleInitialMicrophoneSwitchState) {
  SetParamValueMicrophoneMute();

  base::Value::List args;
  args.Append(this_test_name_);

  privacy_hub_handler_.HandleInitialMicrophoneSwitchState(args);

  const base::Value data = GetLastWebUIResponse(this_test_name_);

  ExpectValueMatchesBoolParam(data);
}

TEST_F(PrivacyHubHandlerMicrophoneTest,
       HandleInitialAvailabilityOfSimpleMicrophone) {
  base::Value::List args;
  args.Append(this_test_name_);

  privacy_hub_handler_.HandleInitialAvailabilityOfMicrophoneForSimpleUsage(
      args);

  const base::Value data = GetLastWebUIResponse(this_test_name_);
  EXPECT_FALSE(data.is_none());
}

TEST_P(PrivacyHubHandlerMicrophoneTest, AvailabilityOfMicrophoneChanged) {
  privacy_hub_handler_.AvailabilityOfMicrophoneChanged(GetParam());

  const base::Value data = GetLastWebUIListenerData(
      "availability-of-microphone-for-simple-usage-changed");

  ExpectValueMatchesBoolParam(data);
}

INSTANTIATE_TEST_SUITE_P(HardwareSwitchStates,
                         PrivacyHubHandlerMicrophoneTest,
                         testing::Values(true, false),
                         testing::PrintToStringParamName());

#if DCHECK_IS_ON()
using PrivacyHubHandlerDeathTest = PrivacyHubHandlerTest;

TEST_F(PrivacyHubHandlerDeathTest, HandleInitialCameraSwitchStateNoCallbackId) {
  base::Value::List args;

  EXPECT_DEATH(privacy_hub_handler_.HandleInitialCameraSwitchState(args),
               ".*Callback ID is required.*");
}

TEST_F(PrivacyHubHandlerDeathTest, HandleInitialCameraSwitchStateWithArgs) {
  base::Value::List args;
  args.Append(this_test_name_);
  args.Append(base::Value());

  EXPECT_DEATH(privacy_hub_handler_.HandleInitialCameraSwitchState(args),
               ".*Did not expect arguments.*");
}

TEST_F(PrivacyHubHandlerDeathTest,
       HandleInitialMicrophoneSwitchStateNoCallbackId) {
  base::Value::List args;

  EXPECT_DEATH(privacy_hub_handler_.HandleInitialMicrophoneSwitchState(args),
               ".*Callback ID is required.*");
}

TEST_F(PrivacyHubHandlerDeathTest, HandleInitialMicrophoneSwitchStateWithArgs) {
  base::Value::List args;
  args.Append(this_test_name_);
  args.Append(base::Value());

  EXPECT_DEATH(privacy_hub_handler_.HandleInitialMicrophoneSwitchState(args),
               ".*Did not expect arguments.*");
}

TEST_F(PrivacyHubHandlerDeathTest,
       HandleInitialAvailabilityOfMicrophoneForSimpleUsageNoCallbackId) {
  base::Value::List args;

  EXPECT_DEATH(
      privacy_hub_handler_.HandleInitialAvailabilityOfMicrophoneForSimpleUsage(
          args),
      ".*Callback ID is required.*");
}

TEST_F(PrivacyHubHandlerDeathTest,
       HandleInitialAvailabilityOfMicrophoneForSimpleUsageWithArgs) {
  base::Value::List args;
  args.Append(this_test_name_);
  args.Append(base::Value());

  EXPECT_DEATH(
      privacy_hub_handler_.HandleInitialAvailabilityOfMicrophoneForSimpleUsage(
          args),
      ".*Did not expect arguments.*");
}
#endif
}  // namespace chromeos::settings


text:
package com.tys.gobmx.beans;

import com.tys.gobmx.AXFrameList.ItemList;

public class Theme extends ItemList{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private int logo;
	private String descripcion;

	public Theme(int id, String displayName,  int logo, String descripcion) {
		super(id, displayName, false);
		this.logo = logo;
		this.descripcion = descripcion;
	}
	public int getLogo() {
		return logo;
	}
	public void setLogo(int logo) {
		this.logo = logo;
	}
	public String getDescripcion() {
		return descripcion;
	}
	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion;
	}

}


text:
package org.drools.workbench.screens.guided.dtable.client.wizard.column.pages.modals;

public interface HasList {

    void addItem(final String itemName,
                 final String itemKey);
}


text:
<!DOCTYPE html>

    <title>A basic Pie chart with dollar syntax example</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A basic example of an RGraph Pie chart that makes use of the dollar syntax to add an event listener to a single point." />
    <meta name="googlebot" content="NOODP">

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

A basic Pie chart with dollar syntax example

    <canvas id="cvs" width="350" height="250">[No canvas support]</canvas>

    This goes in the documents header (or you could place it just above the jQuery ready event code):

<script src="/mps/libs/jquery-1.11.3/jquery-1.11.3.js"></script>
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.pie.js"></script>

    Put this where you want the chart to show up:

<canvas id="cvs" width="600" height="250">
    [No canvas support]
</canvas>

    This is the code that generates the chart. Because it's using the jQuery ready event you can put this at the
    bottom of the document:

<script>
    $(document).ready(function ()
    {
        var pie = new RGraph.Pie({
            id: 'cvs',
            data: [4,8,3,4,6,9,5],
            options: {
                labels: ['Pete','Lou','Pob','Luis','Barney','Fred','Wilma']
            }
        }).draw()

        pie.$2.onclick = function (e, shape)
        {
            alert('The third segment has been clicked');
        }

        pie.$2.onmousemove = function (e, shape)
        {
            e.target.style.cursor = 'pointer';
        }
    });
</script>


text:
using appcache::AppCacheService;
using fileapi::FileSystemContext;
using webkit_blob::BlobStorageController;

namespace content {

namespace {

class BlobProtocolHandler : public webkit_blob::BlobProtocolHandler {
 public:
  BlobProtocolHandler(
      webkit_blob::BlobStorageController* blob_storage_controller,
      fileapi::FileSystemContext* file_system_context,
      base::MessageLoopProxy* loop_proxy)
      : webkit_blob::BlobProtocolHandler(blob_storage_controller,
                                         file_system_context,
                                         loop_proxy) {}

  virtual ~BlobProtocolHandler() {}

 private:
  virtual scoped_refptr<webkit_blob::BlobData>
      LookupBlobData(net::URLRequest* request) const {
    const ResourceRequestInfoImpl* info =
        ResourceRequestInfoImpl::ForRequest(request);
    if (!info)
      return NULL;
    return info->requested_blob_data();
  }

  DISALLOW_COPY_AND_ASSIGN(BlobProtocolHandler);
};

// Adds a bunch of debugging urls. We use an interceptor instead of a protocol
// handler because we want to reuse the chrome://scheme (everyone is familiar
// with it, and no need to expose the content/chrome separation through our UI).
class DeveloperProtocolHandler
    : public net::URLRequestJobFactory::Interceptor {
 public:
  DeveloperProtocolHandler(
      AppCacheService* appcache_service,
      BlobStorageController* blob_storage_controller)
      : appcache_service_(appcache_service),
        blob_storage_controller_(blob_storage_controller) {}
  virtual ~DeveloperProtocolHandler() {}

  virtual net::URLRequestJob* MaybeIntercept(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const OVERRIDE {
    // Check for chrome://view-http-cache/*, which uses its own job type.
    if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
      return ViewHttpCacheJobFactory::CreateJobForRequest(request,
                                                          network_delegate);

    // Next check for chrome://appcache-internals/, which uses its own job type.
    if (request->url().SchemeIs(chrome::kChromeUIScheme) &&
        request->url().host() == chrome::kChromeUIAppCacheInternalsHost) {
      return appcache::ViewAppCacheInternalsJobFactory::CreateJobForRequest(
          request, network_delegate, appcache_service_);
    }

    // Next check for chrome://blob-internals/, which uses its own job type.
    if (ViewBlobInternalsJobFactory::IsSupportedURL(request->url())) {
      return ViewBlobInternalsJobFactory::CreateJobForRequest(
          request, network_delegate, blob_storage_controller_);
    }

#if defined(USE_TCMALLOC)
    // Next check for chrome://tcmalloc/, which uses its own job type.
    if (request->url().SchemeIs(chrome::kChromeUIScheme) &&
        request->url().host() == chrome::kChromeUITcmallocHost) {
      return new TcmallocInternalsRequestJob(request, network_delegate);
    }
#endif

    // Next check for chrome://histograms/, which uses its own job type.
    if (request->url().SchemeIs(chrome::kChromeUIScheme) &&
        request->url().host() == chrome::kChromeUIHistogramHost) {
      return new HistogramInternalsRequestJob(request, network_delegate);
    }

    return NULL;
  }

  virtual net::URLRequestJob* MaybeInterceptRedirect(
        const GURL& location,
        net::URLRequest* request,
        net::NetworkDelegate* network_delegate) const OVERRIDE {
    return NULL;
  }

  virtual net::URLRequestJob* MaybeInterceptResponse(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const OVERRIDE {
    return NULL;
  }

  virtual bool WillHandleProtocol(const std::string& protocol) const {
    return protocol == chrome::kChromeUIScheme;
  }

 private:
  AppCacheService* appcache_service_;
  BlobStorageController* blob_storage_controller_;
};

void InitializeURLRequestContext(
    net::URLRequestContextGetter* context_getter,
    AppCacheService* appcache_service,
    FileSystemContext* file_system_context,
    ChromeBlobStorageContext* blob_storage_context) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (!context_getter)
    return;  // tests.

  // This code only modifies the URLRequestJobFactory on the context
  // to handle blob: URLs, filesystem: URLs, and to let AppCache intercept
  // the appropriate requests.  This is in addition to the slew of other
  // initializtion that is done in during creation of the URLRequestContext.
  // We cannot yet centralize this code because URLRequestContext needs
  // to be created before the StoragePartition context.
  //
  // TODO(ajwong): Fix the ordering so all the initialization is in one spot.
  net::URLRequestContext* context = context_getter->GetURLRequestContext();
  net::URLRequestJobFactory* job_factory =
      const_cast<net::URLRequestJobFactory*>(context->job_factory());

  // Note: if this is called twice with 2 request contexts that share one job
  // factory (as is the case with a media request context and its related
  // normal request context) then this will early exit.
  if (job_factory->IsHandledProtocol(chrome::kBlobScheme))
    return;  // Already initialized this JobFactory.

  bool set_protocol = job_factory->SetProtocolHandler(
      chrome::kBlobScheme,
      new BlobProtocolHandler(
          blob_storage_context->controller(),
          file_system_context,
          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)));
  DCHECK(set_protocol);
  set_protocol = job_factory->SetProtocolHandler(
      chrome::kFileSystemScheme,
      CreateFileSystemProtocolHandler(file_system_context));
  DCHECK(set_protocol);

  job_factory->AddInterceptor(
      new DeveloperProtocolHandler(appcache_service,
                                   blob_storage_context->controller()));

  // TODO(jam): Add the ProtocolHandlerRegistryIntercepter here!
}

// These constants are used to create the directory structure under the profile
// where renderers with a non-default storage partition keep their persistent
// state. This will contain a set of directories that partially mirror the
// directory structure of BrowserContext::GetPath().
//
// The kStoragePartitionDirname contains an extensions directory which is
// further partitioned by extension id, followed by another level of directories
// for the "default" extension storage partition and one directory for each
// persistent partition used by a webview tag. Example:
//
//   Storage/ext/ABCDEF/def
//   Storage/ext/ABCDEF/hash(partition name)
//
// The code in GetStoragePartitionPath() constructs these path names.
//
// TODO(nasko): Move extension related path code out of content.
const FilePath::CharType kStoragePartitionDirname[] =
    FILE_PATH_LITERAL("Storage");
const FilePath::CharType kExtensionsDirname[] =
    FILE_PATH_LITERAL("ext");
const FilePath::CharType kDefaultPartitionDirname[] =
    FILE_PATH_LITERAL("def");

// Because partition names are user specified, they can be arbitrarily long
// which makes them unsuitable for paths names. We use a truncation of a
// SHA256 hash to perform a deterministic shortening of the string. The
// kPartitionNameHashBytes constant controls the length of the truncation.
// We use 6 bytes, which gives us 99.999% reliability against collisions over
// 1 million partition domains.
//
// Analysis:
// We assume that all partition names within one partition domain are
// controlled by the the same entity. Thus there is no chance for adverserial
// attack and all we care about is accidental collision. To get 5 9s over
// 1 million domains, we need the probability of a collision in any one domain
// to be
//
//    p < nroot(1000000, .99999) ~= 10^-11
//
// We use the following birthday attack approximation to calculate the max
// number of unique names for this probability:
//
//    n(p,H) = sqrt(2*H * ln(1/(1-p)))
//
// For a 6-byte hash, H = 2^(6*8).  n(10^-11, H) ~= 75
//
// An average partition domain is likely to have less than 10 unique
// partition names which is far lower than 75.
//
// Note, that for 4 9s of reliability, the limit is 237 partition names per
// partition domain.
const int kPartitionNameHashBytes = 6;

// Needed for selecting all files in ObliterateOneDirectory() below.
#if defined(OS_POSIX)
const int kAllFileTypes = file_util::FileEnumerator::FILES |
                          file_util::FileEnumerator::DIRECTORIES |
                          file_util::FileEnumerator::SHOW_SYM_LINKS;
#else
const int kAllFileTypes = file_util::FileEnumerator::FILES |
                          file_util::FileEnumerator::DIRECTORIES;
#endif

FilePath GetStoragePartitionDomainPath(
    const std::string& partition_domain) {
  CHECK(IsStringUTF8(partition_domain));

  return FilePath(kStoragePartitionDirname).Append(kExtensionsDirname)
      .Append(FilePath::FromUTF8Unsafe(partition_domain));
}

// Helper function for doing a depth-first deletion of the data on disk.
// Examines paths directly in |current_dir| (no recursion) and tries to
// delete from disk anything that is in, or isn't a parent of something in
// |paths_to_keep|. Paths that need further expansion are added to
// |paths_to_consider|.
void ObliterateOneDirectory(const FilePath& current_dir,
                            const std::vector<FilePath>& paths_to_keep,
                            std::vector<FilePath>* paths_to_consider) {
  file_util::FileEnumerator enumerator(current_dir, false, kAllFileTypes);
  for (FilePath to_delete = enumerator.Next(); !to_delete.empty();
       to_delete = enumerator.Next()) {
    // Enum tracking which of the 3 possible actions to take for |to_delete|.
    enum { kSkip, kEnqueue, kDelete } action = kDelete;

    for (std::vector<FilePath>::const_iterator to_keep = paths_to_keep.begin();
         to_keep != paths_to_keep.end();
         ++to_keep) {
      if (to_delete == *to_keep) {
        action = kSkip;
        break;
      } else if (to_delete.IsParent(*to_keep)) {
        // |to_delete| contains a path to keep. Add to stack for further
        // processing.
        action = kEnqueue;
        break;
      }
    }

    switch (action) {
      case kDelete:
        file_util::Delete(to_delete, true);
        break;

      case kEnqueue:
        paths_to_consider->push_back(to_delete);
        break;

      case kSkip:
        break;
    }
  }
}

// Synchronously attempts to delete |root|, preserving only entries in
// |paths_to_keep|. If there are no entries in |paths_to_keep| on disk, then it
// completely removes |root|. All paths must be absolute paths.
void BlockingObliteratePath(const FilePath& root,
                            const std::vector<FilePath>& paths_to_keep) {
  // Reduce |paths_to_keep| set to those under the root and actually on disk.
  std::vector<FilePath> valid_paths_to_keep;
  for (std::vector<FilePath>::const_iterator it = paths_to_keep.begin();
       it != paths_to_keep.end();
       ++it) {
    if (root.IsParent(*it) && file_util::PathExists(*it))
      valid_paths_to_keep.push_back(*it);
  }

  // If none of the |paths_to_keep| are valid anymore then we just whack the
  // root and be done with it.
  if (valid_paths_to_keep.empty()) {
    file_util::Delete(root, true);
    return;
  }

  // Otherwise, start at the root and delete everything that is not in
  // |valid_paths_to_keep|.
  std::vector<FilePath> paths_to_consider;
  paths_to_consider.push_back(root);
  while(!paths_to_consider.empty()) {
    FilePath path = paths_to_consider.back();
    paths_to_consider.pop_back();
    ObliterateOneDirectory(path, valid_paths_to_keep, &paths_to_consider);
  }
}

}  // namespace

// static
FilePath StoragePartitionImplMap::GetStoragePartitionPath(
    const std::string& partition_domain,
    const std::string& partition_name) {
  if (partition_domain.empty())
    return FilePath();

  FilePath path = GetStoragePartitionDomainPath(partition_domain);

  // TODO(ajwong): Mangle in-memory into this somehow, either by putting
  // it into the partition_name, or by manually adding another path component
  // here.  Otherwise, it's possible to have an in-memory StoragePartition and
  // a persistent one that return the same FilePath for GetPath().
  if (!partition_name.empty()) {
    // For analysis of why we can ignore collisions, see the comment above
    // kPartitionNameHashBytes.
    char buffer[kPartitionNameHashBytes];
    crypto::SHA256HashString(partition_name, &buffer[0],
                             sizeof(buffer));
    return path.AppendASCII(base::HexEncode(buffer, sizeof(buffer)));
  }

  return path.Append(kDefaultPartitionDirname);
}

StoragePartitionImplMap::StoragePartitionImplMap(
    BrowserContext* browser_context)
    : browser_context_(browser_context),
      resource_context_initialized_(false) {
}

StoragePartitionImplMap::~StoragePartitionImplMap() {
  STLDeleteContainerPairSecondPointers(partitions_.begin(),
                                       partitions_.end());
}

StoragePartitionImpl* StoragePartitionImplMap::Get(
    const std::string& partition_domain,
    const std::string& partition_name,
    bool in_memory) {
  // TODO(ajwong): ResourceContexts no longer have any storage related state.
  // We should move this into a place where it is called once per
  // BrowserContext creation rather than piggybacking off the default context
  // creation.
  if (!resource_context_initialized_) {
    resource_context_initialized_ = true;
    InitializeResourceContext(browser_context_);
  }

  // Find the previously created partition if it's available.
  StoragePartitionConfig partition_config(
      partition_domain, partition_name, in_memory);

  PartitionMap::const_iterator it = partitions_.find(partition_config);
  if (it != partitions_.end())
    return it->second;

  FilePath partition_path =
      browser_context_->GetPath().Append(
          GetStoragePartitionPath(partition_domain, partition_name));
  StoragePartitionImpl* partition =
      StoragePartitionImpl::Create(browser_context_, in_memory,
                                   partition_path);
  partitions_[partition_config] = partition;

  // These calls must happen after StoragePartitionImpl::Create().
  partition->SetURLRequestContext(
      partition_domain.empty() ?
      browser_context_->GetRequestContext() :
      browser_context_->GetRequestContextForStoragePartition(
          partition->GetPath(), in_memory));
  partition->SetMediaURLRequestContext(
      partition_domain.empty() ?
      browser_context_->GetMediaRequestContext() :
      browser_context_->GetMediaRequestContextForStoragePartition(
          partition->GetPath(), in_memory));

  PostCreateInitialization(partition, in_memory);

  return partition;
}

void StoragePartitionImplMap::AsyncObliterate(const GURL& site) {
  // This method should avoid creating any StoragePartition (which would
  // create more open file handles) so that it can delete as much of the
  // data off disk as possible.
  std::string partition_domain;
  std::string partition_name;
  bool in_memory = false;
  GetContentClient()->browser()->GetStoragePartitionConfigForSite(
      browser_context_, site, false, &partition_domain,
      &partition_name, &in_memory);

  // The default partition is the whole profile. We can't obliterate that and
  // should never even try.
  CHECK(!partition_domain.empty()) << site;

  // Find the active partitions for the domain. Because these partitions are
  // active, it is not possible to just delete the directories that contain
  // the backing data structures without causing the browser to crash. Instead,
  // of deleteing the directory, we tell each storage context later to
  // remove any data they have saved. This will leave the directory structure
  // intact but it will only contain empty databases.
  std::vector<StoragePartitionImpl*> active_partitions;
  std::vector<FilePath> paths_to_keep;
  for (PartitionMap::const_iterator it = partitions_.begin();
       it != partitions_.end();
       ++it) {
    const StoragePartitionConfig& config = it->first;
    if (config.partition_domain == partition_domain) {
      it->second->AsyncClearAllData();
      if (!config.in_memory) {
        paths_to_keep.push_back(it->second->GetPath());
      }
    }
  }

  // Start a best-effort delete of the on-disk storage excluding paths that are
  // known to still be in use. This is to delete any previously created
  // StoragePartition state that just happens to not have been used during this
  // run of the browser.
  FilePath domain_root = browser_context_->GetPath().Append(
      GetStoragePartitionDomainPath(partition_domain));
  base::WorkerPool::PostTask(
      FROM_HERE,
      base::Bind(&BlockingObliteratePath, domain_root, paths_to_keep),
      true);

  // TODO(ajwong): Schedule a final AsyncObliterate of the whole directory on
  // the next browser start. http://crbug.com/85127.
}

void StoragePartitionImplMap::ForEach(
    const BrowserContext::StoragePartitionCallback& callback) {
  for (PartitionMap::const_iterator it = partitions_.begin();
       it != partitions_.end();
       ++it) {
    callback.Run(it->second);
  }
}

void StoragePartitionImplMap::PostCreateInitialization(
    StoragePartitionImpl* partition,
    bool in_memory) {
  // Check first to avoid memory leak in unittests.
  if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ChromeAppCacheService::InitializeOnIOThread,
                   partition->GetAppCacheService(),
                   in_memory ? FilePath() :
                       partition->GetPath().Append(kAppCacheDirname),
                   browser_context_->GetResourceContext(),
                   make_scoped_refptr(partition->GetURLRequestContext()),
                   make_scoped_refptr(
                       browser_context_->GetSpecialStoragePolicy())));

    // Add content's URLRequestContext's hooks.
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(
            &InitializeURLRequestContext,
            make_scoped_refptr(partition->GetURLRequestContext()),
            make_scoped_refptr(partition->GetAppCacheService()),
            make_scoped_refptr(partition->GetFileSystemContext()),
            make_scoped_refptr(
                ChromeBlobStorageContext::GetFor(browser_context_))));

    // We do not call InitializeURLRequestContext() for media contexts because,
    // other than the HTTP cache, the media contexts share the same backing
    // objects as their associated "normal" request context.  Thus, the previous
    // call serves to initialize the media request context for this storage
    // partition as well.
  }
}

}  // namespace content


text:
"""accounts user forms."""

from django import forms
from django.contrib import auth

from accounts.models import CustomUser

class CustomUserCreationForm(auth.forms.UserCreationForm):

    """A form to create users."""

    #https://groups.google.com/forum/?fromgroups=#!topic/django-users/kOVEy9zYn5c
    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            CustomUser._default_manager.get(username=username)
        except CustomUser.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    class Meta(auth.forms.UserCreationForm.Meta):
        model = CustomUser

class CustomUserChangeForm(auth.forms.UserChangeForm):

    """A form to update users."""

    class Meta(auth.forms.UserChangeForm.Meta):
        model = CustomUser


text:
package tests;

import org.junit.Assert;
import org.junit.Test;

import main.*;
import main.Items.*;

public class CriteriosTests {

	//Criterio de aceptación 1.1
	@Test
	public void queAsgardianoTieneStatsBasePropios()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		Assert.assertFalse(pj.getAtaqueBase() == 0);
		Assert.assertFalse(pj.getDanoMagicoBase() == 0);
		Assert.assertFalse(pj.getDefensaBase() == 0);
		Assert.assertFalse(pj.getEnergiaMaximaBase() == 0);
		Assert.assertFalse(pj.getVelocidadBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaPorNivel() == 0);
	}
	@Test
	public void queHulkTieneStatsBasePropios()
	{
		PC pj = new Hulk("pj1", Clase.AGENTE);
		Assert.assertFalse(pj.getAtaqueBase() == 0);
		Assert.assertFalse(pj.getDanoMagicoBase() == 0);
		Assert.assertFalse(pj.getDefensaBase() == 0);
		Assert.assertFalse(pj.getEnergiaMaximaBase() == 0);
		Assert.assertFalse(pj.getVelocidadBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaPorNivel() == 0);
	}
	@Test
	public void queMutanteTieneStatsBasePropios()
	{
		PC pj = new Mutante("pj1", Clase.AGENTE);
		Assert.assertFalse(pj.getAtaqueBase() == 0);
		Assert.assertFalse(pj.getDanoMagicoBase() == 0);
		Assert.assertFalse(pj.getDefensaBase() == 0);
		Assert.assertFalse(pj.getEnergiaMaximaBase() == 0);
		Assert.assertFalse(pj.getVelocidadBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaBase() == 0);
		Assert.assertFalse(pj.getVidaMaximaPorNivel() == 0);

	}
	//Fin criterio aceptación 1.1

	//Crieterio de aceptación 4.1
	@Test
	public void quePuedoGanarExp()
	{
		PC pj = new Hulk("pj1", Clase.AGENTE);
		int expInicial = pj.getExp();
		pj.ganarExp(10);
		Assert.assertTrue(expInicial + 10 == pj.getExp());
	}
	//Fin Criterio 4.1

	//Criterio 4.2

	@Test
	public void queAlGanarExpSuboDeNivel()
	{

		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		int nivelInicial = pj.getNivel();
		pj.ganarExp(60);
		Assert.assertTrue(nivelInicial + 1 == pj.getNivel());
	}

	//Fin criterio 4.2

	//Criterio 5.1
	@Test
	public void queAlTomarUnCascoDeMagnetoSeModificanStats()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		pj.equiparItemCabeza(new CascoDeMagneto());
		Assert.assertTrue(pj.calcularDefensa() != pj.getDefensaBase());

	}
	@Test
	public void queAlTomarUnCascoDeNovaSeModificanStats()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		pj.equiparItemCabeza(new CascoDeNova());
		Assert.assertTrue(pj.calcularDanoMagico() != pj.getDanoMagicoBase());
		Assert.assertTrue(pj.calcularVelocidad() != pj.getVelocidadBase());

	}
	@Test
	public void queAlTomarUnReactorARCSeModificanStats()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		pj.equiparItemPecho(new ReactorARC());
		Assert.assertTrue(pj.calcularEnergiaMax() != pj.getEnergiaMaximaBase());

	}
	@Test
	public void queAlTomarUnSimbionteSeModificanStats()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		pj.equiparItemPecho(new Simbionte());
		Assert.assertTrue(pj.calcularVidaMaxima() != pj.getVidaMaximaBase());

	}

	//Fin criterio 5.1

	//Criterio de aceptación 8.1
	@Test
	public void queAlPerderCombateHulkPierdeMejorItem()
	{
		PC pj = new Hulk("pj1", Clase.AGENTE);
		pj.equiparItemCabeza(new CascoDeMagneto());
		pj.morir();
		Assert.assertTrue(pj.getDefensaBase() == pj.calcularDefensa());
	}
	@Test
	public void queAlPerderCombateAsgardianoPierdeMejorItem()
	{
		PC pj = new Asgardiano("pj1", Clase.AGENTE);
		pj.equiparItemCabeza(new CascoDeMagneto());
		pj.morir();
		Assert.assertTrue(pj.getDefensaBase() == pj.calcularDefensa());
	}
	@Test
	public void queAlPerderCombateMutantePierdeMejorItem()
	{
		PC pj = new Mutante("pj1", Clase.AGENTE);
		pj.equiparItemCabeza(new CascoDeMagneto());
		pj.morir();
		Assert.assertTrue(pj.getDefensaBase() == pj.calcularDefensa());
	}

	//Fin criterio de aceptación 8.1

}