text:
:- module(authenticate,
          [ http_authenticate/3,        % +Check, +Header, -User
            http_authorization_data/2,  % +AuthorizationText, -Data
            http_current_user/3,        % +File, ?User, ?Fields

            http_read_passwd_file/2,    % +File, -Data
            http_write_passwd_file/2    % +File, +Data
          ]).
:- use_module(library(base64)).
:- use_module(library(dcg/basics)).
:- use_module(library(readutil)).
:- use_module(library(lists)).
:- use_module(library(crypt)).
:- use_module(library(debug)).
:- use_module(library(error)).
:- use_module(library(apply)).

/**     <module> Authenticate HTTP connections using 401 headers

This module provides the basics  to   validate  an  HTTP =Authorization=
header. User and password  information  are   read  from  a  Unix/Apache
compatible password file.

This  library  provides,  in  addition    to  the  HTTP  authentication,
predicates to read and write password files.
*/

%!  http_authenticate(+Type, +Request, -Fields)
%
%   True if Request contains the   information to continue according
%   to Type. Type identifies the required authentication technique:
%
%           * basic(+PasswordFile)
%           Use HTTP =Basic= authetication and verify the password
%           from PasswordFile. PasswordFile is a file holding
%           usernames and passwords in a format compatible to
%           Unix and Apache. Each line is record with =|:|=
%           separated fields. The first field is the username and
%           the second the password _hash_.  Password hashes are
%           validated using crypt/2.
%
%   Successful authorization is  cached  for   60  seconds  to avoid
%   overhead of decoding and lookup of the user and password data.
%
%   http_authenticate/3 just validates the  header. If authorization
%   is not provided the browser must   be challenged, in response to
%   which it normally opens a   user-password dialogue. Example code
%   realising this is below. The exception   causes the HTTP wrapper
%   code to generate an HTTP 401 reply.
%
%   ==
%   (   http_authenticate(basic(passwd), Request, Fields)
%   ->  true
%   ;   throw(http_reply(authorise(basic, Realm)))
%   ).
%   ==
%
%   @param  Fields is a list of fields from the password-file entry.
%           The first element is the user.  The hash is skipped.
%   @tbd    Should we also cache failures to reduce the risc of
%           DoS attacks?

http_authenticate(basic(File), Request, [User|Fields]) :-
    memberchk(authorization(Text), Request),
    debug(http_authenticate, 'Authorization: ~w', [Text]),
    (   cached_authenticated(Text, File, User, Fields)
    ->  true
    ;   http_authorization_data(Text, basic(User, Password)),
        debug(http_authenticate,
              'User: ~w, Password: ~s', [User, Password]),
        validate(File, User, Password, Fields),
        get_time(Now),
        assert(authenticated(Text, File, User, Now, Fields)),
        debug(http_authenticate, 'Authenticated ~w~n', [User])
    ).

%!  http_authorization_data(+AuthorizeText, ?Data) is semidet.
%
%   Decode the HTTP =Authorization= header.  Data is a term
%
%       Method(User, Password)
%
%   where Method is the (downcased)  authorization method (typically
%   =basic=), User is an atom holding the  user name and Password is
%   a list of codes holding the password

http_authorization_data(Text, Data) :-
    (   nonvar(Data)
    ->  functor(Data, Method, 2)    % make authorization//2 fail early
    ;   true
    ),
    atom_codes(Text, Codes),
    phrase(authorization(Method, Cookie), Codes),
    phrase(base64(UserPwd), Cookie),
    phrase(ident(UserCodes, Password), UserPwd),
    !,
    atom_codes(User, UserCodes),
    Data =.. [Method, User, Password].

authorization(Method, Cookie) -->
    nonblanks(MethodChars),
    { atom_codes(Method0, MethodChars),
      downcase_atom(Method0, Method)
    },
    blanks,
    nonblanks(Cookie),
    blanks.

ident(User, Password) -->
    string(User),
    ":",
    string(Password).

%!  cached_authenticated(+Authorization, +File, -User, -RestFields)
%
%   Validate using the cache. If the entry   is not in the cache, we
%   also remove all outdated entries from the cache.

:- dynamic
    authenticated/5.        % Authorization, File, User, Time, RestFields

cached_authenticated(Authorization, File, User, Fields) :-
    authenticated(Authorization, File, User, Time, Fields),
    get_time(Now),
    Now-Time =< 60,
    !.              % 60-second timeout
cached_authenticated(_, _, _, _) :-
    get_time(Now),
    (   clause(authenticated(_, _, _, Time, _), true, Ref),
        Now-Time > 60,
        erase(Ref),
        fail
    ).

%!  validate(+File, +User, +Passwd, -Fields)
%
%   True if User and Passwd combination   appears in File. File uses
%   the same format as .htaccess files  from Apache or Unix password
%   files. I.e. it consists  of  one   line  per  entry  with fields
%   separated by =|:|=. The  first  field   is  the  User field, The
%   second contains the Passwd in DES   or MD5 encrypted format. See
%   crypt/2 for details.

validate(File, User, Password, Fields) :-
    update_passwd(File, Path),
    passwd(User, Path, Hash, Fields),
    crypt(Password, Hash).

%!  http_current_user(+File, ?User, ?Fields) is nondet.
%
%   True when User is present in the htpasswd file File and Fields
%   provides the additional fields.
%
%   @arg    Fields are the fields from the password file File,
%           converted using name/2, which means that numeric values
%           are passed as numbers and other fields as atoms.  The
%           password hash is the first element of Fields and is
%           a string.

http_current_user(File, User, Fields) :-
    update_passwd(File, Path),
    passwd(User, Path, Hash, Fields0),
    Fields = [Hash|Fields0].

%!  update_passwd(+File, -Path) is det.
%
%   Update passwd/3 to reflect the correct  passwords for File. Path
%   is the absolute path for File.

:- dynamic
    passwd/4,                       % User, File, Encrypted, Fields
    last_modified/2.                % File, Stamp

update_passwd(File, Path) :-
    absolute_file_name(File, Path, [access(read)]),
    time_file(Path, Stamp),
    (   last_modified(Path, Stamp)
    ->  true
    ;   with_mutex(http_passwd, reload_passwd_file(Path, Stamp))
    ).

reload_passwd_file(Path, Stamp) :-
    last_modified(Path, Stamp),
    !.  % another thread did the work
reload_passwd_file(Path, Stamp) :-
    http_read_passwd_file(Path, Data),
    retractall(last_modified(Path, _)),
    retractall(passwd(_, Path, _, _)),
    forall(member(passwd(User, Hash, Fields), Data),
           assertz(passwd(User, Path, Hash, Fields))),
    assert(last_modified(Path, Stamp)).

%!  http_read_passwd_file(+Path, -Data) is det.
%
%   Read a password file. Data is  a   list  of  terms of the format
%   below, where User is an atom  identifying   the  user, Hash is a
%   string containing the salted password   hash  and Fields contain
%   additional fields. The string value of   each field is converted
%   using name/2 to either a number or an atom.
%
%     ==
%     passwd(User, Hash, Fields)
%     ==

http_read_passwd_file(Path, Data) :-
    setup_call_cleanup(
        open(Path, read, Fd),
        ( read_line_to_codes(Fd, Line),
          read_passwd_file(Line, Fd, Path, Data)
        ),
        close(Fd)).

read_passwd_file(end_of_file, _, _, []) :- !.
read_passwd_file(Line, Fd, Path, Data) :-
    (   phrase(password_line(User, Hash, Fields), Line, _)
    ->  Data = [passwd(User, Hash, Fields)|Tail]
    ;   Tail = Data                 % TBD: warning
    ),
    read_line_to_codes(Fd, Line2),
    read_passwd_file(Line2, Fd, Path, Tail).

password_line(User, Hash, Fields) -->
    string(UserCodes),
    ":",
    string(HashCodes),
    peek_eof,
    !,
    fields(Fields),
    { atom_codes(User, UserCodes),
      string_codes(Hash, HashCodes)
    }.

fields([Field|Fields]) -->
    field(Field),
    !,
    fields(Fields).
fields([]) --> [].

field(Value) -->
    ":",
    !,
    string(Codes),
    peek_eof,
    !,
    { name(Value, Codes)
    }.

peek_eof, ":" --> ":".
peek_eof --> eos.

%!  http_write_passwd_file(+File, +Data:list) is det.
%
%   Write password data Data to File. Data   is a list of entries as
%   below. See http_read_passwd_file/2 for details.
%
%     ==
%     passwd(User, Hash, Fields)
%     ==
%
%   @tbd    Write to a new file and atomically replace the old one.

http_write_passwd_file(File, Data) :-
    must_be(list, Data),
    maplist(valid_data, Data),
    setup_call_cleanup(
        open(File, write, Out, [encoding(utf8)]),
        maplist(write_data(Out), Data),
        close(Out)),
    retractall(last_modified(File, _)). % flush cache

valid_data(passwd(User, Hash, Fields)) :-
    !,
    valid_field(User),
    valid_field(Hash),
    must_be(list, Fields),
    maplist(valid_field, Fields).
valid_data(Data) :-
    type_error(passwd_entry, Data).

valid_field(Field) :-
    must_be(atomic, Field),
    (   number(Field)
    ->  true
    ;   sub_string(Field, _, _, _, ":")
    ->  representation_error(passwd_field)
    ;   true
    ).

write_data(Out, passwd(User, Hash, Fields)) :-
    atomics_to_string([User, Hash|Fields], ":", String),
    format(Out, '~s~n', [String]).

                 /*******************************
                 *   PLUGIN FOR HTTP_DISPATCH   *
                 *******************************/

:- multifile
    http:authenticate/3.

%!  http:authenticate(+AuthData, +Request, -Fields)
%
%   Plugin  for  library(http_dispatch)  to    perform   basic  HTTP
%   authentication.
%
%   This predicate throws http_reply(authorise(basic, Realm)).
%
%   @arg    AuthData must be a term basic(File, Realm)
%   @arg    Request is the HTTP request
%   @arg    Fields describes the authenticated user with the option
%           user(User) and with the option user_details(Fields) if
%           the password file contains additional fields after the
%           user and password.

http:authenticate(basic(File, Realm), Request,
                  [ user(User)
                  | Details
                  ]) :-
    (   http_authenticate(basic(File), Request, [User|Fields])
    ->  (   Fields == []
        ->  Details = []
        ;   Details = [user_details(Fields)]
        )
    ;   throw(http_reply(authorise(basic, Realm)))
    ).


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class FaSortNumericDesc extends React.Component<IconBaseProps> { }
export = FaSortNumericDesc;

redpajama_set_name: RedPajamaGithub


text:
	Синхронизирует матрицу камеры игроков
--]]
--------------------------------------------------------------------------------
--<[ Внутренние события ]>------------------------------------------------------
--------------------------------------------------------------------------------
addEvent( "Camera.onClientSync", true )											-- Клиент прислал данные о матрице своей камеры ( string cameraMatrixData )

--------------------------------------------------------------------------------
--<[ Модуль Camera ]>-----------------------------------------------------------
--------------------------------------------------------------------------------
Camera = {
	init = function()
		addEventHandler( "Camera.onClientSync", resourceRoot, Camera.onClientSync )
	end;

	----------------------------------------------------------------------------
	--<[ Обработчики событий ]>-------------------------------------------------
	----------------------------------------------------------------------------

	-- Клиент прислал данные о матрице своей камеры
	onClientSync = function( cameraMatrixData )
		-- TODO валидация данных "x|y|z|vx|vy|vz"
		setElementData( client, "_cm", cameraMatrixData )
	end;
};
addEventHandler( "onResourceStart", resourceRoot, Camera.init )


text:
package ee.ria.dumonitor.storage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import ee.ria.dumonitor.common.config.Property;
import ee.ria.dumonitor.common.config.PropertyLoader;

/**
 * Generic utilities for servlets: query parsing, database handling, xml parsing, errors etc
 *
 */
public final class Util {

  private static final int ERRCODE_2 = 2;
  private static final int ERRCODE_3 = 3;
  private static final int ERRCODE_4 = 4;
  private static final int ERRCODE_5 = 5;
  private static final int ERRCODE_6 = 6;
  private static final int ERRCODE_7 = 7;
  private static final int ERRCODE_8 = 8;
  private static final int ERRCODE_9 = 9;
  private static final int MAX_TECH_ERROR = 10;

  /**
   * Class with only static methods - no instantiation is allowed.
   */
  private Util() {
  }

  /**
   * Initialize request handling
   *
   * @param req http Request object from servlet
   * @param resp http Response object from servlet
   * @param contentType http request content type
   * @param classObject Caller class object - used for logging
   * @return Context global vars
   * @throws IOException In case there was error when opening output stream
   */
  public static Context initRequest(HttpServletRequest req, HttpServletResponse resp, String contentType,
      Class<?> classObject) throws IOException {
    resp.setContentType(contentType);
    resp.setCharacterEncoding("UTF-8");
    PrintWriter w = resp.getWriter();
    Logger log = LoggerFactory.getLogger(classObject);
    Map<String, String> inParams = new HashMap<String, String>(); // parsed
                                                                  // params
                                                                  // stored here
    Context context = new Context(req, resp, w, log, contentType, inParams);
    boolean ok = Util.loadProperties(context);
    if (ok)
      return context;
    else
      return null;
  }

  /**
   * Use the general configuration file loading methods in common
   *
   * @param context globals
   * @return true if loading ok, false if fails
   * @throws IOException generic catchall
   */
  public static boolean loadProperties(Context context) throws IOException {
    try {
      PropertyLoader.loadProperties(Property.class, "default.properties", "dumonitor.properties");
      if (Property.DATABASE_CONNECTSTRING.getValue() == null || Property.DATABASE_USER.getValue() == null
          || Property.DATABASE_PASSWORD.getValue() == null) {
        showError(context, 1, "failed to load database connect string, user or password configuration properties");
        return false;
      }
      return true;
    } catch (Exception e) {
      showError(context, 1, "failed to load configuration properties: " + e.getMessage());
      return false;
    }
  }

  /**
   * Universal request input parser (cgi,json or xml) data stored to context
   *
   * @param req http Request object from servlet
   * @param resp http Response object from servlet
   * @param context global vars
   * @param inKeys string array of possible input params
   * @param isPost true iff a post request, false iff get
   * @return boolean true if input parsing succeeded, false otherwise
   * @throws IOException generic catchall
   */
  public static boolean parseInput(HttpServletRequest req, HttpServletResponse resp, Context context, String[] inKeys,
      boolean isPost) throws IOException {
    boolean ok;

    String ctype = req.getHeader("Content-Type");
    if (!isPost)
      return Util.parseCgi(context, inKeys);
    // if (ctype==null || (!ctype.equals("application/json") &&
    // !ctype.equals("text/xml"))) {
    if (ctype == null || !ctype.contains("json") && !ctype.contains("xml") && !context.contentType.contains("xml"))
      // default: parse input as cgi key=value parametets
      ok = Util.parseCgi(context, inKeys);
    // } else if (ctype.equals("application/json")) {
    else if (ctype.contains("json"))
      // parse input as json
      ok = Util.parseJson(context, inKeys);
    // } else if (ctype.equals("text/xml")) {
    else if (ctype.contains("xml") || context.contentType.contains("xml"))
      // parse input as xml
      ok = Util.parseXml(context, inKeys);
    else {
      ok = false;
      showError(context, 2, "unknown content-type in http");
    }
    return ok;
  }

  /**
   * Parse input as cgi key=value parameters
   *
   * @param context globals
   * @param inKeys string array of possible input params
   * @return boolean always true for now
   * @throws IOException generic catchall
   */
  public static boolean parseCgi(Context context, String[] inKeys) throws IOException {
    String key, inp;

    for (int i = 0; i < inKeys.length; i++) {
      key = inKeys[i];
      context.inParams.put(key, null); // default value is null
      inp = context.req.getParameter(key); // cgi parameter
      context.inParams.put(key, inp);
    }
    return true;
  }

  /**
   * Parse input as json {"key":"value"} parameters
   *
   * @param context globals
   * @param inKeys string array of possible input params
   * @return boolean true if input parsing succeeded, false otherwise
   * @throws IOException generic catchall
   */
  public static boolean parseJson(Context context, String[] inKeys) throws IOException {
    String inp, key;
    JSONObject jsonObject;

    for (int i = 0; i < inKeys.length; i++) {
      context.inParams.put(inKeys[i], null);
    }

    StringBuffer jb = new StringBuffer();
    try {
      BufferedReader reader = context.req.getReader();
      String line;
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
    } catch (Exception e) {
      // throw new IOException("Error reading request string");
      Util.showError(context, 2, "cannot read input");
      return false;
    }
    try {
      jsonObject = new JSONObject(jb.toString());
      for (int i = 0; i < inKeys.length; i++) {
        key = inKeys[i];
        context.inParams.put(key, null); // default value is null
        if (jsonObject.has(key)) {
          inp = jsonObject.getString(key); // json parameter
          if (inp != null)
            context.inParams.put(key, inp);
        }
      }
    } catch (Exception e) {
      // throw new IOException("Error parsing JSON request string");
      Util.showError(context, ERRCODE_3, "failed to parse input json: " + e.getMessage());
      return false;
    }
    return true;
  }

  /**
   * Parse input as XML (normally from xroad)
   *
   * @param context globals
   * @param inKeys string array of possible input params
   * @return boolean true if input parsing succeeded, false otherwise
   * @throws IOException generic catchall
   */
  public static boolean parseXml(Context context, String[] inKeys) throws IOException {
    String xml;
    StringBuffer jb = new StringBuffer();
    try {
      BufferedReader reader = context.req.getReader();
      String line;
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
    } catch (Exception e) {
      Util.showError(context, ERRCODE_2, "cannot read input");
      return false;
    }
    xml = jb.toString();
    context.xmlstr = xml;
    // context.os.println("|"+xml+"|");
    DocumentBuilder db;
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      db = dbf.newDocumentBuilder();
    } catch (Exception e) {
      Util.showError(context, ERRCODE_4, "preparing xml parsing failed: " + e.getMessage());
      return false;
    }
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document doc;
    try {
      doc = db.parse(is);
    } catch (Exception e) {
      Util.showError(context, ERRCODE_5, "parsing xml failed: " + e.getMessage());
      return false;
    }
    context.xmldoc = doc;
    return true;
  }

  /**
   * Create database connection
   *
   * @param context globals
   * @return Connection db connection object if ok, null if fails
   * @throws IOException generic catchall
   */
  public static Connection createDbConnection(Context context) throws IOException {
    Connection conn = null;

    // check if there is JNDI context in use for datasource:
    if (Property.DATABASE_JNDI.getValue() != null && Property.DATABASE_JNDI.getValue().length() > 0)
      try {
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:/comp/env/" + Property.DATABASE_JNDI.getValue());
        if (ds == null)
          throw new Exception("No data source");
        conn = ds.getConnection();
      } catch (Exception e) {
        Util.showError(context, ERRCODE_7, "Failed to connect to JNDI data source");
        return null;
      }
    else {
      // check whether the driver present
      try {
        Class.forName("org.postgresql.Driver");
      } catch (ClassNotFoundException e) {
        Util.showError(context, ERRCODE_7, "failed to find the PostgreSQL JDBC Driver");
        return null;
      }
      // create db connection
      try {
        conn = DriverManager.getConnection(Property.DATABASE_CONNECTSTRING.getValue(),
            Property.DATABASE_USER.getValue(), Property.DATABASE_PASSWORD.getValue());
      } catch (Exception e) {
        Util.showError(context, ERRCODE_8, "failed to connect to the database");
        return null;
      }
    }
    return conn;
  }

  /**
   * Log and output error message
   *
   * For XML, errors with code < 10 are considered technical
   *
   * @param context globals
   * @param code numeric errcode
   * @param msg string errmessage
   * @throws IOException generic catchall
   */
  public static void showError(Context context, int code, String msg) throws IOException {
    // resp.sendError(resp.SC_BAD_REQUEST, msg); // possible alternative to json
    // output
    String err;
    context.log.error("errcode {} errmessage {}", code, msg);
    if (context.contentType.contains("json")) {
      // json error format
      // handle potential javascript callback parameter
      if (context.inParams.get("callback") != null)
        context.w.println(context.inParams.get("callback") + "(");
      msg = msg.replace("\"", "'").replace("\n", " ").replace("\r", " ");
      context.w.println("{\"errcode\":" + code + ", \"errmessage\":\"" + msg + "\"}");
      if (context.inParams.get("callback") != null)
        context.w.println(");");
    } else {
      // xml error format for xroad
      if (code < MAX_TECH_ERROR) {
        // Technical error: no request obtained or used, no header inserted
        err = Strs.xroadTechErr;
        err = err.replace("{faultCode}", "" + code).replace("{faultString}", cleanXmlStr(msg));
        context.w.println(err);
      } else {
        // Normal error: pass request, insert header
        if (context.xrdVersion.equals("old")) {
          err = Strs.xroadErr.replace("{header}", createSoapHeader(context));
          err = err.replace("{producerns}", Property.XROAD_PRODUCERNS.getValue());
          err = err.replace("{request}", context.xrdRequest);
          err = err.replace("{faultCode}", "" + code).replace("{faultString}", cleanXmlStr(msg));
        } else {
          err = Strs.xroad40Err.replace("{header}", Util.nodeToString(context.xmlheader));
          err = err.replace("{producerns}", Property.XROAD_PRODUCERNS.getValue());
          err = err.replace("{faultCode}", "" + code).replace("{faultString}", cleanXmlStr(msg));
        }
        context.w.println(err);
      }
    }
    context.w.flush();
    context.w.close();
  }

  /**
   * Remove <,>,&," from (xml) string: used mostly for errmessages
   *
   * @param msg input string message
   * @return String cleaned string
   */
  public static String cleanXmlStr(String msg) {
    if (msg == null || msg.equals(""))
      return msg;
    msg = msg.replace("<", " ").replace(">", " ").replace("&", " ").replace("\"", "'");
    return msg;
  }

  /**
   * Output trivial OK message
   *
   * @param context globals
   * @throws IOException generic catchall
   */
  public static void showOK(Context context) throws IOException {
    if (context.contentType.contains("json"))
      context.w.println("{\"ok\":1}");
    else
      context.w.println("<ok>1</ok>");
    context.w.flush();
    context.w.close();
  }

  /*
   * ========== Parsed XML processing utils ===============
   *
  */

  /**
   * Find and return the first instance of an internal node with a given tag and namespace
   *
   * @param context globals
   * @param node xml doc node to search from
   * @param name tag name
   * @param ns tag namespace
   * @return Node found node or null
   * @throws IOException generic catchall
   */
  public static Node getTag(Context context, Node node, String name, String ns) throws IOException {
    if (node == null)
      return null;
    try {
      if (isNode(node, name, ns))
        return node;
      NodeList nodeList = node.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
          Node result = getTag(context, currentNode, name, ns);
          if (result != null)
            return result;
        }
      }
    } catch (Exception e) {
      Util.showError(context, ERRCODE_6, "error traversing xml tree: " + e.getMessage());
    }
    return null;
  }

  /**
   * Find and return the internal text from the first instance of an internal node
   * with a given tag and namespace
   *
   * @param context globals
   * @param node xml doc  node to search from
   * @param name tag name
   * @param ns tag namespace
   * @return Node found node or null
   * @throws IOException generic catchall
   */
  public static String getTagText(Context context, Node node, String name, String ns)
      throws IOException {
    Node foundNode = getTag(context, node, name, ns);
    if (foundNode == null)
      return null;
    String result = foundNode.getTextContent();
    return result;
  }

  /**
   * Check whether passed xml node has given tag name and namespace
   *
   * @param node xml doc node to check
   * @param name tag name
   * @param ns tag namespace
   * @return boolean true if has given tag name and namespace
   */
  public static boolean isNode(Node node, String name, String ns) {
    if (node == null)
      return false;
    if (node.getNodeType() != Node.ELEMENT_NODE)
      return false;
    if (ns != null && (node.getNamespaceURI() == null || !node.getNamespaceURI().equals(ns)))
      return false;
    // if (ns!=null && ! node.getNamespaceURI().equals(ns)) return false;
    String nodename = node.getNodeName();
    if (nodename.contains(":")) {
      String[] parts = nodename.split(":");
      if (parts[1].equals(name))
        return true;
    } else if (nodename.equals(name))
      return true;
    return false;
  }

  /**
   * Convert given xml node to string
   *
   * @param node xml doc node to convert
   * @return String textual form of the node
   * @throws IOException generic catchall
   */
  public static String nodeToString(Node node) throws IOException {
    StringWriter sw = new StringWriter();
    try {
      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (Exception e) {
      return null;
    }
    return sw.toString();
  }

  /**
   * Parse and check X-road header: values stored to context globals.
   * While crucial for old x-road, not really important for the new xroad.
   *
   * @param context globals
   * @param node xml node to search the head from
   * @return boolean true if header was OK, false otherwise
   * @throws IOException generic catchall
   */
  public static boolean parseXroadHeader(Context context, Node node) throws IOException {
    String xrdns = "http://x-road.ee/xsd/x-road.xsd"; // old version
    String newxrdns = "http://x-road.eu/xsd/xroad.xsd"; // new version
    String idns = "http://x-road.eu/xsd/identifiers"; // used by new version
    if (node == null) {
      showError(context, ERRCODE_9, "xml message was empty");
      return false;
    }
    Node headerNode = getTag(context, node, "Header", "http://schemas.xmlsoap.org/soap/envelope/");
    if (headerNode == null) {
      showError(context, ERRCODE_9, "Message Header tag not found");
      return false;
    }
    context.xmlheader = headerNode;
    // determine xroad version
    String version = getTagText(context, headerNode, "protocolVersion", newxrdns);
    if (version == null || !version.equals("4.0")) {
      context.xrdVersion = "old"; // 2.0, 3.0, 3.1
      // parse old xroad version header
      String consumer = getTagText(context, headerNode, "consumer", xrdns);
      String producer = getTagText(context, headerNode, "producer", xrdns);
      String userId = getTagText(context, headerNode, "userId", xrdns);
      String id = getTagText(context, headerNode, "id", xrdns);
      String service = getTagText(context, headerNode, "service", xrdns);
      String issue = getTagText(context, headerNode, "issue", xrdns);
      if (producer == null) {
        showError(context, ERRCODE_9, "Message header producer not found");
        return false;
      }
      if (id == null) {
        showError(context, ERRCODE_9, "Message header id not found");
        return false;
      }
      context.xrdConsumer = consumer;
      context.xrdProducer = producer;
      context.xrdUserId = userId;
      context.xrdId = id;
      context.xrdService = service;
      context.xrdIssue = issue;
      return true;
    } else {
      // new xroad version
      context.xrdVersion = "4.0";
      // parse new xroad version header
      String userId = getTagText(context, headerNode, "userId", newxrdns);
      String id = getTagText(context, headerNode, "id", newxrdns);
      if (id == null) {
        showError(context, ERRCODE_9, "Message header id not found");
        return false;
      }
      Node headerClientNode = getTag(context, headerNode, "client", newxrdns);
      if (headerClientNode == null) {
        showError(context, ERRCODE_9, "Message client tag not found in header");
        return false;
      }
      String memberCode = getTagText(context, headerClientNode, "memberCode", idns);
      if (memberCode == null) {
        showError(context, ERRCODE_9, "Message header client memberCode not found");
        return false;
      }
      context.xrdUserId = userId;
      context.xrdId = id;
      context.xrdClientMemberCode = memberCode;
      return true;
    }
  }

  /**
   * Composing the SOAP header as string for the old x-road: not used for the new x-road
   *
   * @param context globals
   * @return String header string to be included in a template later
   * @throws IOException generic catcall
   */
  public static String createSoapHeader(Context context) throws IOException {
    String header;
    if (context.xrdVersion.equals("4.0")) {
      // new xroad
      showError(context, ERRCODE_9, "Err in code: should not create header for new xroad");
      return "";
    } else {
      // old xroad
      header = Strs.xroadHeader;
      // from request
      header = header.replace("{consumer}", context.xrdProducer);
      header = header.replace("{consumer}", context.xrdProducer);
      header = header.replace("{id}", context.xrdId);
      // our values from configuration
      header = header.replace("{producer}", Property.XROAD_PRODUCER.getValue());
      header = header.replace("{userId}", Property.XROAD_USERID.getValue());
      header = header.replace("{service}", Property.XROAD_SERVICE.getValue());
    }
    return header;
  }
}


text:
var util = require('util'),
	EventEmitter = require('events').EventEmitter,
	logger = require('../logger'),
	_ = require('underscore');

var DebugSession = function(backend) {
	this.backend = backend;
	EventEmitter.call(this);
};

util.inherits(DebugSession, EventEmitter);

_.extend(DebugSession.prototype, {
	pending: {},

	_nowTStamp: function() {
		return new Date().getTime();
	},

	createId: function() {
		if (!this.lastId) {
			this.lastId = this._nowTStamp();
		}
		else {
			this.lastId++;
		}
		return this.lastId;
	},

	setPending: function(id, command, callback) {
		this.pending[id] = {
			command: command,
			callback: callback
		};
	},

	checkPending: function(id) {
		var command = this.pending[id];
		delete this.pending[id];
		return command;
	},

	emitEvent: function(evt, data) {
		this.emit(evt, data);
	},

	gotReply: function(reply) {
		var commandInfo = this.checkPending(reply.id);
		if (commandInfo.callback) {
			commandInfo.callback.call(commandInfo.command, reply.args);
		}

	},

	gotMessage: function(message) {
		this.emitEvent('message', message);
	},

	sendRequest: function(command, callback) {
		var id = this.createId();
		command.id = id;
		this.setPending(id, command, callback);
		this.backend.packAndSendCommand(command);
	}
});

module.exports = DebugSession;


text:
#ifdef ENABLE_GPU
#error "The file nnsubsample.cu should be compiled instead"
#endif
#include "nnbias.cu"

/**
@brief nnbias_forward
@param context context.
@param output output tensor $\by$ [output].
@param outputMult output tensor multiplier $\alpha$.
@param data data tensor $\bx$.
@param dataMult data tensor multiplier $\beta$.
@param biases biases tensor $\bb$.
@param biasesMult biases tensor multiplier $\gamma$.

The function computes
@f[
 y_{ijkd} \leftarrow
 \alpha y_{ijkd} +
 \beta x_{ijkd} +
 \gamma b_k.
@f]

@a data can be the null tensor, in which case this tensor
is dropped in the summation.
*/

/**
@brief nnbias_backward
@param context context.
@param derData data derivative tensor $d\bx$ [output].
@param derDataMult data derivative tensor multiplier $\eta$.
@param derBiases biases derivative tensor $d\bb$ [output].
@param derBiasesMult biased derivative tensor multiplier $\tau$.
@param data data tensor $\bx$.
@param dataMult data tensor multiplier $\beta$.
@param biases biases tensor $\bb$.
@param biasesMult biases tensor multiplier $\gamma$.

If @a derData is the null tensor, this derivative is not comptued and
@param biases can also be null.

If @a derBiases is the null tensor, this derivative is not computed and
@param data can also be null.
*/


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

import java.util.List;
import javax.annotation.Generated;

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

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

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

    private static final MarshallingInfo<String> GAMESERVERGROUPNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GameServerGroupName").build();
    private static final MarshallingInfo<String> ROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("RoleArn").build();
    private static final MarshallingInfo<List> INSTANCEDEFINITIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstanceDefinitions").build();
    private static final MarshallingInfo<String> GAMESERVERPROTECTIONPOLICY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GameServerProtectionPolicy").build();
    private static final MarshallingInfo<String> BALANCINGSTRATEGY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("BalancingStrategy").build();

    private static final UpdateGameServerGroupRequestMarshaller instance = new UpdateGameServerGroupRequestMarshaller();

    public static UpdateGameServerGroupRequestMarshaller getInstance() {
        return instance;
    }

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

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

        try {
            protocolMarshaller.marshall(updateGameServerGroupRequest.getGameServerGroupName(), GAMESERVERGROUPNAME_BINDING);
            protocolMarshaller.marshall(updateGameServerGroupRequest.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(updateGameServerGroupRequest.getInstanceDefinitions(), INSTANCEDEFINITIONS_BINDING);
            protocolMarshaller.marshall(updateGameServerGroupRequest.getGameServerProtectionPolicy(), GAMESERVERPROTECTIONPOLICY_BINDING);
            protocolMarshaller.marshall(updateGameServerGroupRequest.getBalancingStrategy(), BALANCINGSTRATEGY_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package com.facebook.buck.android;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractBuilder;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSortedSet;

import java.nio.file.Path;

import javax.annotation.Nullable;

public class PrebuiltNativeLibraryBuilder
    extends AbstractBuilder<PrebuiltNativeLibraryDescription.Arg> {

  private PrebuiltNativeLibraryBuilder(BuildTarget target) {
    super(new PrebuiltNativeLibraryDescription(), target);
  }

  public static PrebuiltNativeLibraryBuilder newBuilder(BuildTarget buildTarget) {
    return new PrebuiltNativeLibraryBuilder(buildTarget);
  }

  public PrebuiltNativeLibraryBuilder setIsAsset(@Nullable Boolean isAsset) {
    arg.isAsset = Optional.fromNullable(isAsset);
    return this;
  }

  public PrebuiltNativeLibraryBuilder setNativeLibs(@Nullable Path nativeLibs) {
    arg.nativeLibs = nativeLibs;
    return this;
  }

  public PrebuiltNativeLibraryBuilder setDeps(@Nullable ImmutableSortedSet<BuildTarget> deps) {
    arg.deps = Optional.fromNullable(deps);
    return this;
  }
}


text:
title: Graphing Linear Inequalities
localeTitle: Representando Desigualdades Lineares
---
## Representando Desigualdades Lineares

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/graphing-linear-inequalities/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Mais Informações:


text:
package com.example.android.uamp;

 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.os.RemoteException;
 import android.support.annotation.NonNull;
 import android.support.v4.media.MediaBrowserCompat;
 import android.support.v4.media.MediaBrowserCompat.MediaItem;
 import android.support.v4.media.MediaBrowserServiceCompat;
 import android.support.v4.media.MediaDescriptionCompat;
 import android.support.v4.media.MediaMetadataCompat;
 import android.support.v4.media.session.MediaButtonReceiver;
 import android.support.v4.media.session.MediaSessionCompat;
 import android.support.v4.media.session.PlaybackStateCompat;
 import android.support.v7.media.MediaRouter;

 import com.example.android.uamp.ui.MediaBrowserClient.BrowsableItem;
 /*
 import com.example.android.uamp.model.CursorBasedPagedAlbumByIdMediaProvider;
 import com.example.android.uamp.model.CursorBasedPagedAlbumsMediaProvider;
 import com.example.android.uamp.model.CursorBasedPagedArtistByIdMediaProvider;
 import com.example.android.uamp.model.CursorBasedPagedArtistsMediaProvider;
 */
 import com.example.android.uamp.model.MusicProvider;
 import com.example.android.uamp.playback.*;
 import com.example.android.uamp.settings.Settings;
 import com.example.android.uamp.ui.MainLauncherActivity;
 import com.example.android.uamp.ui.MediaBrowserClient.MediaIDUampHelper;
 import com.example.android.uamp.utils.CarHelper;
 import com.example.android.uamp.utils.LogHelper;
 import com.example.android.uamp.utils.TvHelper;
 import com.example.android.uamp.utils.WearHelper;
 import com.google.android.gms.cast.framework.CastContext;
 import com.google.android.gms.cast.framework.CastSession;
 import com.google.android.gms.cast.framework.SessionManager;
 import com.google.android.gms.cast.framework.SessionManagerListener;
 import com.google.android.gms.common.ConnectionResult;
 import com.google.android.gms.common.GoogleApiAvailability;

 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 //import com.example.android.uamp.model.CursorBasedPagedMediaProvider;

 import static com.example.android.uamp.ui.MediaBrowserClient.MediaIDUampHelper.MEDIA_ID_EMPTY_ROOT;
 import static com.example.android.uamp.ui.MediaBrowserClient.MediaIDUampHelper.MEDIA_ID_ROOT;

 /**
  * This class provides a MediaBrowser through a service. It exposes the media library to a browsing
  * client, through the onGetRoot and onLoadChildren methods. It also creates a MediaSession and
  * exposes it through its MediaSession.Token, which allows the client to create a MediaController
  * that connects to and send control commands to the MediaSession remotely. This is useful for
  * user interfaces that need to interact with your media session, like Android Auto. You can
  * (should) also use the same service from your app's UI, which gives a seamless playback
  * experience to the user.
  *
  * To implement a MediaBrowserService, you need to:
  *
  *

  *
  *
 Extend {@link android.service.media.MediaBrowserService}, implementing the media browsing
  *      related methods {@link android.service.media.MediaBrowserService#onGetRoot} and
  *      {@link android.service.media.MediaBrowserService#onLoadChildren};
  *
 In onCreate, start a new {@link android.media.session.MediaSession} and notify its parent
  *      with the session's token {@link android.service.media.MediaBrowserService#setSessionToken};
  *
  *
 Set a callback on the
  *      {@link android.media.session.MediaSession#setCallback(android.media.session.MediaSession.Callback)}.
  *      The callback will receive all the user's actions, like play, pause, etc;
  *
  *
 Handle all the actual music playing using any method your app prefers (for example,
  *      {@link android.media.MediaPlayer})
  *
  *
 Update playbackState, "now playing" metadata and queue, using MediaSession proper methods
  *      {@link android.media.session.MediaSession#setPlaybackState(android.media.session.PlaybackState)}
  *      {@link android.media.session.MediaSession#setMetadata(android.media.MediaMetadata)} and
  *      {android.media.session.MediaSession#setQueue(java.util.List)})
  *
  *
 Declare and export the service in AndroidManifest with an intent receiver for the action
  *      android.media.browse.MediaBrowserService
  *
  *

  *
  * To make your app compatible with Android Auto, you also need to:
  *
  *

  *
  *
 Declare a meta-data tag in AndroidManifest.xml linking to a xml resource
  *      with a <automotiveApp> root element. For a media app, this must include
  *      an <uses name="media"/> element as a child.
  *      For example, in AndroidManifest.xml:
  *          <meta-data android:name="com.google.android.gms.car.application"
  *              android:resource="@xml/automotive_app_desc"/>
  *      And in res/values/automotive_app_desc.xml:
  *          <automotiveApp>
  *              <uses name="media"/>
  *          </automotiveApp>
  *
  *

  * @see README.md for more details.
  *
  */
 public class MusicService extends MediaBrowserServiceCompat implements
         PlaybackManager.PlaybackServiceCallback {

     private static final String TAG = LogHelper.makeLogTag(MusicService.class);

     // Extra on MediaSession that contains the Cast device name currently connected to
     public static final String EXTRA_CONNECTED_CAST = "com.example.android.uamp.CAST_NAME";
     // The action of the incoming Intent indicating that it contains a command
     // to be executed (see {@link #onStartCommand})
     public static final String ACTION_CMD = "com.example.android.uamp.ACTION_CMD";
     // The key in the extras of the incoming Intent indicating the command that
     // should be executed (see {@link #onStartCommand})
     public static final String CMD_NAME = "CMD_NAME";
     // A value of a CMD_NAME key in the extras of the incoming Intent that
     // indicates that the music playback should be paused (see {@link #onStartCommand})
     public static final String CMD_PAUSE = "CMD_PAUSE";
     // A value of a CMD_NAME key that indicates that the music playback should switch
     // to local playback from cast playback.
     public static final String CMD_STOP_CASTING = "CMD_STOP_CASTING";
     // Delay stopSelf by using a handler.
     private static final int STOP_DELAY = 30000;

     private MusicProvider mMusicProvider;
     private PlaybackManager mPlaybackManager;

     private MediaSessionCompat mSession;
     private MediaNotificationManager mMediaNotificationManager;
     private Bundle mSessionExtras;
     private final DelayedStopHandler mDelayedStopHandler = new DelayedStopHandler(this);
     private MediaRouter mMediaRouter;
     private PackageValidator mPackageValidator;
     private SessionManager mCastSessionManager;
     private SessionManagerListener<CastSession> mCastSessionManagerListener;

     private boolean mIsConnectedToCar;
     private BroadcastReceiver mCarConnectionReceiver;

     // Used by the onLoadChildren to get paginated data
     /*
     private CursorBasedPagedMediaProvider mCursorBasedPagedMediaProvider;
     private CursorBasedPagedAlbumsMediaProvider mCursorBasedPagedAlbumsMediaProvider;
     private CursorBasedPagedAlbumByIdMediaProvider mCursorBasedPagedAlbumByIdMediaProvider;
     private CursorBasedPagedArtistByIdMediaProvider mCursorBasedPagedArtistByIdMediaProvider;
     private CursorBasedPagedArtistsMediaProvider mCursorBasedPagedArtistsMediaProvider;
    */
     private ArrayList<MediaItem> mHistoryList = new ArrayList<>();

     private void addItemToHistory(MediaMetadataCompat metadata) {
         int historySize = Settings.getHistorySize(getApplicationContext());
         MediaItem mediaItem = new MediaItem(metadata.getDescription(), MediaItem.FLAG_PLAYABLE);
         mHistoryList.add(0, mediaItem); // add to top of history (most recent)
         if (mHistoryList.size() > historySize) {
             int index = 0;
             Iterator<MediaItem> itr = mHistoryList.iterator();
             while (itr.hasNext()) {
                 itr.next();
                 if (index++ > historySize) {
                     LogHelper.i(TAG, "remove item from history");
                     itr.remove();
                 }
             }
         }
     }

     /*
      * (non-Javadoc)
      * @see android.app.Service#onCreate()
      */
     @Override
     public void onCreate() {
         super.onCreate();
         LogHelper.i(TAG, "onCreate");

         mMusicProvider = new MusicProvider(this);

         // To make the app more responsive, fetch and cache catalog information now.
         // This can help improve the response time in the method
         // {@link #onLoadChildren(String, Result<List<MediaItem>>) onLoadChildren()}.

         // WE DONT'T NEED TO DO THIS. OUR CATALOGUE ISN'T ONLINE
         // mMusicProvider.retrieveMediaAsync(null /* Callback */);

         mPackageValidator = new PackageValidator(this);

         // Queue manager is just our local utility class, maintaining a queue of MediaSessionCompat.QueueItem
         // Any changes to the queue (current queue index updated or queue changed will be called back to this service
         // (using QueueManager.MetadataUpdateListener)
         // So in effect the sevice holds the queue, via the queuemanager
         QueueManager queueManager = new QueueManager(mMusicProvider, getResources(), getApplicationContext(),
                 new QueueManager.MetadataUpdateListener() {
                     @Override
                     public void onMetadataChanged(MediaMetadataCompat metadata) {
                         LogHelper.i(TAG, "Service MetadataUpdateListener onMetadataChanged ", metadata.getDescription().getTitle());
                         addItemToHistory(metadata);
                         notifyChildrenChanged("HISTORY");
                         mSession.setMetadata(metadata);
                     }

                     @Override
                     public void onMetadataRetrieveError() {
                         mPlaybackManager.updatePlaybackState(
                                 getString(R.string.error_no_metadata));
                     }
/* there is no queue index
    so onCurrentQueueIndexUpdated has been replaced by onNowPlayingChanged
                    @Override
                    public void onCurrentQueueIndexUpdated(int queueIndex) {
                        mPlaybackManager.handlePlayRequest();
                    }
*/

                     @Override
                     public void onNowPlayingChanged(MediaSessionCompat.QueueItem newNowPlaying) {
                         LogHelper.i(TAG, "Service MetadataUpdateListener onNowPlayingChanged ", newNowPlaying.getDescription().getTitle(), "id=,",
                                 newNowPlaying.getDescription().getMediaId());
                         mPlaybackManager.handlePlayRequest();
                     }

                     // I added this!
                     @Override
                     public void onPauseRequest() {
                         LogHelper.i(TAG, "Service MetadataUpdateListener onPauseRequest ");
                         mSession.getController().getTransportControls().pause();
                     }

                     @Override
                     public void onQueueUpdated(String title,
                                                List<MediaSessionCompat.QueueItem> newQueue) {
                         LogHelper.i(TAG, "Service MetadataUpdateListener onQueueUpdated: size= ", newQueue.size());
                         // So when the queue is updated we tell our mediaSessionCompat
                         // The media session has callbacks which are handled by mPlaybackManager
                         mSession.setQueue(newQueue);// DISABLED
                         mSession.setQueueTitle(title);// DISABLED
                     }
                 });

         Context context = getApplicationContext();

         StoragePlayback /*LocalPlayback*/ playback = new StoragePlayback /*LocalPlayback*/ (this, mMusicProvider);
         mPlaybackManager = new PlaybackManager(this, getResources(), mMusicProvider, queueManager,
                 playback, context);

         // Start a new MediaSession
         mSession = new MediaSessionCompat(this, "MusicService");
         setSessionToken(mSession.getSessionToken());
         mSession.setCallback(mPlaybackManager.getMediaSessionCallback());
         mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                 | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
                 | MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS);

         Intent intent = new Intent(context, MainLauncherActivity.class);
         PendingIntent pi = PendingIntent.getActivity(context, 99 /*request code*/,
                 intent, PendingIntent.FLAG_UPDATE_CURRENT);
         mSession.setSessionActivity(pi);

         mSessionExtras = new Bundle();
         CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
         WearHelper.setSlotReservationFlags(mSessionExtras, true, true);
         WearHelper.setUseBackgroundFromTheme(mSessionExtras, true);
         mSession.setExtras(mSessionExtras);

         mPlaybackManager.updatePlaybackState(null);

         try {
             mMediaNotificationManager = new MediaNotificationManager(this);
         } catch (RemoteException e) {
             throw new IllegalStateException("Could not create a MediaNotificationManager", e);
         }

         int playServicesAvailable =
                 GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);

         if (!TvHelper.isTvUiMode(this) && playServicesAvailable == ConnectionResult.SUCCESS) {
             mCastSessionManager = CastContext.getSharedInstance(this).getSessionManager();
             mCastSessionManagerListener = new CastSessionManagerListener();
             mCastSessionManager.addSessionManagerListener(mCastSessionManagerListener,
                     CastSession.class);
         }

         mMediaRouter = MediaRouter.getInstance(getApplicationContext());

         registerCarConnectionReceiver();
         // fill an initial random queue. Does not set any song to play
         queueManager.fillRandomQueue();
     }

     /**
      * (non-Javadoc)
      * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
      */
     @Override
     public int onStartCommand(Intent startIntent, int flags, int startId) {
         if (startIntent != null) {
             String action = startIntent.getAction();
             String command = startIntent.getStringExtra(CMD_NAME);
             if (ACTION_CMD.equals(action)) {
                 if (CMD_PAUSE.equals(command)) {
                     mPlaybackManager.handlePauseRequest();
                 } else if (CMD_STOP_CASTING.equals(command)) {
                     CastContext.getSharedInstance(this).getSessionManager().endCurrentSession(true);
                 }
             } else {
                 // Try to handle the intent as a media button event wrapped by MediaButtonReceiver
                 MediaButtonReceiver.handleIntent(mSession, startIntent);
             }
         }
         // Reset the delay handler to enqueue a message to stop the service if
         // nothing is playing.
         mDelayedStopHandler.removeCallbacksAndMessages(null);
         mDelayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
         return START_STICKY;
     }

     /**
      * (non-Javadoc)
      * @see android.app.Service#onDestroy()
      */
     @Override
     public void onDestroy() {
         LogHelper.d(TAG, "onDestroy");
         unregisterCarConnectionReceiver();
         // Service is being killed, so make sure we release our resources
         mPlaybackManager.handleStopRequest(null);
         mMediaNotificationManager.stopNotification();

         if (mCastSessionManager != null) {
             mCastSessionManager.removeSessionManagerListener(mCastSessionManagerListener,
                     CastSession.class);
         }

         mDelayedStopHandler.removeCallbacksAndMessages(null);
         mSession.release();
     }

     @Override
     public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid,
                                  Bundle rootHints) {
         LogHelper.i(TAG, "OnGetRoot: clientPackageName=" + clientPackageName,
                 "; clientUid=" + clientUid + " ; rootHints=", rootHints);
         // To ensure you are not allowing any arbitrary app to browse your app's contents, you
         // need to check the origin:
         if (!mPackageValidator.isCallerAllowed(this, clientPackageName, clientUid)) {
             // If the request comes from an untrusted package, return an empty browser root.
             // If you return null, then the media browser will not be able to connect and
             // no further calls will be made to other media browsing methods.
             LogHelper.i(TAG, "OnGetRoot: Browsing NOT ALLOWED for unknown caller. "
                     + "Returning empty browser root so all apps can use MediaController."
                     + clientPackageName);
             return new MediaBrowserServiceCompat.BrowserRoot(MediaIDUampHelper.MEDIA_ID_EMPTY_ROOT, null);
         }
         //noinspection StatementWithEmptyBody
         if (CarHelper.isValidCarPackage(clientPackageName)) {
             // Optional: if your app needs to adapt the music library to show a different subset
             // when connected to the car, this is where you should handle it.
             // If you want to adapt other runtime behaviors, like tweak ads or change some behavior
             // that should be different on cars, you should instead use the boolean flag
             // set by the BroadcastReceiver mCarConnectionReceiver (mIsConnectedToCar).
         }
         //noinspection StatementWithEmptyBody
         if (WearHelper.isValidWearCompanionPackage(clientPackageName)) {
             // Optional: if your app needs to adapt the music library for when browsing from a
             // Wear device, you should return a different MEDIA ROOT here, and then,
             // on onLoadChildren, handle it accordingly.
         }
         LogHelper.i(TAG,"return root");
         return new BrowserRoot(MediaIDUampHelper.MEDIA_ID_ROOT, null);
     }

     private List<MediaBrowserCompat.MediaItem> mapToMediaItems(List<BrowsableItem> browsableItems) {
         List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
         for (BrowsableItem browsableItem : browsableItems) {
             MediaDescriptionCompat mediaDescription = new MediaDescriptionCompat.Builder()
                     .setTitle(browsableItem.title)
                     .setSubtitle(browsableItem.subtitle)
                     .setMediaId(browsableItem.mediaId)
                     .build();

             int flags = 0;
             if (browsableItem.isPlayable) {
                 flags |= MediaItem.FLAG_PLAYABLE;
             }
             if (browsableItem.isBrowsable) {
                 flags |= MediaItem.FLAG_BROWSABLE;
             }

             MediaBrowserCompat.MediaItem mediaItem = new MediaBrowserCompat.MediaItem(mediaDescription, flags);
             mediaItems.add(mediaItem);
         }

         return mediaItems;
     }

     /**
      * Overriden method of MediaBrowserServiceCompat
      * Used to get history
      * @param parentMediaId
      * @param result
      */
     @Override
     public void onLoadChildren(@NonNull final String parentMediaId,
                                @NonNull final Result<List<MediaItem>> result) {
         LogHelper.i(TAG, "OnLoadChildren id=", parentMediaId);
         if (parentMediaId.equals(MediaIDUampHelper.MEDIA_ID_HISTORY)) {
             result.sendResult(mHistoryList);
         } else if (parentMediaId.equals(MediaIDUampHelper.MEDIA_ID_ALL_SONGS)) {
             ArrayList<MediaItem> mediaItems = mMusicProvider.getAllSongs();
             result.sendResult(mediaItems);
         } else if (parentMediaId.equals(MediaIDUampHelper.MEDIA_ID_ARTISTS)) {
             ArrayList<MediaItem> mediaItems = mMusicProvider.getArtistMediaItems();
             LogHelper.i(TAG, "found ", mediaItems.size()," items");
             result.sendResult(mediaItems);
         } else if (parentMediaId.equals(MediaIDUampHelper.MEDIA_ID_ALBUMS)) {
             ArrayList<MediaItem> mediaItems = mMusicProvider.getAlbumMediaItems();
             LogHelper.i(TAG, "found ", mediaItems.size()," items");
             result.sendResult(mediaItems);
         } else if (parentMediaId.startsWith(MediaIDUampHelper.MEDIA_ID_ARTIST)) {
             String artistMediaID = MediaIDUampHelper.getArtistIdFromMediaId(parentMediaId);
             LogHelper.i(TAG, "id = ", artistMediaID);
             ArrayList<MediaItem> mediaItems = mMusicProvider.getMediaItemsByArtist(artistMediaID);
             result.sendResult(mediaItems);
         } else if (parentMediaId.startsWith(MediaIDUampHelper.MEDIA_ID_ALBUM)) {
             String AlbumMediaId = MediaIDUampHelper.getAlbumIdFromMediaId(parentMediaId);
             LogHelper.i(TAG, "id = ", AlbumMediaId);
             ArrayList<MediaItem> mediaItems = mMusicProvider.getMediaItemsByAlbum(AlbumMediaId);
             result.sendResult(mediaItems);
         } else if (parentMediaId.equals(MEDIA_ID_ROOT)) {
             ArrayList<BrowsableItem> mainMenuItems = new ArrayList<>();
             BrowsableItem s;
             s = new BrowsableItem("All Songs", "View All songs on the device", MediaIDUampHelper.MEDIA_ID_ALL_SONGS,false, true);
             mainMenuItems.add(s);
             s = new BrowsableItem("History", "View recently played songs", MediaIDUampHelper.MEDIA_ID_HISTORY, false, true);
             mainMenuItems.add(s);
             s = new BrowsableItem("Albums", "View all albums", MediaIDUampHelper.MEDIA_ID_ALBUMS, false, true);
             mainMenuItems.add(s);
             s = new BrowsableItem("Artists", "View all artists", MediaIDUampHelper.MEDIA_ID_ARTISTS, false, true);
             mainMenuItems.add(s);
             List<MediaBrowserCompat.MediaItem> mediaItems = mapToMediaItems(mainMenuItems);
             result.sendResult(mediaItems);
         } else {
             result.sendResult(null);
         }
     }

     /**
      * Callback method called from PlaybackManager whenever the music is about to play.
      */
     @Override
     public void onPlaybackStart() {
         mSession.setActive(true);

         mDelayedStopHandler.removeCallbacksAndMessages(null);

         // The service needs to continue running even after the bound client (usually a
         // MediaController) disconnects, otherwise the music playback will stop.
         // Calling startService(Intent) will keep the service running until it is explicitly killed.
         startService(new Intent(getApplicationContext(), MusicService.class));
     }

     /**
      * Callback method called from PlaybackManager whenever the music stops playing.
      */
     @Override
     public void onPlaybackStop() {
         mSession.setActive(false);
         // Reset the delayed stop handler, so after STOP_DELAY it will be executed again,
         // potentially stopping the service.
         mDelayedStopHandler.removeCallbacksAndMessages(null);
         mDelayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
         stopForeground(true);
     }

     @Override
     public void onNotificationRequired() {
         mMediaNotificationManager.startNotification();
     }

     @Override
     public void onPlaybackStateUpdated(PlaybackStateCompat newState) {
         mSession.setPlaybackState(newState);
     }

     private void registerCarConnectionReceiver() {
         IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
         mCarConnectionReceiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                 String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
                 mIsConnectedToCar = CarHelper.MEDIA_CONNECTED.equals(connectionEvent);
                 LogHelper.i(TAG, "Connection event to Android Auto: ", connectionEvent,
                         " isConnectedToCar=", mIsConnectedToCar);
             }
         };
         registerReceiver(mCarConnectionReceiver, filter);
     }

     private void unregisterCarConnectionReceiver() {
         unregisterReceiver(mCarConnectionReceiver);
     }

     /**
      * A simple handler that stops the service if playback is not active (playing)
      */
     private static class DelayedStopHandler extends Handler {
         private final WeakReference<MusicService> mWeakReference;

         private DelayedStopHandler(MusicService service) {
             mWeakReference = new WeakReference<>(service);
         }

         @Override
         public void handleMessage(Message msg) {
             MusicService service = mWeakReference.get();
             if (service != null && service.mPlaybackManager.getPlayback() != null) {
                 if (service.mPlaybackManager.getPlayback().isPlaying()) {
                     LogHelper.d(TAG, "Ignoring delayed stop since the media player is in use.");
                     return;
                 }
                 LogHelper.d(TAG, "Stopping service with delay handler.");
                 service.stopSelf();
             }
         }
     }

     /**
      * Session Manager Listener responsible for switching the Playback instances
      * depending on whether it is connected to a remote player.
      */
     private class CastSessionManagerListener implements SessionManagerListener<CastSession> {

         @Override
         public void onSessionEnded(CastSession session, int error) {
             LogHelper.d(TAG, "onSessionEnded");
             mSessionExtras.remove(EXTRA_CONNECTED_CAST);
             mSession.setExtras(mSessionExtras);
             Playback playback = new StoragePlayback /*LocalPlayback*/ (MusicService.this, mMusicProvider);
             mMediaRouter.setMediaSessionCompat(null);
             mPlaybackManager.switchToPlayback(playback, false);
         }

         @Override
         public void onSessionResumed(CastSession session, boolean wasSuspended) {
         }

         @Override
         public void onSessionStarted(CastSession session, String sessionId) {
             // In case we are casting, send the device name as an extra on MediaSession metadata.
             mSessionExtras.putString(EXTRA_CONNECTED_CAST,
                     session.getCastDevice().getFriendlyName());
             mSession.setExtras(mSessionExtras);
             // Now we can switch to CastPlayback
             Playback playback = new CastPlayback(mMusicProvider, MusicService.this);
             mMediaRouter.setMediaSessionCompat(mSession);
             mPlaybackManager.switchToPlayback(playback, true);
         }

         @Override
         public void onSessionStarting(CastSession session) {
         }

         @Override
         public void onSessionStartFailed(CastSession session, int error) {
         }

         @Override
         public void onSessionEnding(CastSession session) {
             // This is our final chance to update the underlying stream position
             // In onSessionEnded(), the underlying CastPlayback#mRemoteMediaClient
             // is disconnected and hence we update our local value of stream position
             // to the latest position.
             mPlaybackManager.getPlayback().updateLastKnownStreamPosition();
         }

         @Override
         public void onSessionResuming(CastSession session, String sessionId) {
         }

         @Override
         public void onSessionResumeFailed(CastSession session, int error) {
         }

         @Override
         public void onSessionSuspended(CastSession session, int reason) {
         }
     }
 }


text:
import os.path

import cv2
import numpy as np
from opensfm import context

class BagOfWords:
    def __init__(self, words, frequencies):
        self.words = words
        self.frequencies = frequencies
        self.weights = np.log(frequencies.sum() / frequencies)
        FLANN_INDEX_KDTREE = 1
        flann_params = {"algorithm": FLANN_INDEX_KDTREE, "trees": 8, "checks": 300}
        self.index = context.flann_Index(words, flann_params)

    def map_to_words(self, descriptors, k, matcher_type="FLANN"):
        if matcher_type == "FLANN":
            params = {"checks": 200}
            idx, dist = self.index.knnSearch(descriptors, k, params=params)
        else:
            matcher = cv2.DescriptorMatcher_create(matcher_type)
            matches = matcher.knnMatch(descriptors, self.words, k=k)
            idx = [[int(n.trainIdx) for n in m] for m in matches]
            idx = np.array(idx).astype(np.int32)
        return idx

    def histogram(self, words):
        h = np.bincount(words, minlength=len(self.words)) * self.weights
        return h / h.sum()

    def bow_distance(self, w1, w2, h1=None, h2=None):
        if h1 is None:
            h1 = self.histogram(w1)
        if h2 is None:
            h2 = self.histogram(w2)
        return np.fabs(h1 - h2).sum()

def load_bow_words_and_frequencies(config):
    if config["bow_file"] == "bow_hahog_root_uchar_10000.npz":
        assert config["feature_type"] == "HAHOG"
        assert config["feature_root"]
        assert config["hahog_normalize_to_uchar"]

    bow_file = os.path.join(context.BOW_PATH, config["bow_file"])
    bow = np.load(bow_file)
    return bow["words"], bow["frequencies"]

def load_vlad_words_and_frequencies(config):
    if config["vlad_file"] == "bow_hahog_root_uchar_64.npz":
        assert config["feature_type"] == "HAHOG"
        assert config["feature_root"]
        assert config["hahog_normalize_to_uchar"]

    vlad_file = os.path.join(context.BOW_PATH, config["vlad_file"])
    vlad = np.load(vlad_file)
    return vlad["words"], vlad["frequencies"]

def load_bows(config):
    words, frequencies = load_bow_words_and_frequencies(config)
    return BagOfWords(words, frequencies)


text:
package com.mindoo.domino.jna.internal.structs;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.List;

import com.sun.jna.Pointer;
import com.sun.jna.Structure;
/**
 * This file was autogenerated by JNAerator,

 * a tool written by Olivier Chafik that uses a few opensource projects..

 * For help, please visit NativeLibs4Java , Rococoa, or JNA.
 */
public class NotesReplicationHistorySummaryStruct extends BaseStructure {
	/**
	 * Time returned from last replication

	 * C type : TIMEDATE
	 */
	public NotesTimeDateStruct ReplicationTime;
	/** Access level at time of replication */
	public short AccessLevel;
	/** Access flags at time of replication */
	public short AccessFlags;
	/** NEVER, SEND, RECEIVE */
	public short Direction;
	/** Server name offset in packed data */
	public int ServerNameOffset;
	/** Server name length in packed data */
	public short ServerNameLength;
	/** File name length in packed data */
	public short FileNameLength;
	/** contains MoreInfo from cache - includes complete replication flag */
	public short MoreInfo;
	/** Room for growth */
	public short wSpare;
	/** Room for growth */
	public int dwSpare;

	public NotesReplicationHistorySummaryStruct() {
		super(Structure.ALIGN_DEFAULT);
	}

	public static NotesReplicationHistorySummaryStruct newInstance() {
		return AccessController.doPrivileged(new PrivilegedAction<NotesReplicationHistorySummaryStruct>() {

			@Override
			public NotesReplicationHistorySummaryStruct run() {
				return new NotesReplicationHistorySummaryStruct();
			}
		});
	}

	protected List<String> getFieldOrder() {
		return Arrays.asList("ReplicationTime", "AccessLevel", "AccessFlags", "Direction", "ServerNameOffset", "ServerNameLength", "FileNameLength", "MoreInfo", "wSpare", "dwSpare");
	}

	public NotesReplicationHistorySummaryStruct(Pointer peer) {
		super(peer, Structure.ALIGN_DEFAULT);
	}

	public static NotesReplicationHistorySummaryStruct newInstance(Pointer peer) {
		return AccessController.doPrivileged(new PrivilegedAction<NotesReplicationHistorySummaryStruct>() {

			@Override
			public NotesReplicationHistorySummaryStruct run() {
				return new NotesReplicationHistorySummaryStruct(peer);
			}
		});
	}

	public static class ByReference extends NotesReplicationHistorySummaryStruct implements Structure.ByReference {

	};
	public static class ByValue extends NotesReplicationHistorySummaryStruct implements Structure.ByValue {

	};
}


text:
package org.modelmapper.bugs;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import org.modelmapper.AbstractTest;
import org.testng.annotations.Test;

/**
 * https://github.com/jhalterman/modelmapper/issues/9
 *
 * Reported by andy-m.
 */
@Test
public class GH9 extends AbstractTest {
  public static class TestItem {
    TestItemConfiguration testItemConfiguration;
  }

  static class TestItemConfiguration {
    SomeConfiguration someConfiguration;
  }

  static class SomeConfiguration {
    String someProperty;
    boolean someOtherProperty;
  }

  static class TestItemDTO {
    TestItemConfigurationDTO testItemConfiguration;
  }

  static class TestItemConfigurationDTO {
    SomeConfigurationDTO someConfiguration;
  }

  static class SomeConfigurationDTO {
    String someProperty;
  }

  public void testValuesInDestinationRemainUnchangedUnlessTheyArePresentInSource() {
    String expectedValue = "someValue";
    TestItemDTO source = new TestItemDTO();
    source.testItemConfiguration = new TestItemConfigurationDTO();
    source.testItemConfiguration.someConfiguration = new SomeConfigurationDTO();
    source.testItemConfiguration.someConfiguration.someProperty = "someValue";

    TestItem dest = new TestItem();
    TestItemConfiguration destItemConfig = new TestItemConfiguration();
    SomeConfiguration destSomeConfig = new SomeConfiguration();
    dest.testItemConfiguration = destItemConfig;
    dest.testItemConfiguration.someConfiguration = destSomeConfig;
    dest.testItemConfiguration.someConfiguration.someProperty = "someValueX";
    dest.testItemConfiguration.someConfiguration.someOtherProperty = true;

    modelMapper.map(source, dest);

    assertEquals(expectedValue, dest.testItemConfiguration.someConfiguration.someProperty);
    assertEquals(destItemConfig, dest.testItemConfiguration);
    assertEquals(destSomeConfig, dest.testItemConfiguration.someConfiguration);
    assertTrue(dest.testItemConfiguration.someConfiguration.someOtherProperty);
  }
}


text:
package com.likya.tlossw.exceptions;

public class XSLLoadException extends TlosException {

	private static final long serialVersionUID = -7579462910001969483L;

	public XSLLoadException() {
		// TODO Auto-generated constructor stub
	}

	public XSLLoadException(String arg0, Throwable arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}

	public XSLLoadException(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public XSLLoadException(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

}


text:
<?php

namespace ZeldaBundle\Repository;

/**
 * RecetteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RecetteRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
require 'rails_helper'

describe "Tags" do
  before do
    SiteSetting.tagging_enabled = true
  end

  describe "checking tag hashtags" do
    let(:tag) { Fabricate(:tag, name: 'test') }

    it "should return the right response" do
      get "/tags/check.json", { tag_values: [tag.name] }

      expect(response).to be_success

      tag = JSON.parse(response.body)["valid"].first
      expect(tag["value"]).to eq('test')
    end
  end
end


text:
The message is "
"


text:
$(function(){
	$('#report').footable();

	// If window viewport is a small screen
	if($(window).width() <= 528){
		if($('#paginationContainer ul li').length >= 6){
			// $('#paginationContainer').parent().removeAttr('style');
			$('#printReportButton').hide();
			$('#viewMoreResults').show();
		}
	} else {
		if($('#paginationContainer ul li').length >= 6){
			$('#printReportButton').show();
			$('#viewMoreResults').hide();
		}
	}

	// When the viewport window resizes
	$(window).resize(function(){
		// Check viewport window size
		var windowSize = $(window).width();
		// If the viewport window size is a small screen
		if(windowSize <= 528){
			if($('#paginationContainer ul li').length >= 6){
				// $('#paginationContainer').parent().removeAttr('style');
				$('#printReportButton').hide();
				$('#viewMoreResults').show();
			}
		} else {
			if($('#paginationContainer ul li').length >= 6){
				$('#printReportButton').show();
				$('#viewMoreResults').hide();
			}
		}
	});
});

// Tabbed Example
$(function(){
	$('#tabTable').footable();

	// If window viewport is a small screen
	if($(window).width() <= 528){
		if($('#paginationContainer ul li').length >= 6){
			// $('#paginationContainer').parent().removeAttr('style');
			$('#printReportButton').hide();
			$('#viewMoreResults').show();
		}
	} else {
		if($('#paginationContainer ul li').length >= 6){
			$('#printReportButton').show();
			$('#viewMoreResults').hide();
		}
	}

	// When the viewport window resizes
	$(window).resize(function(){
		// Check viewport window size
		var windowSize = $(window).width();
		// If the viewport window size is a small screen
		if(windowSize <= 528){
			if($('#paginationContainer ul li').length >= 6){
				// $('#paginationContainer').parent().removeAttr('style');
				$('#printReportButton').hide();
				$('#viewMoreResults').show();
			}
		} else {
			if($('#paginationContainer ul li').length >= 6){
				$('#printReportButton').show();
				$('#viewMoreResults').hide();
			}
		}
	});
});


text:
'use strict';

var chalk = require('chalk');
var jsdom = require('jsdom');
var cheerio = require('cheerio');
var wat = require('workshopper-wat');
var jquery = require('../../lib/jquery');
var exercise = wat({ verify: verify });

module.exports = exercise;

function verify (t, req, res) {
  var body = res.body;
  var $ = cheerioOrBail();
  if ($ === void 0) {
    return;
  }

  t.fgroup('sanity');

  var scripts = $('script');
  if (scripts.length === 0) {
    t.ffail('empty', { tag: 'script' });
  }
  var styles = $('link[rel="stylesheet"]');
  if (styles.length === 0) {
    t.ffail('empty', { tag: 'link' });
  }

  t.groupend();

  var scriptSources = [];
  var linkSources = [];

  scripts.each(validateScript);
  styles.each(validateStyle);

  console.log(exercise.__('boot_jsdom', { process: chalk.yellow('jsdom') }));
  jsdom.env({
    html: body,
    src: [jquery],
    features: {
      FetchExternalResources: ['script'],
      ProcessExternalResources: ['script']
    },
    done: domloaded
  });

  function validateScript () {
    var el = $(this);
    var nonblocking = !!el.attr('async');
    var src = el.attr('src');
    if (src) {
      t.fgroup('script', { src: src });
      if (scriptSources.indexOf(src) !== -1) {
        t.ffail('dupe', { tag: 'script' }); return;
      }
      scriptSources.push(src);
      t.fpass('body', el.parent().is('body'));
      t.fpass('bottom', el.nextAll().length === el.nextAll('script').length);
      t.fpass('async', nonblocking);
      t.groupend();
    }
  }

  function validateStyle () {
    var el = $(this);
    var href = el.attr('href');
    t.fgroup('link', { href: href });
    t.fpass('noscript', el.parent().is('noscript'));
    linkSources.push(href);
    t.groupend();
  }

  function cheerioOrBail () {
    try {
      return cheerio.load(body);
    } catch (err) {
      t.end(err);
    }
  }

  function domloaded (err, window) {
    if (err) {
      t.error(err.length ? err[0] : err); return;
    }
    var $ = window.$;
    linkSources.forEach(verifyLink);
    t.end();

    function verifyLink (href) {
      t.fgroup('link', { href: href });

      var links = $('link').filter(byLinkAndMedia);
      if (links.length === 0) {
        t.ffail('noloadcss');
      } else if (links.length > 1) {
        t.ffail('dupe', { tag: 'link' });
      } else {
        t.fpass('deferred', links.attr('media') === 'all');
      }
      t.groupend();

      function byLinkAndMedia () {
        var el = $(this);
        var matches = el.attr('href') === href;
        return matches;
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
	android:initialLayout="@layout/appwidget"
	android:previewImage="@drawable/widget_running"
	android:resizeMode="none"
	android:updatePeriodMillis="0"
	android:minHeight="40dp"
	android:minResizeHeight="40dp"
	android:minResizeWidth="40dp"
	android:minWidth="40dp" />


text:
layout: post
title: Hot Bitch Gets Fucked By Conny Dachs
titleinfo: pornvd
desc: Watch Hot Bitch Gets Fucked By Conny Dachs. Pornhub is the ultimate xxx porn and sex site.
---

Hot Bitch Gets Fucked By Conny Dachs

Watch Hot Bitch Gets Fucked By Conny Dachs. Pornhub is the ultimate xxx porn and sex site.


text:
require 'shoulda'
require File.dirname(__FILE__) + '/acts_as_state_machine/macros_old' unless defined?(AASM)
require File.dirname(__FILE__) + '/acts_as_state_machine/macros_new' if defined?(AASM)

Test::Unit::TestCase.class_eval do
  extend Woulda::ActsAsStateMachine::Macros
end


text:
<?php

namespace OpenCFP\Domain\Services;

use Cartalyst\Sentry\Sentry;
use Cartalyst\Sentry\Users\UserNotActivatedException;
use Cartalyst\Sentry\Users\UserNotFoundException;

class Login
{
    /**
     * @var Sentry
     */
    private $sentry;

    /**
     * @var string
     */
    private $authenticationMessage = '';

    /**
     * @param Sentry $sentry
     */
    public function __construct($sentry)
    {
        $this->sentry = $sentry;
    }

    /**
     * @param string $user
     * @param string $password
     *
     * @return bool
     */
    public function authenticate($user, $password)
    {
        if (empty($user) || empty($password)) {
            $this->authenticationMessage = "Missing Email or Password";

            return false;
        }

        try {
            $this->sentry->authenticate(
                [
                    'email'=>$user,
                    'password'=>$password,
                ],
                false
            );
        } catch (UserNotFoundException $e) {
            $this->authenticationMessage = "Invalid Email or Password";

            return false;
        } catch (UserNotActivatedException $e) {
            $this->authenticationMessage = "Your account hasn't been activated. Did you get the activation email?";

            return false;
        }

        return true;
    }

    /**
     * @return array
     */
    public function getViewVariables()
    {
        $variables = [];
        if (isset($_REQUEST['email']) && (isset($_REQUEST['passwd']))) {
            if (!$this->authenticate($_REQUEST['email'], $_REQUEST['passwd'])) {
                $variables['errorMessage'] = $this->getAuthenticationMessage();
                $variables['email'] = $_REQUEST['email'];
            } else {
                $variables['redirect'] = '/dashboard';
            }
        }

        return $variables;
    }

    /**
     * @return string
     */
    public function getAuthenticationMessage()
    {
        return $this->authenticationMessage;
    }
}


text:
<?php
$this->breadcrumbs=array(
    'Program Studis'=>array('index'),
    $programStudi->id,
);

$this->menu=array(
    array('label'=>Yii::t('app','List Program Studi'), 'url'=>array('index')),
    array('label'=>Yii::t('app','Create Program Studi'), 'url'=>array('create')),
    array('label'=>Yii::t('app','Update Program Studi'), 'url'=>array('update', 'id'=>$programStudi->id)),
    array('label'=>Yii::t('app','Delete Program Studi'), 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$programStudi->id),'confirm'=>'Are you sure you want to delete this item?')),
);
?>

<?php echo Yii::t('app','View Program Studi') ?>

<?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$programStudi,
    'attributes'=>array(
        'id',
        'nama',
        'kode',
        array(
            'name' => 'jurusanId',
            'value' => $programStudi->jurusan->nama,
        ),
        array(
            'name' => 'fakultasId',
            'value' => $programStudi->fakultas->nama,
        ),
        'created',
        'modified',
    ),
)); ?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?= $title ?></title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="Cannes film Festival Dataviz">
    <meta name="author" content="Team20 ©2016">
    <link rel="favicon" href="#">

    <link href="./css/style.css" rel="stylesheet">

  <body class="page-<?= $class ?>">

Cannes
Retrospective

You have to go on desktop to view this experience


text:
<html>
    <head>
        <script src="https://cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
        <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/libs/stats.min.js"></script>

        <script src="https://cdn.rawgit.com/jeromeetienne/threex.laser/master/threex.laserbeam.js"></script>
    </head>
    <body style="margin: 0px; overflow: hidden;">
        <script src="js/index.1.0.1.js"></script>
    </body>
</html>


text:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
the 6th prime is 13.

If your language provides methods in the standard library to deal with prime
numbers, pretend it doesn't exist and implement it yourself.


text:
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".

import socket from "./socket"

// Make each door lock status icon clickable to unlock that door
$.each(door_ids, (i, door_id) => {
  $('.door_lock_'+door_id+'_status').on('click', (ev) => {
    $.get($(ev.currentTarget).attr('href'))
    return false
  })
})

$.each(preScheduledRows, (i, preScheduledRow) => {
  addScheduleRow(...preScheduledRow)
})
$('button#add_schedule').click(function(ev) {
  addScheduleRow()
  ev.preventDefault()
})


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_COntroller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/welcome
	 *	- or -
	 * 		http://example.com/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index(){
		$this->load->library('session');
		$val = 'false';
        if ( $this->session->has_userdata('empleado') ) {
        	$val = 'true';
        }
        $this->load->model('Plan_model', '', TRUE);
        $data['planes'] = $this->Plan_model->mostrarPlanesPrincipal( 1 );
        $data['logueado'] = $val;
        $data['msg'] = (isset($_GET['msg']))?$_GET['msg']:'';
        // print_r( $data );
        $this->twiggy->set($data, NULL, TRUE);
        $this->twiggy->template('/landing/index')->display();
	}

    /*
        Mensajes
    */
    public function dudas(){
        $this->load->model('Dudas_mensajes_model','', TRUE);
        $this->Dudas_mensajes_model->agregaMensaje( $_POST['nombre'], $_POST['correo'], $_POST['mensaje'] );
    }
}


text:
DROP TABLE IF EXISTS book;
DROP VIEW IF EXISTS view_book_titles;

CREATE TABLE book
(
    id INTEGER NOT NULL AUTO_INCREMENT COMMENT 'Book Id',
    title VARCHAR(255) NOT NULL COMMENT 'Book Title with accent éài',
    isbn VARCHAR(24) NOT NULL COMMENT 'ISBN Number',
    price FLOAT COMMENT 'Price of the book.',
    PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='Book Table';

CREATE VIEW view_book_titles AS SELECT title FROM book;

DROP TABLE IF EXISTS foo;

CREATE TABLE foo (
  `longitude` decimal(10,7) NOT NULL
) ENGINE=InnoDB;


text:
#include "cppmicroservices/Any.h"
#include "Utils.h"

#include <stdexcept>

namespace cppmicroservices {

namespace detail {

void ThrowBadAnyCastException(const std::string& funcName,
                              const std::type_info& source,
                              const std::type_info& target)
{
  std::string msg("cppmicroservices::BadAnyCastException: ");
  std::string targetTypeName(GetDemangledName(target));
  std::string sourceTypeName(GetDemangledName(source));
  msg += funcName + ": Failed to convert from cppmicroservices::Any type " +
         sourceTypeName + " to target type " + targetTypeName;
  throw BadAnyCastException(msg);
}
}

std::ostream& any_value_to_string(std::ostream& os, const Any& any)
{
  os << any.ToString();
  return os;
}

std::ostream& any_value_to_json(std::ostream& os, const Any& val)
{
  os << val.ToJSON();
  return os;
}

std::ostream& any_value_to_json(std::ostream& os, const std::string& val)
{
  return os << '"' << val << '"';
}

std::ostream& any_value_to_json(std::ostream& os, bool val)
{
  return os << (val ? "true" : "false");
}

// The default constructor implementation needs to be in the implementation file, not the
// header in order to avoid this error:
// "default initialization of an object of const type 'const cppmicroservices::Any' without
// a user-provided default constructor"
Any::Any() = default;

std::string Any::ToString() const
{
  if (Empty()) {
    throw std::logic_error("empty any");
  }
  return _content->ToString();
}

std::string Any::ToStringNoExcept() const
{
  return Empty() ? std::string() : _content->ToString();
}
}


text:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>install-linux</id>
    <formats>
        <format>tar.gz</format>
    </formats>
    <dependencySets>
        <dependencySet>
            <scope>runtime</scope>
            <outputDirectory>java</outputDirectory>
            <useProjectArtifact>false</useProjectArtifact>
            <unpack>false</unpack>
            <outputFileNameMapping>${artifact.artifactId}.${artifact.extension}</outputFileNameMapping>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>${root.basedir}</directory>
            <outputDirectory>.</outputDirectory>
            <includes>
                <include>README*</include>
                <include>LICENSE*</include>
                <include>NOTICE*</include>
            </includes>
        </fileSet>
        <fileSet>
            <directory>${project.basedir}/src/main/plsql</directory>
            <outputDirectory>plsql</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${project.basedir}/src/main/scripts</directory>
            <outputDirectory>.</outputDirectory>
            <includes>
                <include>*.sh</include>
            </includes>
            <fileMode>0755</fileMode>
        </fileSet>
        <fileSet>
            <directory>${project.basedir}/src/main/scripts</directory>
            <outputDirectory>.</outputDirectory>
            <excludes>
                <exclude>*.sh</exclude>
                <exclude>*.bat</exclude>
            </excludes>
        </fileSet>
        <fileSet>
            <directory>${root.basedir}/ftldb/target/site/apidocs</directory>
            <outputDirectory>doc/java</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${project.build.directory}/site/sql-apidocs</directory>
            <outputDirectory>doc/plsql</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>