text:
from __future__ import unicode_literals
import frappe, json
from frappe.oauth import OAuthWebRequestValidator, WebApplicationServer
from oauthlib.oauth2 import FatalClientError, OAuth2Error
from werkzeug import url_fix
from six.moves.urllib.parse import quote, urlencode, urlparse
from frappe.integrations.doctype.oauth_provider_settings.oauth_provider_settings import get_oauth_settings
from frappe import _

def get_oauth_server():
	if not getattr(frappe.local, 'oauth_server', None):
		oauth_validator = OAuthWebRequestValidator()
		frappe.local.oauth_server  = WebApplicationServer(oauth_validator)

	return frappe.local.oauth_server

def get_urlparams_from_kwargs(param_kwargs):
	arguments = param_kwargs
	if arguments.get("data"):
		arguments.pop("data")
	if arguments.get("cmd"):
		arguments.pop("cmd")

	return urlencode(arguments)

@frappe.whitelist()
def approve(*args, **kwargs):
	r = frappe.request
	uri = url_fix(r.url.replace("+"," "))
	http_method = r.method
	body = r.get_data()
	headers = r.headers

	try:
		scopes, frappe.flags.oauth_credentials = get_oauth_server().validate_authorization_request(uri, http_method, body, headers)

		headers, body, status = get_oauth_server().create_authorization_response(uri=frappe.flags.oauth_credentials['redirect_uri'], \
				body=body, headers=headers, scopes=scopes, credentials=frappe.flags.oauth_credentials)
		uri = headers.get('Location', None)

		frappe.local.response["type"] = "redirect"
		frappe.local.response["location"] = uri

	except FatalClientError as e:
		return e
	except OAuth2Error as e:
		return e

@frappe.whitelist(allow_guest=True)
def authorize(*args, **kwargs):
	#Fetch provider URL from settings
	oauth_settings = get_oauth_settings()
	params = get_urlparams_from_kwargs(kwargs)
	request_url = urlparse(frappe.request.url)
	success_url = request_url.scheme + "://" + request_url.netloc + "/api/method/frappe.integrations.oauth2.approve?" + params
	failure_url = frappe.form_dict["redirect_uri"] + "?error=access_denied"

	if frappe.session['user']=='Guest':
		#Force login, redirect to preauth again.
		frappe.local.response["type"] = "redirect"
		frappe.local.response["location"] = "/login?redirect-to=/api/method/frappe.integrations.oauth2.authorize?" + quote(params.replace("+"," "))

	elif frappe.session['user']!='Guest':
		try:
			r = frappe.request
			uri = url_fix(r.url)
			http_method = r.method
			body = r.get_data()
			headers = r.headers

			scopes, frappe.flags.oauth_credentials = get_oauth_server().validate_authorization_request(uri, http_method, body, headers)

			skip_auth = frappe.db.get_value("OAuth Client", frappe.flags.oauth_credentials['client_id'], "skip_authorization")
			unrevoked_tokens = frappe.get_all("OAuth Bearer Token", filters={"status":"Active"})

			if skip_auth or (oauth_settings["skip_authorization"] == "Auto" and len(unrevoked_tokens)):

				frappe.local.response["type"] = "redirect"
				frappe.local.response["location"] = success_url
			else:
				#Show Allow/Deny screen.
				response_html_params = frappe._dict({
					"client_id": frappe.db.get_value("OAuth Client", kwargs['client_id'], "app_name"),
					"success_url": success_url,
					"failure_url": failure_url,
					"details": scopes
				})
				resp_html = frappe.render_template("templates/includes/oauth_confirmation.html", response_html_params)
				frappe.respond_as_web_page("Confirm Access", resp_html)

		except FatalClientError as e:
			return e
		except OAuth2Error as e:
			return e

@frappe.whitelist(allow_guest=True)
def get_token(*args, **kwargs):
	r = frappe.request

	uri = url_fix(r.url)
	http_method = r.method
	body = r.form
	headers = r.headers

	#Check whether frappe server URL is set
	frappe_server_url = frappe.db.get_value("Social Login Key", "frappe", "base_url") or None
	if not frappe_server_url:
		frappe.throw(_("Please set Base URL in Social Login Key for Frappe"))

	try:
		headers, body, status = get_oauth_server().create_token_response(uri, http_method, body, headers, frappe.flags.oauth_credentials)
		out = frappe._dict(json.loads(body))
		if not out.error and "openid" in out.scope:
			token_user = frappe.db.get_value("OAuth Bearer Token", out.access_token, "user")
			token_client = frappe.db.get_value("OAuth Bearer Token", out.access_token, "client")
			client_secret = frappe.db.get_value("OAuth Client", token_client, "client_secret")
			if token_user in ["Guest", "Administrator"]:
				frappe.throw(_("Logged in as Guest or Administrator"))
			import hashlib
			id_token_header = {
				"typ":"jwt",
				"alg":"HS256"
			}
			id_token = {
				"aud": token_client,
				"exp": int((frappe.db.get_value("OAuth Bearer Token", out.access_token, "expiration_time") - frappe.utils.datetime.datetime(1970, 1, 1)).total_seconds()),
				"sub": frappe.db.get_value("User Social Login", {"parent":token_user, "provider": "frappe"}, "userid"),
				"iss": frappe_server_url,
				"at_hash": frappe.oauth.calculate_at_hash(out.access_token, hashlib.sha256)
			}
			import jwt
			id_token_encoded = jwt.encode(id_token, client_secret, algorithm='HS256', headers=id_token_header)
			out.update({"id_token":str(id_token_encoded)})
		frappe.local.response = out

	except FatalClientError as e:
		return e

@frappe.whitelist(allow_guest=True)
def revoke_token(*args, **kwargs):
	r = frappe.request
	uri = url_fix(r.url)
	http_method = r.method
	body = r.form
	headers = r.headers

	headers, body, status = get_oauth_server().create_revocation_response(uri, headers=headers, body=body, http_method=http_method)

	frappe.local.response['http_status_code'] = status
	if status == 200:
		return "success"
	else:
		return "bad request"

@frappe.whitelist()
def openid_profile(*args, **kwargs):
	picture = None
	first_name, last_name, avatar, name = frappe.db.get_value("User", frappe.session.user, ["first_name", "last_name", "user_image", "name"])
	frappe_userid = frappe.db.get_value("User Social Login", {"parent":frappe.session.user, "provider": "frappe"}, "userid")
	request_url = urlparse(frappe.request.url)
	base_url = frappe.db.get_value("Social Login Key", "frappe", "base_url") or None

	if avatar:
		if validate_url(avatar):
			picture = avatar
		elif base_url:
			picture = base_url + '/' + avatar
		else:
			picture = request_url.scheme + "://" + request_url.netloc + avatar

	user_profile = frappe._dict({
			"sub": frappe_userid,
			"name": " ".join(filter(None, [first_name, last_name])),
			"given_name": first_name,
			"family_name": last_name,
			"email": name,
			"picture": picture
		})

	frappe.local.response = user_profile

def validate_url(url_string):
	try:
		result = urlparse(url_string)
		if result.scheme and result.scheme in ["http", "https", "ftp", "ftps"]:
			return True
		else:
			return False
	except:
		return False


text:
<?php
/*
The following file enables the uploading of each image from the java applet.

PLEASE NOTE, THIS FILES IN ITS PRESENT FORM IS A MASSIVE SECURITY RISK, AND
SHOULD NOT BE USED WITHOUT DOING EITHER OF THE FOLLOWING:

- PROTECTING THE ACCESS OF THE FILE BY THE USE OF SESSION VARIABLES (DO NOT
  PROTECT IT BY USING HTTP PASSWORDS)
- ENSURING THAT UPLOADED FILES ARE NOT ACCESSIBLE TO THE WEB (UPLOAD FILES
  TO A DIRECTORY ABOVE THE DOCUMENT ROOT)
*/

/*
AS OF POSTLET 0.11, POSTLET READS THE MESSAGES SENT BACK TO IT, AND NOW
IS AWARE OF WHETHER OR NOT AN UPLOAD HAS BEEN SUCCESSFUL. MORE INFORMATION
ABOUT THE FORMAT OF REPLY MESSAGES CAN BE FOUND ON THE POSTLET WEBSITE
http://www.postlet.com/install/
*/

// Configuration ---------------------------------------------------------------
// Change the below path to the folder where you would like files uploading.
// e.g. "/home/yourname/myuploads/"
// or "c:\php\uploads\"
// Note, this MUST have the trailing slash.
$uploaddir = '../../zona_descargas/software/temp/';
// Whether or not to allow the upload of specific files
$allow_or_deny = true;
// If the above is true, then this states whether the array of files is a list of
// extensions to ALLOW, or DENY
$allow_or_deny_method = "deny"; // "allow" or "deny"
$file_extension_list = array("php","asp","pl");
// -----------------------------------------------------------------------------
if ($allow_or_deny){
	if (($allow_or_deny_method == "allow" && !in_array(strtolower(array_pop(explode('.', $_FILES['userfile']['name']))), $file_extension_list))
		|| ($allow_or_deny_method == "deny" && in_array(strtolower(array_pop(explode('.', $_FILES['userfile']['name']))), $file_extension_list))){
		// Atempt to upload a file with a specific extension when NOT allowed.
		// 403 error
		header("HTTP/1.1 403 Forbidden");
		echo "POSTLET REPLY\r\n";
		echo "POSTLET:NO\r\n";
		echo "POSTLET:FILE TYPE NOT ALLOWED\r\n";
		echo "POSTLET:ABORT THIS\r\n"; // Postlet should NOT send this file again.
		echo "END POSTLET REPLY\r\n";
		exit;
	}
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir .$_FILES['userfile']['name']))
{
	// All replies MUST start with "POSTLET REPLY", if they don't, then Postlet will
	// not read the reply and will assume the file uploaded successfully.
	echo "POSTLET REPLY\r\n";
	// "YES" tells Postlet that this file was successfully uploaded.
    echo "POSTLET:YES\r\n";
	// End the Postlet reply
	echo "END POSTLET REPLY\r\n";
	exit;
}
else
{
	// If the file can not be uploaded (most likely due to size), then output the
	// correct error code
	// If $_FILES is EMPTY, or $_FILES['userfile']['error']==1 then TOO LARGE
	if (count($_FILES)==0 || $_FILES['userfile']['error']==1){
		// All replies MUST start with "POSTLET REPLY", if they don't, then Postlet will
		// not read the reply and will assume the file uploaded successfully.
		header("HTTP/1.1 413 Request Entity Too Large");
		echo "POSTLET REPLY\r\n";
		echo "POSTLET:NO\r\n";
		echo "POSTLET:TOO LARGE\r\n";
		echo "POSTLET:ABORT THIS\r\n"; // Postlet should NOT send this file again.
		echo "END POSTLET REPLY\r\n";
		exit;
	}
	// Unable to write the file to the server ALL WILL FAIL
	else if ($_FILES['userfile']['error']==6 || $_FILES['userfile']['error']==7){
		// All replies MUST start with "POSTLET REPLY", if they don't, then Postlet will
		// not read the reply and will assume the file uploaded successfully.
		header("HTTP/1.1 500 Internal Server Error");
		echo "POSTLET REPLY\r\n";
		echo "POSTLET:NO\r\n";
		echo "POSTLET:SERVER ERROR\r\n";
		echo "POSTLET:ABORT ALL\r\n"; // Postlet should NOT send any more files
		echo "END POSTLET REPLY\r\n";
		exit;
	}
	// Unsure of the error here (leaves 2,3,4, which means try again)
	else {
		// All replies MUST start with "POSTLET REPLY", if they don't, then Postlet will
		// not read the reply and will assume the file uploaded successfully.
		header("HTTP/1.1 500 Internal Server Error");
		echo "POSTLET REPLY\r\n";
		echo "POSTLET:NO\r\n";
		echo "POSTLET:UNKNOWN ERROR\r\n";
		echo "POSTLET:RETRY\r\n";
		print_r($_REQUEST); // Possible usefull for debugging
		echo "END POSTLET REPLY\r\n";
		exit;
	}
}
?>

redpajama_set_name: RedPajamaGithub


text:
import java.util.ArrayList;

public class Node {
	int stateNum;
	String word;

	ArrayList<Integer> next;
	ArrayList<Integer> prev;

	ArrayList<Double> alpha;
	ArrayList<Double> beta;

	//HashMap<String, Double> tagScores;
	ArrayList<Double> tagScores;

	boolean isEndState;
	boolean isStartState;

	public Node(){

	}

	public Node(int stateNum, String word) {
		this.stateNum = stateNum;
		this.word = word;

		this.next = new ArrayList<>();
		this.prev = new ArrayList<>();

		this.alpha = new ArrayList<>();
		this.beta = new ArrayList<>();

		//this.tagScores = new HashMap<>();
		this.tagScores = new ArrayList<>();

		if(stateNum == 0){
			this.isStartState = true;
		}
		else{
			this.isStartState = false;
		}

		this.isEndState = false;
	}

	@Override
	public String toString() {
		return stateNum + ": " + word + " alpha: " + this.alpha;//" (next: " + next + " | prev: " + prev + ") ";
	}

}


text:
/* IBM_PROLOG_BEGIN_TAG */
/*
 * Copyright 2003,2016 IBM International Business Machines Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 		 http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* IBM_PROLOG_END_TAG */

/* @(#)36	1.6  src/htx/usr/lpp/htx/bin/hxecd/prt_msg.c, exer_cd, htxubuntu 5/24/04 17:24:55 */

/******************************************************************************
 *   COMPONENT_NAME: exer_cd
 *
 *   MODULE NAME: prt_msg.c
 *
 *   FUNCTIONS: info_msg
 *              prt_msg
 *              prt_msg_asis
 *
 *   DESCRIPTION: Functions to format messages and send to HTX.
 ******************************************************************************/
#include <string.h>
#include "hxecd.h"

/**************************************************************************/
/* format information message                                             */
/**************************************************************************/
info_msg(ps,pr,loop,blkno,msg_text)
struct htx_data *ps;
struct ruleinfo *pr;
int  loop;
int  *blkno;
char *msg_text;
{
  sprintf(msg_text, "%s: loop = %5d,  blk = %5d, len = %4d\n",
          pr->rule_id, loop, blkno[0], pr->dlen);
  return;
}

/**************************************************************************/
/* send message to HTX                                                    */
/**************************************************************************/
prt_msg(ps,pr,loop,blkno,err,sev,text)
struct htx_data *ps;
struct ruleinfo *pr;
int  loop;
int  *blkno;
int  err;
int  sev;
char *text;
{
  char msg[550];

  info_msg(ps, pr, loop, blkno, msg);
  strcat(msg, text);
  if ( err <= sys_nerr )
     strcat(msg, sys_errlist[err]);
  hxfmsg(ps, err, sev, msg);
  return;
}

/****************************************************************/
/* Send message to HTX as-is to bypass system error messages    */
/****************************************************************/
prt_msg_asis(phtx_info,prule_info,loop,pblk_num,err,sev,text)
struct htx_data *phtx_info;
struct ruleinfo *prule_info;
struct blk_num_typ *pblk_num;
int  loop;
int  err;
int  sev;
char *text;
{
  char msg[550];

  info_msg(phtx_info, prule_info, loop, pblk_num, msg);
  strncat(msg, text, (sizeof(msg) - strlen(msg)) );
  hxfmsg(phtx_info, err, sev, msg);
  return;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>JSPDemo4_Cookie</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  	<servlet-name>login</servlet-name>
  	<servlet-class>web.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>login</servlet-name>
  	<url-pattern>/main/login</url-pattern>
  </servlet-mapping>

  <servlet>
  	<servlet-name>index</servlet-name>
  	<servlet-class>web.IndexServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>index</servlet-name>
  	<url-pattern>/main/index</url-pattern>
  </servlet-mapping>

  <servlet>
  	<servlet-name>find</servlet-name>
  	<servlet-class>web.CostServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>find</servlet-name>
  	<url-pattern>/cost/find</url-pattern>
  </servlet-mapping>
</web-app>


text:
"use strict";
var Promise = require('bluebird');

var helper = require(__dirname + '/helper.js');
var Connection = require(__dirname + '/connection.js');
var Term = require(__dirname + '/term.js');
var errors = require(__dirname + '/error.js');
var PoolMaster = require(__dirname + '/pool_master.js');
var termTypes = require(__dirname + '/protodef.js').Term.TermType;

function r() {
  var self = this;      // jshint ignore:line
  var _r = function(x) {
    return new Term(_r).expr(x);
  };
  helper.changeProto(_r, self);

  Term.prototype._setNestingLevel(r.prototype.nestingLevel);
  Term.prototype._setArrayLimit(r.prototype.arrayLimit);

  _r.row = new Term(_r).row();

  _r.monday = new Term(_r).monday();
  _r.tuesday = new Term(_r).tuesday();
  _r.wednesday = new Term(_r).wednesday();
  _r.thursday = new Term(_r).thursday();
  _r.friday = new Term(_r).friday();
  _r.saturday = new Term(_r).saturday();
  _r.sunday = new Term(_r).sunday();

  _r.january = new Term(_r).january();
  _r.february = new Term(_r).february();
  _r.march = new Term(_r).march();
  _r.april = new Term(_r).april();
  _r.may = new Term(_r).may();
  _r.june = new Term(_r).june();
  _r.july = new Term(_r).july();
  _r.august = new Term(_r).august();
  _r.september = new Term(_r).september();
  _r.october = new Term(_r).october();
  _r.november = new Term(_r).november();
  _r.december = new Term(_r).december();
  _r.minval = new Term(_r).minval();
  _r.maxval = new Term(_r).maxval();

  _r.nextVarId = 1;
  _r._Term = Term;
  return _r;
}

r.prototype._host = 'localhost';
r.prototype._port = 28015;
r.prototype._authKey = '';
r.prototype._user = 'admin';
r.prototype._password = '';
r.prototype._timeoutConnect = 20; // seconds
r.prototype._pingInterval = -1; // seconds

r.prototype._nestingLevel = 100;
r.prototype._arrayLimit = 100000;
r.prototype._db = 'test';
r.prototype._useOutdated = false;
r.prototype._timeFormat = 'native';
r.prototype._profile = false;

r.prototype.setNestingLevel = function(nestingLevel) {
  if (typeof nestingLevel !== 'number') throw new errors.ReqlDriverError('The first argument of `setNestingLevel` must be a number.');
  this.nestingLevel = nestingLevel;
};

r.prototype.setArrayLimit = function(arrayLimit) {
  if (typeof arrayLimit !== 'number') throw new errors.ReqlDriverError('The first argument of `setArrayLimit` must be a number.');
  this.arrayLimit = arrayLimit;
};

r.prototype.connect = function(options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  var self = this;

  var p = new Promise(function(resolve, reject) {
    new Connection(self, options, resolve, reject);
  }).nodeify(callback);
  return p;
};

r.prototype.createPools = function(options) {
  this._poolMaster = new PoolMaster(this, options);
  return this;
};

r.prototype.getPoolMaster = function() {
  return this._poolMaster;
};

r.prototype.getPool = function(i) {
  if (i === undefined) {
    if (this.getPoolMaster().getPools().length === 1) {
      return this.getPoolMaster().getPools()[0];
    }
    else {
      throw new Error('You have multiple pools. Use `getPool(index)` or `getPools()`');
    }
  }
  else {
    return this.getPoolMaster().getPools()[i];
  }
};

r.prototype.expr = function(expression, nestingLevel) {
  if (Term.prototype._fastArityRange(arguments.length, 1, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'expr', this);
  }
  var _nestingLevel = nestingLevel || this.nestingLevel;
  return new Term(this).expr(expression, _nestingLevel);
};

r.prototype.db = function(db) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.db', this);
  }
  return new Term(this).db(db);
};

r.prototype.table = function(table, options) {
  if (Term.prototype._fastArityRange(arguments.length, 1, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'table', this);
  }
  return new Term(this).table(table, options);
};

r.prototype.js = function(jsString, options) {
  if (Term.prototype._fastArityRange(arguments.length, 1, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'r.js', this);
  }
  return new Term(this).js(jsString, options);
};

r.prototype.tableCreate = function(table, options) {
  if (Term.prototype._fastArityRange(arguments.length, 1, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'r.tableCreate', this);
  }
  return new Term(this).tableCreate(table, options);
};

r.prototype.tableDrop = function(db) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.tableDrop', this);
  }
  return new Term(this).tableDrop(db);
};

r.prototype.tableList = function() {
  if (Term.prototype._fastArity(arguments.length, 0) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 0, 'r.tableList', this);
  }
  return new Term(this).tableList();
};

r.prototype.dbCreate = function(db) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'dbCreate', this);
  }
  return new Term(this).dbCreate(db);
};

r.prototype.dbDrop = function(db) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'dbDrop', this);
  }
  return new Term(this).dbDrop(db);
};

r.prototype.dbList = function() {
  if (Term.prototype._fastArity(arguments.length, 0) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 0, 'dbList', this);
  }
  return new Term(this).dbList();
};

r.prototype.literal = function(obj) {
  if (Term.prototype._fastArityRange(arguments.length, 0, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'r.literal', this);
  }
  if (obj === undefined) {
    return new Term(this).literal();
  }
  else {
    return new Term(this).literal(obj);
  }
};

r.prototype.desc = function(field) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.desc', this);
  }
  return new Term(this).desc(field);
};

r.prototype.asc = function(field) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.asc', this);
  }
  return new Term(this).asc(field);
};

r.prototype.union = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}

  var term = new Term(this).expr(_args[0]);
  return term.union.apply(term, _args.slice(1));
};

r.prototype.add = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.add', this);

  var term = new Term(this).expr(_args[0]);
  return term.add.apply(term, _args.slice(1));
};

r.prototype.sub = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.sub', this);

  var term = new Term(this).expr(_args[0]);
  return term.sub.apply(term, _args.slice(1));
};

r.prototype.div = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.div', this);

  var term = new Term(this).expr(_args[0]);
  return term.div.apply(term, _args.slice(1));
};

r.prototype.mul = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.mul', this);

  var term = new Term(this).expr(_args[0]);
  return term.mul.apply(term, _args.slice(1));
};

r.prototype.mod = function(a, b) {
  if (Term.prototype._fastArity(arguments.length, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 2, 'r.mod', this);
  }

  return new Term(this).expr(a).mod(b);
};

r.prototype.and = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}

  var term = new Term(this);
  return term.and.apply(term, _args);
};

r.prototype.or = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}

  var term = new Term(this);
  return term.or.apply(term, _args);
};

r.prototype.eq = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.eq', this);

  var term = new Term(this).expr(_args[0]);
  return term.eq.apply(term, _args.slice(1));
};

r.prototype.ne = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.ne', this);

  var term = new Term(this).expr(_args[0]);
  return term.ne.apply(term, _args.slice(1));
};

r.prototype.gt = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.gt', this);

  var term = new Term(this).expr(_args[0]);
  return term.gt.apply(term, _args.slice(1));
};

r.prototype.ge = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.ge', this);

  var term = new Term(this).expr(_args[0]);
  return term.ge.apply(term, _args.slice(1));
};

r.prototype.lt = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.lt', this);

  var term = new Term(this).expr(_args[0]);
  return term.lt.apply(term, _args.slice(1));
};

r.prototype.le = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.le', this);

  var term = new Term(this).expr(_args[0]);
  return term.le.apply(term, _args.slice(1));
};

r.prototype.not = function(bool) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.not', this);
  }
  return new Term(this).expr(bool).not();
};

r.prototype.floor = function(num) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.floor', this);
  }
  return new Term(this).expr(num).floor();
};

r.prototype.ceil = function(num) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.ceil', this);
  }
  return new Term(this).expr(num).ceil();
};

r.prototype.round = function(num) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.round', this);
  }
  return new Term(this).expr(num).round();
};

r.prototype.now = function() {
  if (Term.prototype._fastArity(arguments.length, 0) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 0, 'now', this);
  }
  return new Term(this).now();
};

r.prototype.time = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  var term = new Term(this);
  return term.time.apply(term, _args);
};

r.prototype.epochTime = function(epochTime) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.epochTime', this);
  }
  return new Term(this).epochTime(epochTime);
};

r.prototype.ISO8601 = function(isoTime, options) {
  if (Term.prototype._fastArityRange(arguments.length, 1, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 1, 2, 'r.ISO8601', this);
  }
  return new Term(this).ISO8601(isoTime, options);
};

r.prototype.branch = function(predicate, trueBranch, falseBranch) {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 3, Infinity, 'r.branch', this);

  var term = new Term(this).expr(predicate);
  return term.branch.apply(term, _args.slice(1));
};

r.prototype.error = function(errorStr) {
  if (Term.prototype._fastArityRange(arguments.length, 0, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 0, 1, 'r.error', this);
  }
  var term = new Term(this);
  term._query.push(termTypes.ERROR);
  if (errorStr !== undefined) {
    term._query.push([new Term(this).expr(errorStr)._query]);
  }
  return term;
};

r.prototype.json = function(json) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.json', this);
  }
  return new Term(this).json(json);
};

r.prototype.object = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  var term = new Term(this);
  return term.object.apply(term, _args);
};

r.prototype.args = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  var term = new Term(this);
  return term.args.apply(term, _args);
};

r.prototype.random = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  var term = new Term(this);
  return term.random.apply(term, _args);
};

r.prototype.http = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  var term = new Term(this);
  return term.http.apply(term, _args);
};

r.prototype.do = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.do', this);

  var term = new Term(this).expr(_args[0]);
  return term.do.apply(term, _args.slice(1));
};

r.prototype.binary = function(bin) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.binary', this);
  }
  var term = new Term(this);
  return term.binary(bin);
};

r.prototype.uuid = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 0, 1, 'r.uuid', this);
  var term = new Term(this);
  return term.uuid(_args[0]);
};

r.prototype.line = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, Infinity, 'r.line', this);

  var term = new Term(this);
  return term.line.apply(term, _args);
};

r.prototype.point = function(longitude, latitude) {
  if (Term.prototype._fastArity(arguments.length, 2) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 2, 'r.point', this);
  }
  return new Term(this).point(longitude, latitude);
};

r.prototype.polygon = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 3, Infinity, 'r.polygon', this);

  var term = new Term(this);
  return term.polygon.apply(term, _args);
};

r.prototype.circle = function(center, radius, options) {
  if (Term.prototype._fastArityRange(arguments.length, 2, 3) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arityRange(_args, 2, 3, 'r.circle', this);
  }
  var term = new Term(this);
  if (options !== undefined) {
    return term.circle(center, radius, options);
  }
  else {
    return term.circle(center, radius);
  }
};

r.prototype.geojson = function(value) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.geojson', this);
  }
  var term = new Term(this);
  return term.geojson(value);
};

r.prototype.distance = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 2, 3, 'r.add', this);

  var term = new Term(this).expr(_args[0]);
  return term.distance.apply(term, _args.slice(1));
};

r.prototype.range = function(start, end) {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, 2, 'r.range', this);

  var term = new Term(this);
  if (end !== undefined) {
    return term.range(start, end);
  }
  else {
    return term.range(start);
  }
};

r.prototype.wait = function() {
  // `wait` on the top level has been removed in 2.3.
  throw new errors.ReqlDriverError('`wait` can only be called on a table or a database since 2.3');
};

r.prototype.reconfigure = function(config) {
  // `reconfigure` on the top level has been removed in 2.3.
  throw new errors.ReqlDriverError('`reconfigure` can only be called on a table or a database since 2.3');
};

r.prototype.rebalance = function(config) {
  // `rebalance` on the top level has been removed in 2.3.
  throw new errors.ReqlDriverError('`rebalance` can only be called on a table or a database since 2.3');
};

r.prototype.map = function() {
  var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.map', this);

  var term = new Term(this);
  return term.map.apply(term, _args);
};

r.prototype.typeOf = function(value) {
  if (Term.prototype._fastArity(arguments.length, 1) === false) {
    var _len = arguments.length;var _args = new Array(_len); for (var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
    Term.prototype._arity(_args, 1, 'r.typeOf', this);
  }
  var term = new Term(this);
  return term.expr(value).typeOf();
};

r.prototype.min = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.min', this);
  var term = new Term(this).expr(_args[0]);
  return term.min.apply(term, _args.slice(1));
};

r.prototype.max = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.max', this);
  var term = new Term(this).expr(_args[0]);
  return term.max.apply(term, _args.slice(1));
};

r.prototype.sum = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.sum', this);
  var term = new Term(this).expr(_args[0]);
  return term.sum.apply(term, _args.slice(1));
};

r.prototype.avg = function() {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.avg', this);
  var term = new Term(this).expr(_args[0]);
  return term.avg.apply(term, _args.slice(1));
};

r.prototype.distinct = function(value) {
  var _len = arguments.length;var _args = new Array(_len); for(var _i = 0; _i < _len; _i++) {_args[_i] = arguments[_i];}
  Term.prototype._arityRange(_args, 1, Infinity, 'r.distinct', this);
  var term = new Term(this).expr(_args[0]);
  return term.distinct.apply(term, _args.slice(1));
};

r.prototype.Error = Error;

function main(options) {
  var _r = new r(); // jshint ignore:line

  if (!helper.isPlainObject(options)) options = {};
  if (options.pool !== false) _r.createPools(options);
  _r._options = {};
  if (options.cursor === true) _r._options.cursor = true;
  if (options.stream === true) _r._options.stream = true;
  if (options.optionalRun === false) {
    delete _r._Term.prototype.then;
    delete _r._Term.prototype.error;
    delete _r._Term.prototype.catch;
    delete _r._Term.prototype.finally;
  }
  return _r;
}

module.exports = main;


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Ooui.Forms.Extensions;
using Xamarin.Forms;

namespace Ooui.Forms
{
    [Flags]
    public enum VisualElementRendererFlags
    {
        Disposed = 1 << 0,
        AutoTrack = 1 << 1,
        AutoPackage = 1 << 2
    }

    public class VisualElementRenderer<TElement> : Ooui.Element, IVisualElementRenderer where TElement : VisualElement
    {
        bool disposedValue = false; // To detect redundant calls

        readonly PropertyChangedEventHandler _propertyChangedHandler;

        public TElement Element { get; private set; }

        VisualElement IVisualElementRenderer.Element => Element;

        public Element NativeView => this;

        event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged {
            add { _elementChangedHandlers.Add (value); }
            remove { _elementChangedHandlers.Remove (value); }
        }

        readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers =
            new List<EventHandler<VisualElementChangedEventArgs>> ();

        VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;

        EventTracker _events;
        VisualElementPackager _packager;
        VisualElementTracker _tracker;

        protected bool AutoPackage {
            get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
            set {
                if (value)
                    _flags |= VisualElementRendererFlags.AutoPackage;
                else
                    _flags &= ~VisualElementRendererFlags.AutoPackage;
            }
        }

        protected bool AutoTrack {
            get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
            set {
                if (value)
                    _flags |= VisualElementRendererFlags.AutoTrack;
                else
                    _flags &= ~VisualElementRendererFlags.AutoTrack;
            }
        }

        protected override bool HtmlNeedsFullEndElement => TagName == "div";

        public VisualElementRenderer (string tagName = "div") : base (tagName)
        {
            Style.Overflow = "hidden";
            _propertyChangedHandler = OnElementPropertyChanged;
        }

        protected virtual void OnElementChanged (ElementChangedEventArgs<TElement> e)
        {
            var args = new VisualElementChangedEventArgs (e.OldElement, e.NewElement);
            for (int i = 0; i < _elementChangedHandlers.Count; i++) {
                _elementChangedHandlers[i] (this, args);
            }

            var changed = ElementChanged;
            if (changed != null)
                changed (this, e);
        }

        public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;

        void IVisualElementRenderer.SetElement (VisualElement element)
        {
            SetElement ((TElement)element);
        }

        public void SetElement (TElement element)
        {
            var oldElement = Element;
            Element = element;

            if (oldElement != null)
                oldElement.PropertyChanged -= _propertyChangedHandler;

            if (element != null) {
                if (element.BackgroundColor != Xamarin.Forms.Color.Default || (oldElement != null && element.BackgroundColor != oldElement.BackgroundColor))
                    SetBackgroundColor (element.BackgroundColor);

                if (_tracker == null) {
                    _tracker = new VisualElementTracker (this);
                    _tracker.NativeControlUpdated += (sender, e) => UpdateNativeWidget ();
                }

                if (AutoPackage && _packager == null) {
                	_packager = new VisualElementPackager (this);
                	_packager.Load ();
                }

                if (AutoTrack && _events == null) {
                	_events = new EventTracker (this);
                	_events.LoadEvents (this);
                }

                element.PropertyChanged += _propertyChangedHandler;
                ClassName = Element?.StyleId;
            }

            OnElementChanged (new ElementChangedEventArgs<TElement> (oldElement, element));

            if (element != null)
                SendVisualElementInitialized (element, this);

            if (Element != null && !string.IsNullOrEmpty (Element.AutomationId))
                SetAutomationId (Element.AutomationId);
        }

        public void SetElementSize (Size size)
        {
            Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion (Element, new Rectangle (Element.X, Element.Y, size.Width, size.Height));
        }

        public virtual void SetControlSize (Size size)
        {
        }

        protected virtual void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) {
                SetBackgroundColor (Element.BackgroundColor);
            }
            else if (e.PropertyName == Layout.IsClippedToBoundsProperty.PropertyName) {
                //UpdateClipToBounds ();
            }
            else if (e.PropertyName == "StyleId") {
                ClassName = Element?.StyleId;
            }
        }

        protected virtual void OnRegisterEffect (PlatformEffect effect)
        {
            //effect.Container = this;
        }

        protected virtual void SetAutomationId (string id)
        {
        }

        protected virtual void SetBackgroundColor (Xamarin.Forms.Color color)
        {
            Style.BackgroundColor = color.ToOouiColor (Colors.Clear);
        }

        protected virtual void UpdateNativeWidget ()
        {
        }

        protected virtual void SendVisualElementInitialized (VisualElement element, Element nativeView)
        {
            element.SendViewInitialized (nativeView);
        }

        public virtual SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
        {
            return NativeView.GetSizeRequest (widthConstraint, heightConstraint);
        }

        protected virtual void Dispose (bool disposing)
        {
            if (!disposedValue) {
                if (disposing) {
                }
                disposedValue = true;
            }
        }

        public void Dispose ()
        {
            Dispose (true);
        }
    }
}


text:
package net.emaze.dysfunctional.dispatching.composing;

import net.emaze.dysfunctional.contracts.dbc;
import java.util.function.BiPredicate;

/**
 * A composite binary predicate yielding true when the first predicate matches
 * (no further predicate is evaluated beyond the first returning true)
 *
 * @param <E1> the predicates first parameter type
 * @param <E2> the predicates second parameter type
 * @author rferranti
 */
public class FirstMatchingBinaryPredicate<E1, E2> implements BiPredicate<E1, E2> {

    private final Iterable<BiPredicate<E1, E2>> predicates;

    public FirstMatchingBinaryPredicate(Iterable<BiPredicate<E1, E2>> predicates) {
        dbc.precondition(predicates != null, "cannot evaluate or(...) of a null iterable of binary predicates");
        this.predicates = predicates;
    }

    @Override
    public boolean test(E1 first, E2 second) {
        for (BiPredicate<E1, E2> predicate : predicates) {
            if (predicate.test(first, second)) {
                return true;
            }
        }
        return false;
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode.snapshot;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockUnderConstructionFeature;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.datanode.*;
import org.apache.hadoop.hdfs.server.datanode.checker.DatasetVolumeChecker;
import org.apache.hadoop.hdfs.server.datanode.checker.ThrottledAsyncChecker;
import org.apache.hadoop.hdfs.server.namenode.*;
import org.apache.hadoop.hdfs.server.namenode.top.metrics.TopMetrics;
import org.apache.hadoop.http.HttpRequestLog;
import org.apache.hadoop.http.HttpServer2;
import org.apache.hadoop.ipc.ProtobufRpcEngine.Server;
import org.apache.hadoop.metrics2.impl.MetricsSystemImpl;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.GSet;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

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

/**
 * Helper for writing snapshot related tests
 */
public class SnapshotTestHelper {
  static final Logger LOG = LoggerFactory.getLogger(SnapshotTestHelper.class);

  /** Disable the logs that are not very useful for snapshot related tests. */
  public static void disableLogs() {
    final String[] lognames = {
        "org.apache.hadoop.hdfs.server.common.Util",
        "org.apache.hadoop.hdfs.server.blockmanagement.BlockReportLeaseManager",
        "org.apache.hadoop.hdfs.server.namenode.FileJournalManager",
        "org.apache.hadoop.hdfs.server.namenode.NNStorageRetentionManager",
        "org.apache.hadoop.hdfs.server.namenode.FSImageFormatProtobuf",
        "org.apache.hadoop.hdfs.server.namenode.FSEditLog",
        "org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceScanner",
        "org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.BlockPoolSlice",
        "org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl",
        "org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetAsyncDiskService",
        "org.apache.hadoop.hdfs.server.datanode.fsdataset.impl" +
            ".RamDiskAsyncLazyPersistService",
    };
    for(String n : lognames) {
      GenericTestUtils.disableLog(LoggerFactory.getLogger(n));
    }

    GenericTestUtils.disableLog(LoggerFactory.getLogger(
        UserGroupInformation.class));
    GenericTestUtils.disableLog(LoggerFactory.getLogger(BlockManager.class));
    GenericTestUtils.disableLog(LoggerFactory.getLogger(FSNamesystem.class));
    GenericTestUtils.disableLog(LoggerFactory.getLogger(
        DirectoryScanner.class));
    GenericTestUtils.disableLog(LoggerFactory.getLogger(
        MetricsSystemImpl.class));

    GenericTestUtils.disableLog(DatasetVolumeChecker.LOG);
    GenericTestUtils.disableLog(DatanodeDescriptor.LOG);
    GenericTestUtils.disableLog(GSet.LOG);
    GenericTestUtils.disableLog(TopMetrics.LOG);
    GenericTestUtils.disableLog(HttpRequestLog.LOG);
    GenericTestUtils.disableLog(ThrottledAsyncChecker.LOG);
    GenericTestUtils.disableLog(VolumeScanner.LOG);
    GenericTestUtils.disableLog(BlockScanner.LOG);
    GenericTestUtils.disableLog(HttpServer2.LOG);
    GenericTestUtils.disableLog(DataNode.LOG);
    GenericTestUtils.disableLog(BlockPoolSliceStorage.LOG);
    GenericTestUtils.disableLog(LeaseManager.LOG);
    GenericTestUtils.disableLog(NameNode.stateChangeLog);
    GenericTestUtils.disableLog(NameNode.blockStateChangeLog);
    GenericTestUtils.disableLog(DFSClient.LOG);
    GenericTestUtils.disableLog(Server.LOG);
  }

  private SnapshotTestHelper() {
    // Cannot be instantinatied
  }

  public static Path getSnapshotRoot(Path snapshottedDir, String snapshotName) {
    return new Path(snapshottedDir, HdfsConstants.DOT_SNAPSHOT_DIR + "/"
        + snapshotName);
  }

  public static Path getSnapshotPath(Path snapshottedDir, String snapshotName,
      String fileLocalName) {
    return new Path(getSnapshotRoot(snapshottedDir, snapshotName),
        fileLocalName);
  }

  /**
   * Create snapshot for a dir using a given snapshot name
   *
   * @param hdfs DistributedFileSystem instance
   * @param snapshotRoot The dir to be snapshotted
   * @param snapshotName The name of the snapshot
   * @return The path of the snapshot root
   */
  public static Path createSnapshot(DistributedFileSystem hdfs,
      Path snapshotRoot, String snapshotName) throws Exception {
    LOG.info("createSnapshot " + snapshotName + " for " + snapshotRoot);
    assertTrue(hdfs.exists(snapshotRoot));
    hdfs.allowSnapshot(snapshotRoot);
    hdfs.createSnapshot(snapshotRoot, snapshotName);
    // set quota to a large value for testing counts
    hdfs.setQuota(snapshotRoot, Long.MAX_VALUE-1, Long.MAX_VALUE-1);
    return SnapshotTestHelper.getSnapshotRoot(snapshotRoot, snapshotName);
  }

  /**
   * Check the functionality of a snapshot.
   *
   * @param hdfs DistributedFileSystem instance
   * @param snapshotRoot The root of the snapshot
   * @param snapshottedDir The snapshotted directory
   */
  public static void checkSnapshotCreation(DistributedFileSystem hdfs,
      Path snapshotRoot, Path snapshottedDir) throws Exception {
    // Currently we only check if the snapshot was created successfully
    assertTrue(hdfs.exists(snapshotRoot));
    // Compare the snapshot with the current dir
    FileStatus[] currentFiles = hdfs.listStatus(snapshottedDir);
    FileStatus[] snapshotFiles = hdfs.listStatus(snapshotRoot);
    assertEquals("snapshottedDir=" + snapshottedDir
        + ", snapshotRoot=" + snapshotRoot,
        currentFiles.length, snapshotFiles.length);
  }

  /**
   * Compare two dumped trees that are stored in two files. The following is an
   * example of the dumped tree:
   *
   *

   * information of root
   * +- the first child of root (e.g., /foo)
   *   +- the first child of /foo
   *   ...
   *   \- the last child of /foo (e.g., /foo/bar)
   *     +- the first child of /foo/bar
   *     ...
   *   snapshots of /foo
   *   +- snapshot s_1
   *   ...
   *   \- snapshot s_n
   * +- second child of root
   *   ...
   * \- last child of root
   *
   * The following information is dumped for each inode:
   * localName (className@hashCode) parent permission group user
   *
   * Specific information for different types of INode:
   * {@link INodeDirectory}:childrenSize
   * {@link INodeFile}: fileSize, block list. Check {@link BlockInfo#toString()}
   * and {@link BlockUnderConstructionFeature#toString()} for detailed information.
   *

   * @see INode#dumpTreeRecursively()
   */
  public static void compareDumpedTreeInFile(File file1, File file2,
      boolean compareQuota) throws IOException {
    try {
      compareDumpedTreeInFile(file1, file2, compareQuota, false);
    } catch(Throwable t) {
      LOG.info("FAILED compareDumpedTreeInFile(" + file1 + ", " + file2 + ")", t);
      compareDumpedTreeInFile(file1, file2, compareQuota, true);
    }
  }

  private static void compareDumpedTreeInFile(File file1, File file2,
      boolean compareQuota, boolean print) throws IOException {
    if (print) {
      printFile(file1);
      printFile(file2);
    }

    BufferedReader reader1 = new BufferedReader(new FileReader(file1));
    BufferedReader reader2 = new BufferedReader(new FileReader(file2));
    try {
      String line1 = "";
      String line2 = "";
      while ((line1 = reader1.readLine()) != null
          && (line2 = reader2.readLine()) != null) {
        if (print) {
          System.out.println();
          System.out.println("1) " + line1);
          System.out.println("2) " + line2);
        }
        // skip the hashCode part of the object string during the comparison,
        // also ignore the difference between INodeFile/INodeFileWithSnapshot
        line1 = line1.replaceAll("INodeFileWithSnapshot", "INodeFile");
        line2 = line2.replaceAll("INodeFileWithSnapshot", "INodeFile");
        line1 = line1.replaceAll("@[\\dabcdef]+", "");
        line2 = line2.replaceAll("@[\\dabcdef]+", "");

        // skip the replica field of the last block of an
        // INodeFileUnderConstruction
        line1 = line1.replaceAll("replicas=\\[.*\\]", "replicas=[]");
        line2 = line2.replaceAll("replicas=\\[.*\\]", "replicas=[]");

        if (!compareQuota) {
          line1 = line1.replaceAll("Quota\\[.*\\]", "Quota[]");
          line2 = line2.replaceAll("Quota\\[.*\\]", "Quota[]");
        }

        // skip the specific fields of BlockUnderConstructionFeature when the
        // node is an INodeFileSnapshot or INodeFileUnderConstructionSnapshot
        if (line1.contains("(INodeFileSnapshot)")
            || line1.contains("(INodeFileUnderConstructionSnapshot)")) {
          line1 = line1.replaceAll(
           "\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}",
           "");
          line2 = line2.replaceAll(
           "\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}",
           "");
        }
        assertEquals(line1.trim(), line2.trim());
      }
      Assert.assertNull(reader1.readLine());
      Assert.assertNull(reader2.readLine());
    } finally {
      reader1.close();
      reader2.close();
    }
  }

  static void printFile(File f) throws IOException {
    System.out.println();
    System.out.println("File: " + f);
    BufferedReader in = new BufferedReader(new FileReader(f));
    try {
      for(String line; (line = in.readLine()) != null; ) {
        System.out.println(line);
      }
    } finally {
      in.close();
    }
  }

  public static void dumpTree2File(FSDirectory fsdir, File f) throws IOException{
    final PrintWriter out = new PrintWriter(new FileWriter(f, false), true);
    fsdir.getINode("/").dumpTreeRecursively(out, new StringBuilder(),
        Snapshot.CURRENT_STATE_ID);
    out.close();
  }

  /**
   * Generate the path for a snapshot file.
   *
   * @param snapshotRoot of format
   *          {@literal <snapshottble_dir>/.snapshot/<snapshot_name>}
   * @param file path to a file
   * @return The path of the snapshot of the file assuming the file has a
   *         snapshot under the snapshot root of format
   *         {@literal <snapshottble_dir>/.snapshot/<snapshot_name>/<path_to_file_inside_snapshot>}
   *         . Null if the file is not under the directory associated with the
   *         snapshot root.
   */
  static Path getSnapshotFile(Path snapshotRoot, Path file) {
    Path rootParent = snapshotRoot.getParent();
    if (rootParent != null && rootParent.getName().equals(".snapshot")) {
      Path snapshotDir = rootParent.getParent();
      if (file.toString().contains(snapshotDir.toString())
          && !file.equals(snapshotDir)) {
        String fileName = file.toString().substring(
            snapshotDir.toString().length() + 1);
        Path snapshotFile = new Path(snapshotRoot, fileName);
        return snapshotFile;
      }
    }
    return null;
  }

  /**
   * A class creating directories trees for snapshot testing. For simplicity,
   * the directory tree is a binary tree, i.e., each directory has two children
   * as snapshottable directories.
   */
  static class TestDirectoryTree {
    /** Height of the directory tree */
    final int height;
    /** Top node of the directory tree */
    final Node topNode;
    /** A map recording nodes for each tree level */
    final Map<Integer, ArrayList<Node>> levelMap;

    /**
     * Constructor to build a tree of given {@code height}
     */
    TestDirectoryTree(int height, FileSystem fs) throws Exception {
      this.height = height;
      this.topNode = new Node(new Path("/TestSnapshot"), 0,
          null, fs);
      this.levelMap = new HashMap<Integer, ArrayList<Node>>();
      addDirNode(topNode, 0);
      genChildren(topNode, height - 1, fs);
    }

    /**
     * Add a node into the levelMap
     */
    private void addDirNode(Node node, int atLevel) {
      ArrayList<Node> list = levelMap.get(atLevel);
      if (list == null) {
        list = new ArrayList<Node>();
        levelMap.put(atLevel, list);
      }
      list.add(node);
    }

    int id = 0;
    /**
     * Recursively generate the tree based on the height.
     *
     * @param parent The parent node
     * @param level The remaining levels to generate
     * @param fs The FileSystem where to generate the files/dirs
     * @throws Exception
     */
    private void genChildren(Node parent, int level, FileSystem fs)
        throws Exception {
      if (level == 0) {
        return;
      }
      parent.leftChild = new Node(new Path(parent.nodePath,
          "left" + ++id), height - level, parent, fs);
      parent.rightChild = new Node(new Path(parent.nodePath,
          "right" + ++id), height - level, parent, fs);
      addDirNode(parent.leftChild, parent.leftChild.level);
      addDirNode(parent.rightChild, parent.rightChild.level);
      genChildren(parent.leftChild, level - 1, fs);
      genChildren(parent.rightChild, level - 1, fs);
    }

    /**
     * Randomly retrieve a node from the directory tree.
     *
     * @param random A random instance passed by user.
     * @param excludedList Excluded list, i.e., the randomly generated node
     *          cannot be one of the nodes in this list.
     * @return a random node from the tree.
     */
    Node getRandomDirNode(Random random, List<Node> excludedList) {
      while (true) {
        int level = random.nextInt(height);
        ArrayList<Node> levelList = levelMap.get(level);
        int index = random.nextInt(levelList.size());
        Node randomNode = levelList.get(index);
        if (excludedList == null || !excludedList.contains(randomNode)) {
          return randomNode;
        }
      }
    }

    /**
     * The class representing a node in {@link TestDirectoryTree}.
     *

     * This contains:
     *

     *
Two children representing the two snapshottable directories

     *
A list of files for testing, so that we can check snapshots
     * after file creation/deletion/modification.

     *
A list of non-snapshottable directories, to test snapshots with
     * directory creation/deletion. Note that this is needed because the
     * deletion of a snapshottale directory with snapshots is not allowed.

     *

     */
    static class Node {
      /** The level of this node in the directory tree */
      final int level;

      /** Children */
      Node leftChild;
      Node rightChild;

      /** Parent node of the node */
      final Node parent;

      /** File path of the node */
      final Path nodePath;

      /**
       * The file path list for testing snapshots before/after file
       * creation/deletion/modification
       */
      ArrayList<Path> fileList;

      /**
       * Each time for testing snapshots with file creation, since we do not
       * want to insert new files into the fileList, we always create the file
       * that was deleted last time. Thus we record the index for deleted file
       * in the fileList, and roll the file modification forward in the list.
       */
      int nullFileIndex = 0;

      /**
       * A list of non-snapshottable directories for testing snapshots with
       * directory creation/deletion
       */
      final ArrayList<Node> nonSnapshotChildren;

      Node(Path path, int level, Node parent,
          FileSystem fs) throws Exception {
        this.nodePath = path;
        this.level = level;
        this.parent = parent;
        this.nonSnapshotChildren = new ArrayList<Node>();
        fs.mkdirs(nodePath);
      }

      /**
       * Create files and add them in the fileList. Initially the last element
       * in the fileList is set to null (where we start file creation).
       */
      void initFileList(FileSystem fs, String namePrefix, long fileLen,
          short replication, long seed, int numFiles) throws Exception {
        fileList = new ArrayList<Path>(numFiles);
        for (int i = 0; i < numFiles; i++) {
          Path file = new Path(nodePath, namePrefix + "-f" + i);
          fileList.add(file);
          if (i < numFiles - 1) {
            DFSTestUtil.createFile(fs, file, fileLen, replication, seed);
          }
        }
        nullFileIndex = numFiles - 1;
      }

      @Override
      public boolean equals(Object o) {
        if (o != null && o instanceof Node) {
          Node node = (Node) o;
          return node.nodePath.equals(nodePath);
        }
        return false;
      }

      @Override
      public int hashCode() {
        return nodePath.hashCode();
      }
    }
  }

  public static void dumpTree(String message, MiniDFSCluster cluster
      ) throws UnresolvedLinkException {
    System.out.println("XXX " + message);
    try {
      cluster.getNameNode().getNamesystem().getFSDirectory().getINode("/"
          ).dumpTreeRecursively(System.out);
    } catch (UnresolvedLinkException ule) {
      throw ule;
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }
}


text:
<?php

declare(strict_types=1);

namespace YoutubeDl\Tests\Entity;

use PHPUnit\Framework\TestCase;
use YoutubeDl\Entity\Extractor;

final class ExtractorTest extends TestCase
{
    public function testGetter(): void
    {
        $extractor = new Extractor([
            'title' => 'youtube:channel',
        ]);

        self::assertSame('youtube:channel', $extractor->getTitle());
    }
}


text:
require 'rubygems'
require 'open-uri'
require 'pismo'
require 'spreadsheet'

class Google_Scarpping_Script
 #Method to get the input from user at run time.
 def input_data
    begin
        print "Input query string : "
        @query_string=gets.chomp
	if @query_string.empty? or @query_string=='' or @query_string=='\n'	#validate the query string.
          raise 'Invalid query string.'
        end

        print "Input page number - Range 1 :"
        @range1=gets.to_i
	if (@range1<=0) or (@range1.is_a? Float)	#validate the input range1 - if it is a valid integer.
          raise 'Invalid range value.Input only numbers.'
        end

        print "Input page number - Range 2 :"
        @range2=gets.to_i
	if (@range2<=0) or (@range2.is_a? Float)	#validate the input range2 - if it is a valid integer.
          raise 'Invalid range value.Input only numbers.'
        end

    rescue Exception => e
        puts e.message
        retry
    end
 end
 #Method to fetch the webpage contents within the given range of pages and the exact query string and push those data into a spreadsheet.
 def process_data()
   	Spreadsheet.client_encoding='UTF-8'
	book=Spreadsheet::Workbook.new
	sheet = book.create_worksheet
	sheet.row(0).push 'Link Text','Link Url','Description' #For including headers to the spreadsheet.

	main_content=Array.new
	s=''
	s1=''
	value=0
	row_count=1
	iterate=@range1.to_i
	while iterate <= @range2.to_i
  		if iterate==1
   			url='http://www.google.co.in/search?q='+@query_string.to_s	#for first page.
   			link_count=11
  		elsif iterate>1
   			value=(iterate-1)*10
   			link_count=10
   			url='http://www.google.co.in/search?q='+@query_string.to_s+'&start='+value.to_s	#for subsequent pages.
  		end
  		doc = Pismo::Document.new(url)
  		content=doc.body.to_s
  		main_content=content.split('*',11)
  		tmp=1
  		while tmp <= link_count
    			s=main_content[tmp]
    			s1=s.lines.map(&:chomp) #s1=s.split(/[\n]+/)
    			#print "Link #{j} : " + s1[1].to_s + "\nUrl #{j}  : " + s1[2].to_s + "\nDesc #{j} : " + s1[3].to_s + "\n"
    			sheet.row(row_count).push s1[1].to_s,s1[2].to_s,s1[3].to_s
    			book.write('/home/chandrasekar/training-ruby/shekar/23_September/website_links.xls')
    			row_count+=1
    			tmp+=1
  		end
  		iterate+=1
	end
 end
 def validate_input()
 end
end

   scrap=Google_Scarpping_Script.new
   scrap.input_data()	#calls the method to fetch data from user
   scrap.process_data()	#calls the method to fetch results and add them to the spreadsheet.
   puts "Spreadsheet created."


text:
require 'fog/openstack/models/collection'
require 'fog/openstack/identity/v2/models/ec2_credential'

module Fog
  module OpenStack
    class Identity
      class V2
        class Ec2Credentials < Fog::OpenStack::Collection
          model Fog::OpenStack::Identity::V2::Ec2Credential

          attribute :user

          def all(options = {})
            user_id = user ? user.id : nil

            options[:user_id] = user_id
            ec2_credentials = service.list_ec2_credentials(options)

            load_response(ec2_credentials, 'credentials')
          end

          def create(attributes = {})
            if user
              attributes[:user_id] ||= user.id
              attributes[:tenant_id] ||= user.tenant_id
            end

            super attributes
          end

          def destroy(access_key)
            ec2_credential = find_by_access_key(access_key)
            ec2_credential.destroy
          end

          def find_by_access_key(access_key)
            user_id = user ? user.id : nil

            ec2_credential =
              find { |ec2_cred| ec2_cred.access == access_key }

            unless ec2_credential
              response = service.get_ec2_credential(user_id, access_key)
              body = response.body['credential']
              body = body.merge 'service' => service

              ec2_credential = Fog::OpenStack::Identity::V2::EC2Credential.new(body)
            end

            ec2_credential
          end
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <title>Hypo Tests</title>


text:
> Formularies (singular formulary; Latin littera(e) formularis, -ares) are medieval collections of models for the execution of documents (acta), public or private; a space being left for the insertion of names, dates, and circumstances peculiar to each case. Their modern equivalent are forms.
>
> -- Wikipedia

A Ruby gem to parse HTML5 forms and decompose them into model validation using their field types (email, url, number, etc) and form attributes (required, pattern, etc).

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'formulary'
```

And then execute:

$ bundle

Or install it yourself as:

$ gem install formulary

## Usage

Create a new Formulary Form

```ruby
require 'formulary'

form_html = <<EOF
<form>
<input type="email" name="email" required />
<input type="username" name="username" pattern="[a-z0-9_-]{3,16}" />
</form>
EOF

html_form = Formulary::HtmlForm.new(form_html)
```

Validate the form based on HTML5 field types and/or patterns and view which fields are invalid and why.

```ruby
html_form.valid?({ email: "test@example.com", username: "person" })
# => true

html_form.valid?({ email: "invalid", username: "person" })
# => false

html_form.errors
# => {"email"=>"not a valid email"}
```

When an unexpected field is submitted that wasn't in the original markup, it will raise a `Formulary::UnexpectedParameter` exception:

```ruby
html_form.valid?({ unknown: "value" })
# => Formulary::UnexpectedParameter: Got unexpected field 'unknown'
```

## Currently Supported

**Supported Input Types**
- checkbox
- color
- date
- email
- hidden
- month
- number
- password
- radio
- range
- search
- tel
- text
- week

**Ignored Field Types (not validated but does not make things explode)
- button
- image
- reset
- submit

**Supported Input Attributes**
- max (number, range, date)
- min (number, range, date)
- pattern
- required
- step (number, range)

**Other Supported Tags**
- select
- textarea

## TODO

**Add Unsupported Input Types**
- datetime
- datetime-local
- file
- time
- url

## Authors

        * Matt Bohme / [@quady](https://github.com/quady)
        * Don Petersen / [@dpetersen](https://github.com/dpetersen)

## Contributing

1. Fork it
2. Get it running (see Installation above)
3. Create your feature branch (`git checkout -b my-new-feature`)
4. Write your code and **specs**
5. Commit your changes (`git commit -am 'Add some feature'`)
6. Push to the branch (`git push origin my-new-feature`)
7. Create new Pull Request

## License

        Copyright (c) 2013 G5

        MIT License

        Permission is hereby granted, free of charge, to any person obtaining
        a copy of this software and associated documentation files (the
                        "Software"), to deal in the Software without restriction, including
        without limitation the rights to use, copy, modify, merge, publish,
        distribute, sublicense, and/or sell copies of the Software, and to
        permit persons to whom the Software is furnished to do so, subject to
        the following conditions:

        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
        NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
        LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
        WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<!--
	 Filename: submit.php
	 Purpose: To manage the file upload on the index page
-->

<?php
	//Error reporting
	ini_set('display_errors', 1);
	error_reporting(0);

    //This is for PHPMailer
    require 'PHPMailer/PHPMailerAutoload.php';

    //Set the local timezone
    date_default_timezone_set("America/Los_Angeles");

    $target_dir = "uploads/";
    $file = basename($_FILES["fileToUpload"]["name"]);
    $ext = pathinfo ($file, PATHINFO_EXTENSION);
    $uploadOk = 1;

     //Check for empty fields
    if ( (empty($_POST['uploaderName']) == true) || (empty($_POST['uploaderPhone']) == true) || (empty($_POST['uploaderEmail']) == true) ) {
         echo "Please fill in your name, email, phone number and attach your resume. ";
        $uploadOk = 0;
    }

    //Check file type
    $allowed =  array('pdf','rtf' ,'doc', 'docx', 'txt');
    if(!in_array($ext, $allowed) ) {
        echo "Wrong file type, please upload a pdf, rtf, text or Word Document. ";
        $uploadOk = 0;
    }

    //Change the file name
    $file_name = basename($_FILES["fileToUpload"]["name"]). " " . $_POST['uploaderName'] . " " . date("jS \of F Y h:i:s A") . "." . $ext;
    $target_file = $target_dir . $file_name;

    // Check if file already exists. Almost would never happen
    if (file_exists($target_file)) {
        echo "File already exists. ";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Your file is too large. ";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded. ";

    // if everything is ok, try to upload file
    } else {
          //Captcha
           session_start();
          if($_POST['captcha'] != $_SESSION['digit']) die("Sorry, the CAPTCHA code entered was incorrect!");
           session_destroy();

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
          header( "Refresh:3; url=https://review-my-resume.myshopify.com", true, 303);
          echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. You will be redirected to Shopify for payment..";

          //Save to the database
               $uploaderName = $_POST['uploaderName'];
               $uploaderPhone = $_POST['uploaderPhone'];
               $uploaderEmail = $_POST['uploaderEmail'];
               $uploaderTime = date("jS \of F Y h:i:s A");
               $uploaderFile = $file_name;

          //require 'reviewDB.php';
          $conn= mysqli_connect('localhost','review','GL2RIdtQNTih', 'review_DB');
          $sql = "INSERT INTO resumes (name, email, phone, time, filename)
          VALUES ('$uploaderName', '$uploaderEmail', '$uploaderPhone', '$uploaderTime', '$uploaderFile')";
          $result = @mysqli_query($cnxn, $sql);

          if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
           }

          if ($conn->query($sql) === TRUE) {
               echo ".";
           } else {
               echo "Error: " . $sql . "<br>" . $conn->error;
           }
               //Sending email
                $email = new PHPMailer();
                $email->From      = 'reviewmyresume@hotmail.com';
                $email->FromName  = 'ReviewMyResume';

                $email->Subject   = 'Your attached file';
                $email->Body      = 'This is the resume';
                $email->AddAddress( 'Motake@mail.greenriver.edu' );

                $email->Subject   = 'Your resume from ' . $_POST['uploaderName'] . " " . date("l jS \of F Y h:i:s A");
                $email->Body      = 'You have a new Resume!';
                //$email->AddAddress( 'chau.duong1995@yahoo.com' );

                $email->Subject   = 'Your resume from ' . $_POST['uploaderName'] . " " . date("jS \of F Y h:i:s A");
                $email->Body      = 'You have a new Resume!';
                $email->AddAddress( 'sk8rak@gmail.com' );
                //$email->AddAddress( 'chau.duong1995@yahoo.com' );
                $email->AddAttachment( $target_file , $file_name );

                return $email->Send();

        } else {
            echo "There was an error uploading your file.";
        }
    }
?>


text:
//
//  C4UIElement.h
//  C4iOS
//
//  Created by moi on 13-02-28.
//  Copyright (c) 2013 POSTFL. All rights reserved.
//

#import <Foundation/Foundation.h>
/** C4UIElement protocol groups methods that are fundamental to basic interaction user interface objects in C4.

 If an object conforms to this protocol that object can trigger methods associated with various control events.
 */
@protocol C4UIElement <NSObject>
///@name User Interface Methods
/**Attaches a method to a specific control event for the receiver.

 You may call this method multiple times, and you may specify multiple target-action pairs for a particular event. The action message may optionally include the sender and the event as parameters, in that order.

 When you call this method, target is not retained.

 @param methodName A string-version of a selector (i.e. the name of a method) identifying an action message. It cannot be NULL.
 @param object The target object—that is, the object from which the method is run. If this is nil, the responder chain is searched for an object willing to respond to the action message.
 @param event A bitmask specifying the control events for which the action message is sent. See "Control Events" for bitmask constants.
 */
-(void)runMethod:(NSString *)methodName target:(id)object forEvent:(C4ControlEvents)event;

/**Removes a target and action for a particular event (or events) from an internal dispatch table.

 @param methodName A string-version of a selector (i.e. the name of a method) identifying an action message. It cannot be NULL.
 @param object The target object—that is, the object from which the method is run. Pass nil to remove all targets paired with action and the specified control events.
 @param event A bitmask specifying the control events for which the action message is sent. See "Control Events" for bitmask constants.
 */
-(void)stopRunningMethod:(NSString *)methodName target:(id)object forEvent:(C4ControlEvents)event;
@end


text:
define(['query/property_query'], function(PropertyQuery){

  var NameQuery = PropertyQuery.extend({
    className: 'NameQuery'
  });
  NameQuery.prototype.base = NameQuery;

  return NameQuery;

});


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

namespace Dicom.Network {
	public class DicomCEchoResponse : DicomResponse {
		public DicomCEchoResponse(DicomDataset command) : base(command) {
		}

		public DicomCEchoResponse(DicomCEchoRequest request, DicomStatus status) : base(request, status) {
		}
	}
}


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Shopibar in your macOS menu bar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content='Shopify Admin Plugin for BitBar - install xbar for free to get started.'>
	<meta name='author' content='Etka Özdemir'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='http://i.imgur.com/Dt499Nh.png'>
	<meta itemprop='name' content='Shopibar in your macOS menu bar'>
	<meta itemprop='description' content='Shopify Admin Plugin for BitBar - install xbar for free to get started.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Shopibar in your macOS menu bar'>
	<meta name='twitter:description' content='Shopify Admin Plugin for BitBar - install xbar for free to get started.'>
	<meta name='twitter:image' content='http://i.imgur.com/Dt499Nh.png'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Shopibar in your macOS menu bar'>
	<meta property='og:description' content='Shopify Admin Plugin for BitBar - install xbar for free to get started.'>
	<meta property='og:url' content='https://xbarapp.com/plugins/E-Commerce/Shopibar.15m.js.html'>
	<meta property='og:site_name' content='xbar lets you put anything into your macOS menu bar'>
	<meta property='og:type' content='article'>
	<meta property='og:image' content='http://i.imgur.com/Dt499Nh.png'>
	<link rel='apple-touch-icon' sizes='180x180' href='http://i.imgur.com/Dt499Nh.png'>
	<link rel='icon' type='image/png' sizes='32x32' href='http://i.imgur.com/Dt499Nh.png'>
	<link rel='shortcut icon' href='http://i.imgur.com/Dt499Nh.png'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

Shopibar

										Etka Özdemir (@m-etka on GitHub)

						Shopify Admin Plugin for BitBar

						🖥 Open in xbar app

Requires xbar app

							Shopibar.15m.js

						Edit

						Open on GitHub

#!/usr/bin/env /usr/local/bin/node

/*
 * <bitbar.title>Shopibar</bitbar.title>
 * <bitbar.version>v1.0.1</bitbar.version>
 * <bitbar.author>Etka Özdemir</bitbar.author>
 * <bitbar.author.github>m-etka</bitbar.author.github>
 * <bitbar.image>http://i.imgur.com/Dt499Nh.png</bitbar.image>
 * <bitbar.desc>Shopify Admin Plugin for BitBar</bitbar.desc>
 * <bitbar.dependencies>node</bitbar.dependencies>
 *
 */

/*
 * Visit http://shopibar.etka.org for installation and details
 */

/* Shopibar configuration */
var admin = {
    myShopifyAccountName: 'example.myshopify.com',
    apiKey: 'example.com_api_key',
    password: 'example.com_password'
};
showCustomerCount = true;
showPendingOrders = true;
showUnshippedOrders = true;
/* End of Shopibar configuration  */

var verbose = true;

// Start plug-in
console.log('🛒');
console.log('---');
printBitBarLine('Shopibar', ['color=black', 'font=Phosphate', 'size=20']);

// Get data using Shopify Admin API
get(admin, 'shop', function(data) {
    // Show shop info
    printBitBarLine(data.shop.name, ['color=black', 'font=Calibri', 'size=18']);

    if (showCustomerCount) {
        // Get customer count
        get(admin, 'customerCount', function(data) {
            // Show customer count
            printBitBarLine('Customer Count:', ['color=gray', 'font=Calibri', 'size=14']);
            printBitBarLine(data.count, ['color=black', 'font=Calibri', 'size=16']);
        });
    }

    if (showPendingOrders) {
        // Get pending orders
        get(admin, 'pendingOrders', function(data) {
            printOrders(data, 'Pending Orders');
        });
    }

    if (showUnshippedOrders) {
        // Get unshipped orders
        get(admin, 'unshippedOrders', function(data) {
            printOrders(data, 'Unshipped Orders');
        });
    }

});

// Print order details
function printOrders(data, title) {
    // Show orders
    printBitBarLine(' ');
    printBitBarLine(title + ':', ['color=gray', 'font=Calibri', 'size=14']);
    printBitBarLine(data.orders.length, ['color=black', 'font=Calibri', 'size=16']);
    for (var i = 0; i < data.orders.length; i++) {
        // Show order price and user info
        printBitBarLine('--$' + data.orders[i].total_line_items_price, ['color=black', 'font=Calibri', 'size=16']);
        printBitBarLine('--' + data.orders[i].email, ['font=Calibri', 'size=14']);
        // Show items ordered
        for (var j = 0; j < data.orders[i].line_items.length; j++) {
            if (j !== 0) {
                printBitBarLine('----');
            }
            printBitBarLine('----' + data.orders[i].line_items[j].title, ['font=Calibri', 'size=16', 'color=black']);
            printBitBarLine('----');
            printBitBarLine('----Name     : ' + data.orders[i].line_items[j].name, ['font=Monaco', 'size=11']);
            printBitBarLine('----SKU      : ' + data.orders[i].line_items[j].sku, ['font=Monaco', 'size=11']);
            printBitBarLine('----Price    : $' + data.orders[i].line_items[j].price, ['font=Monaco', 'size=11']);
            printBitBarLine('----Quantity : ' + data.orders[i].line_items[j].quantity, ['font=Monaco', 'size=11']);

        }
        printBitBarLine('-----');

    }
}

// Get
function get(admin, requestName, callback) {
    var endpoint = {
        url: '',
        requestType: 'GET'
    };
    switch (requestName) {
        case 'shop':
            endpoint.url = '/admin/shop.json';
            endpoint.requestType = 'GET';
            break;
        case 'customerCount':
            endpoint.url = '/admin/customers/count.json';
            endpoint.requestType = 'GET';
            break;
        case 'pendingOrders':
            endpoint.url = '/admin/orders.json?status=pending';
            endpoint.requestType = 'GET';
            break;
        case 'unshippedOrders':
            endpoint.url = '/admin/orders.json?fulfillment_status=unshipped';
            endpoint.requestType = 'GET';
            break;
        default:
            break;
    }
    performRequest(admin, endpoint.url, endpoint.requestType, function(data) {
        if (data.errors && verbose) {
            console.log('Errors: ' + data.errors);
        } else {
            callback(data);
        }
    });

}

// HTTPS request
function performRequest(admin, endpoint, method, success) {
    var https = require('https');
    var auth = new Buffer(admin.apiKey + ':' + admin.password).toString('base64');

    var headers = {};

    headers = {
        'Authorization': 'Basic ' + auth,
        'Content-Type': 'application/json'
    };

    var options = {
        host: admin.myShopifyAccountName,
        path: endpoint,
        method: method,
        headers: headers
    };

    var req = https.request(options, function(res) {
        res.setEncoding('utf-8');

        var responseString = '';

        res.on('data', function(data) {
            responseString += data;
        });

        res.on('end', function() {
            var responseObject = JSON.parse(responseString);
            success(responseObject);
        });
    });

    req.end();

    req.on('error', function(err) {
        console.log('Error: Could not connect! Check your credientials and connection.');
        if (verbose) {
            console.log(err);
        }
    });
}

// Plug-in output
function printBitBarLine(title, args) {
    var lineArgs = [];

    if (title !== '-----') {
        for (var i in args) {
            lineArgs.push(args[i]);
        }

        if (lineArgs.length !== 0) {
            title = title + '|';
        }
    }
    console.log(title + lineArgs.join(' '));
}

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
#include "fboss/agent/hw/mock/MockHwSwitch.h"

#include <folly/Memory.h>
#include <folly/dynamic.h>

#include "fboss/agent/hw/mock/MockTxPacket.h"

using std::make_unique;
using ::testing::Invoke;
using ::testing::_;

namespace facebook { namespace fboss {

MockHwSwitch::MockHwSwitch(MockPlatform *platform) :
    platform_(platform) {
  // We need to delete the memory allocated by the packet. Ideally, we
  // could pass a smart pointer to these functions, but gmock does not
  // support move-only types and if we pass in a shared_ptr we cannot
  // delegate to a function that takes a unique_ptr. This is
  // definitely hacky, but it makes the interface more flexible.
  ON_CALL(*this, sendPacketSwitched_(_))
    .WillByDefault(Invoke([=](TxPacket* pkt) -> bool {
          delete pkt; return true; } ));
  ON_CALL(*this, sendPacketOutOfPort_(_, _))
      .WillByDefault(Invoke([=](TxPacket* pkt, PortID /*port*/) -> bool {
        delete pkt;
        return true;
      }));
}

std::unique_ptr<TxPacket> MockHwSwitch::allocatePacket(uint32_t size) {
  return make_unique<MockTxPacket>(size);
}

bool MockHwSwitch::sendPacketSwitched(std::unique_ptr<TxPacket> pkt) noexcept {
  TxPacket* raw(pkt.release());
  sendPacketSwitched_(raw);
  return true;
}

bool MockHwSwitch::sendPacketOutOfPort(
    std::unique_ptr<TxPacket> pkt,
    facebook::fboss::PortID portID) noexcept {
  TxPacket* raw(pkt.release());
  sendPacketOutOfPort_(raw, portID);
  return true;
}

std::shared_ptr<SwitchState>
MockHwSwitch::stateChanged(const StateDelta& delta) {
    stateChangedMock(delta);
    return delta.newState();
}

}} // facebook::fboss


text:
"""Support for controlling GPIO pins of a Numato Labs USB GPIO expander."""
import logging

import numato_gpio as gpio
import voluptuous as vol

from homeassistant.const import (
    CONF_BINARY_SENSORS,
    CONF_ID,
    CONF_NAME,
    CONF_SENSORS,
    CONF_SWITCHES,
    EVENT_HOMEASSISTANT_START,
    EVENT_HOMEASSISTANT_STOP,
    PERCENTAGE,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform

_LOGGER = logging.getLogger(__name__)

DOMAIN = "numato"

CONF_INVERT_LOGIC = "invert_logic"
CONF_DISCOVER = "discover"
CONF_DEVICES = "devices"
CONF_DEVICE_ID = "id"
CONF_PORTS = "ports"
CONF_SRC_RANGE = "source_range"
CONF_DST_RANGE = "destination_range"
CONF_DST_UNIT = "unit"
DEFAULT_INVERT_LOGIC = False
DEFAULT_SRC_RANGE = [0, 1024]
DEFAULT_DST_RANGE = [0.0, 100.0]
DEFAULT_DEV = [f"/dev/ttyACM{i}" for i in range(10)]

PORT_RANGE = range(1, 8)  # ports 0-7 are ADC capable

DATA_PORTS_IN_USE = "ports_in_use"
DATA_API = "api"

def int_range(rng):
    """Validate the input array to describe a range by two integers."""
    if not (isinstance(rng[0], int) and isinstance(rng[1], int)):
        raise vol.Invalid(f"Only integers are allowed: {rng}")
    if len(rng) != 2:
        raise vol.Invalid(f"Only two numbers allowed in a range: {rng}")
    if rng[0] > rng[1]:
        raise vol.Invalid(f"Lower range bound must come first: {rng}")
    return rng

def float_range(rng):
    """Validate the input array to describe a range by two floats."""
    try:
        coe = vol.Coerce(float)
        coe(rng[0])
        coe(rng[1])
    except vol.CoerceInvalid as err:
        raise vol.Invalid(f"Only int or float values are allowed: {rng}") from err
    if len(rng) != 2:
        raise vol.Invalid(f"Only two numbers allowed in a range: {rng}")
    if rng[0] > rng[1]:
        raise vol.Invalid(f"Lower range bound must come first: {rng}")
    return rng

def adc_port_number(num):
    """Validate input number to be in the range of ADC enabled ports."""
    try:
        num = int(num)
    except ValueError as err:
        raise vol.Invalid(f"Port numbers must be integers: {num}") from err
    if num not in range(1, 8):
        raise vol.Invalid(f"Only port numbers from 1 to 7 are ADC capable: {num}")
    return num

ADC_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_NAME): cv.string,
        vol.Optional(CONF_SRC_RANGE, default=DEFAULT_SRC_RANGE): int_range,
        vol.Optional(CONF_DST_RANGE, default=DEFAULT_DST_RANGE): float_range,
        vol.Optional(CONF_DST_UNIT, default=PERCENTAGE): cv.string,
    }
)

PORTS_SCHEMA = vol.Schema({cv.positive_int: cv.string})

IO_PORTS_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_PORTS): PORTS_SCHEMA,
        vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean,
    }
)

DEVICE_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_ID): cv.positive_int,
        CONF_BINARY_SENSORS: IO_PORTS_SCHEMA,
        CONF_SWITCHES: IO_PORTS_SCHEMA,
        CONF_SENSORS: {CONF_PORTS: {adc_port_number: ADC_SCHEMA}},
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: {
            CONF_DEVICES: vol.All(cv.ensure_list, [DEVICE_SCHEMA]),
            vol.Optional(CONF_DISCOVER, default=DEFAULT_DEV): vol.All(
                cv.ensure_list, [cv.string]
            ),
        },
    },
    extra=vol.ALLOW_EXTRA,
)

def setup(hass, config):
    """Initialize the numato integration.

    Discovers available Numato devices and loads the binary_sensor, sensor and
    switch platforms.

    Returns False on error during device discovery (e.g. duplicate ID),
    otherwise returns True.

    No exceptions should occur, since the platforms are initialized on a best
    effort basis, which means, errors are handled locally.
    """
    hass.data[DOMAIN] = config[DOMAIN]

    try:
        gpio.discover(config[DOMAIN][CONF_DISCOVER])
    except gpio.NumatoGpioError as err:
        _LOGGER.info("Error discovering Numato devices: %s", err)
        gpio.cleanup()
        return False

    _LOGGER.info(
        "Initializing Numato 32 port USB GPIO expanders with IDs: %s",
        ", ".join(str(d) for d in gpio.devices),
    )

    hass.data[DOMAIN][DATA_API] = NumatoAPI()

    def cleanup_gpio(event):
        """Stuff to do before stopping."""
        _LOGGER.debug("Clean up Numato GPIO")
        gpio.cleanup()
        if DATA_API in hass.data[DOMAIN]:
            hass.data[DOMAIN][DATA_API].ports_registered.clear()

    def prepare_gpio(event):
        """Stuff to do when home assistant starts."""
        _LOGGER.debug("Setup cleanup at stop for Numato GPIO")
        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gpio)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, prepare_gpio)

    load_platform(hass, "binary_sensor", DOMAIN, {}, config)
    load_platform(hass, "sensor", DOMAIN, {}, config)
    load_platform(hass, "switch", DOMAIN, {}, config)
    return True

# pylint: disable=no-self-use
class NumatoAPI:
    """Home-Assistant specific API for numato device access."""

    def __init__(self):
        """Initialize API state."""
        self.ports_registered = {}

    def check_port_free(self, device_id, port, direction):
        """Check whether a port is still free set up.

        Fail with exception if it has already been registered.
        """
        if (device_id, port) not in self.ports_registered:
            self.ports_registered[(device_id, port)] = direction
        else:
            raise gpio.NumatoGpioError(
                "Device {} port {} already in use as {}.".format(
                    device_id,
                    port,
                    "input"
                    if self.ports_registered[(device_id, port)] == gpio.IN
                    else "output",
                )
            )

    def check_device_id(self, device_id):
        """Check whether a device has been discovered.

        Fail with exception.
        """
        if device_id not in gpio.devices:
            raise gpio.NumatoGpioError(f"Device {device_id} not available.")

    def check_port(self, device_id, port, direction):
        """Raise an error if the port setup doesn't match the direction."""
        self.check_device_id(device_id)
        if (device_id, port) not in self.ports_registered:
            raise gpio.NumatoGpioError(
                f"Port {port} is not set up for numato device {device_id}."
            )
        msg = {
            gpio.OUT: f"Trying to write to device {device_id} port {port} set up as input.",
            gpio.IN: f"Trying to read from device {device_id} port {port} set up as output.",
        }
        if self.ports_registered[(device_id, port)] != direction:
            raise gpio.NumatoGpioError(msg[direction])

    def setup_output(self, device_id, port):
        """Set up a GPIO as output."""
        self.check_device_id(device_id)
        self.check_port_free(device_id, port, gpio.OUT)
        gpio.devices[device_id].setup(port, gpio.OUT)

    def setup_input(self, device_id, port):
        """Set up a GPIO as input."""
        self.check_device_id(device_id)
        gpio.devices[device_id].setup(port, gpio.IN)
        self.check_port_free(device_id, port, gpio.IN)

    def write_output(self, device_id, port, value):
        """Write a value to a GPIO."""
        self.check_port(device_id, port, gpio.OUT)
        gpio.devices[device_id].write(port, value)

    def read_input(self, device_id, port):
        """Read a value from a GPIO."""
        self.check_port(device_id, port, gpio.IN)
        return gpio.devices[device_id].read(port)

    def read_adc_input(self, device_id, port):
        """Read an ADC value from a GPIO ADC port."""
        self.check_port(device_id, port, gpio.IN)
        self.check_device_id(device_id)
        return gpio.devices[device_id].adc_read(port)

    def edge_detect(self, device_id, port, event_callback):
        """Add detection for RISING and FALLING events."""
        self.check_port(device_id, port, gpio.IN)
        gpio.devices[device_id].add_event_detect(port, event_callback, gpio.BOTH)
        gpio.devices[device_id].notify = True