text:
<?php

namespace socialCocktail\Http\Controllers;

use Illuminate\Http\Request;

use socialCocktail\Http\Requests;

class IngredientesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function addIngrediente(Request $request){
        return 'hola';
    }
}


text:
package com.abusalimov.mrcalc.backend;

/**
 * The backend is responsible for creating callable functions from basic expressions.
 *
 * This class is the main entry point for the backend and serves as a factory for a {@link FunctionAssembler}, which is
 * responsible for assembling {@link com.abusalimov.mrcalc.runtime.Evaluable} functions.
 *
 * @param <E> the type of expressions used by the backend implementation
 * @param <F> the internal type of assembled functions used by the backend implementation
 * @author Eldar Abusalimov
 */
public interface Backend<E, F> {
    /**
     * Creates a new function assembler for a function with given signature.
     *
     * @param returnType     the return type of the function to be assembled
     * @param parameterTypes the types of parameters taken by the function to be assembled
     * @param <R>            the return type
     * @return the new {@link FunctionAssembler} instance
     */
    <R> FunctionAssembler<R, E, F> createFunctionAssembler(Class<R> returnType, Class<?>... parameterTypes);
}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.groovy.dsl.dsltop;

import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.dsl.GdslMembersHolderConsumer;
import org.jetbrains.plugins.groovy.dsl.holders.DelegatedMembersHolder;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;

/**
 * @author ilyas
 */
public class GroovyDslDefaultMembers implements GdslMembersProvider {

  /**
   * Find a class by its full-qulified name
   *
   * @param fqn
   * @return
   */
  @Nullable
  public PsiClass findClass(String fqn, GdslMembersHolderConsumer consumer) {
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(consumer.getProject());
    final PsiClass clazz = facade.findClass(fqn, GlobalSearchScope.allScope(consumer.getProject()));
    return clazz;
  }

  /**
   * **********************************************************************************
   * Methods and properties of the GroovyDSL language
   * **********************************************************************************
   */

  public void delegatesTo(@Nullable PsiElement elem, GdslMembersHolderConsumer consumer) {
    if (elem instanceof PsiClass) {
      final PsiClass clazz = (PsiClass)elem;
      final DelegatedMembersHolder holder = new DelegatedMembersHolder();
      for (PsiMethod method : clazz.getAllMethods()) {
        if (!method.isConstructor()) holder.addMember(method);
      }
      for (PsiField field : clazz.getAllFields()) {
        holder.addMember(field);
      }
      consumer.addMemberHolder(holder);
    }
    else if (elem instanceof GrExpression) {
      GrExpression expr = (GrExpression)elem;
      final PsiType type = expr.getType();
      if (type instanceof PsiClassType) {
        PsiClassType ctype = (PsiClassType)type;
        delegatesTo(ctype.resolve(), consumer);
      }
    }
  }

  /**
   * Add a member to a context's ctype
   *
   * @param member
   */
  public PsiMember add(PsiMember member, GdslMembersHolderConsumer consumer) {
    final DelegatedMembersHolder holder = new DelegatedMembersHolder();
    holder.addMember(member);
    consumer.addMemberHolder(holder);
    return member;
  }

  /**
   * Returns enclosing method call of a given context's place
   */
  @Nullable
  public GrMethodCallExpression enclosingCall(String name, GdslMembersHolderConsumer consumer) {
    final PsiElement place = consumer.getPlace();
    if (place == null) return null;
    GrMethodCallExpression call = PsiTreeUtil.getParentOfType(place, GrMethodCallExpression.class, true);
    if (call == null) return null;
    while (call != null && !name.equals(getInvokedMethodName(call))) {
      call = PsiTreeUtil.getParentOfType(call, GrMethodCallExpression.class, true);
    }
    if (call == null) return null;
    for (GrExpression arg : call.getClosureArguments()) {
      if (arg instanceof GrClosableBlock && PsiTreeUtil.findCommonParent(place, arg) == arg) {
        return call;
      }
    }
    for (GrExpression arg : call.getExpressionArguments()) {
      if (arg instanceof GrClosableBlock && PsiTreeUtil.findCommonParent(place, arg) == arg) {
        return call;
      }
    }
    return null;
  }

  @Nullable
  public PsiMethod enclosingMethod(GdslMembersHolderConsumer consumer) {
    final PsiElement place = consumer.getPlace();
    if (place == null) return null;
    return PsiTreeUtil.getParentOfType(place, PsiMethod.class, true);
  }

  @Nullable
  public PsiMember enclosingMember(GdslMembersHolderConsumer consumer) {
    final PsiElement place = consumer.getPlace();
    if (place == null) return null;
    final PsiMember member = PsiTreeUtil.getParentOfType(place, PsiMember.class, true);
    if (member instanceof PsiClass) return null;
    return member;
  }

  @Nullable
  public PsiClass enclosingClass(GdslMembersHolderConsumer consumer) {
    final PsiElement place = consumer.getPlace();
    if (place == null) return null;
    return PsiTreeUtil.getParentOfType(place, PsiClass.class, true);
  }

  private static String getInvokedMethodName(GrMethodCallExpression call) {
    final GrExpression expr = call.getInvokedExpression();
    if (expr instanceof GrReferenceExpression) {
      GrReferenceExpression ref = (GrReferenceExpression)expr;
      return ref.getName();
    }
    return null;
  }

}


text:
FROM php:fpm

ADD php.ini /usr/local/etc/php/conf.d/php.ini

# Installation of required package
RUN apt-get update && \
	apt-get install -y \
	libxml2 \
	libxml2-dev

RUN docker-php-ext-install mysqli pdo_mysql xml


text:
<?xml version="1.0" standalone="no"?>
<WebPage Name="{$view_short_name}" Description="{$comp}" Class="WebPage" Tab="" TemplateEngine="Smarty" TemplateFile="view.tpl" Access="{$acl.access}">
   <FormReferences>
   		<Reference Name="{$comp}.{$default_form}"/>
   </FormReferences>
</WebPage>


text:
package io.swagger.client.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * An action on a card
 **/

@ApiModel(description = "An action on a card")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-02-15T21:57:26.280-06:00")
public class CardAction   {

  private String type = null;
  private String title = null;
  private String image = null;
  private String value = null;

  /**
   * Defines the type of action implemented by this button.
   **/
  public CardAction type(String type) {
    this.type = type;
    return this;
  }

  @ApiModelProperty(example = "null", value = "Defines the type of action implemented by this button.")
  @JsonProperty("type")
  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }

  /**
   * Text description which appear on the button.
   **/
  public CardAction title(String title) {
    this.title = title;
    return this;
  }

  @ApiModelProperty(example = "null", value = "Text description which appear on the button.")
  @JsonProperty("title")
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }

  /**
   * URL Picture which will appear on the button, next to text label.
   **/
  public CardAction image(String image) {
    this.image = image;
    return this;
  }

  @ApiModelProperty(example = "null", value = "URL Picture which will appear on the button, next to text label.")
  @JsonProperty("image")
  public String getImage() {
    return image;
  }
  public void setImage(String image) {
    this.image = image;
  }

  /**
   * Supplementary parameter for action. Content of this property depends on the ActionType
   **/
  public CardAction value(String value) {
    this.value = value;
    return this;
  }

  @ApiModelProperty(example = "null", value = "Supplementary parameter for action. Content of this property depends on the ActionType")
  @JsonProperty("value")
  public String getValue() {
    return value;
  }
  public void setValue(String value) {
    this.value = value;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CardAction cardAction = (CardAction) o;
    return Objects.equals(this.type, cardAction.type) &&
        Objects.equals(this.title, cardAction.title) &&
        Objects.equals(this.image, cardAction.image) &&
        Objects.equals(this.value, cardAction.value);
  }

  @Override
  public int hashCode() {
    return Objects.hash(type, title, image, value);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CardAction {\n");

    sb.append("    type: ").append(toIndentedString(type)).append("\n");
    sb.append("    title: ").append(toIndentedString(title)).append("\n");
    sb.append("    image: ").append(toIndentedString(image)).append("\n");
    sb.append("    value: ").append(toIndentedString(value)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:ldap="http://www.springframework.org/schema/ldap"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:component-scan base-package="com.zeiv.emp.repo" />
	<!-- <tx:jta-transaction-manager /> -->
	<context:annotation-config />
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml" />
	</bean>
	<bean id="txnManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="txnManager" />

</beans>


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

    <string name="app_name">GeoQuiz</string>
    <string name="voice_trigger">GeoQuiz</string>

    <!-- Samples -->
    <string name="sample_question">The capital of Turkey is Constantinople.</string>
    <string name="sample_result">Correct!</string>

    <!-- Menu -->
    <string name="menu_true">True</string>
    <string name="menu_false">False</string>
    <string name="menu_next">Next</string>
    <string name="menu_previous">Previous</string>
    <string name="menu_stop">Stop</string>

    <!-- Results -->
    <string name="result_correct">Correct!</string>
    <string name="result_incorrect">Incorrect!</string>

    <!-- Questions -->
    <string name="question_turkey">The capital of Turkey is Constantinople.</string>
    <string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
    <string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
    <string name="question_africa">The source of the Nile River is in Egypt.</string>
    <string name="question_americas">The Amazon River is the longest river in the Americas.</string>
    <string name="question_asia">Lake Vaikal is the world\'s oldest and deepest freshwater lake.</string>

</resources>


text:
Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}

/**
* I convert a day string to an number.
*
* @method dayOfWeekAsInteger
* @param {String} day
* @return {Number} Returns day as number
*/

function dayOfWeekAsInteger(day) {
  return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day];
}

/**
* Compare 2 arrays with subarrays whose values are objects!.
* for example arr1 = [{id1:value1, id2:value2, ...},{id1:value1, id2:value2, ...}]
* and arr2 = [{id1:value1, id2:value2, ...},{id1:value1, id2:value2, ...}]
*
* @method compare_arrays_of_obj
* @param {arrays of objects} arr1, arr2
* @return {Boolean} Returns true if the arrays are the same or false if not
*/
function compare_arrays_of_obj(arr1, arr2){
    if(arr1.length!=arr2.length){
        // console.log("not the same array length");
        return false;
    }
    else {
        var length=arr1.length;
    }
    //itterating the array:
    for (var i = length - 1; i >= 0; i--) {
        var obj1 = arr1[i];
        var obj2 = arr2[i];
        if(Object.keys(obj1).length != Object.keys(obj2).length){
            // console.log("the objects are not the same length");
            return false;
        }
        for (var key in obj1) {
            if(obj1[key]!=obj2[key]){ //I know they have exactly the same keys. If there would be a difference then it wound be in the values
                console.log("Found a difference in: "+key);
                // console.log(obj1[key]);
                // console.log(obj2[key]);
                return false;
            }
        };
    }
    //found no difference!
    return true;
}

/**
* Compare 2 arrays with subarrays whose values are objects!.
* This function might be more generic than the above... I have to check it ...
*/
function isEqual(value, other) {

	// Get the value type
	var type = Object.prototype.toString.call(value);

	// If the two objects are not the same type, return false
	if (type !== Object.prototype.toString.call(other)) return false;

	// If items are not an object or array, return false
	if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;

	// Compare the length of the length of the two items
	var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
	var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
	if (valueLen !== otherLen) return false;

	// Compare two items
	var compare = function (item1, item2) {

		// Get the object type
		var itemType = Object.prototype.toString.call(item1);

		// If an object or array, compare recursively
		if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
			if (!isEqual(item1, item2)) return false;
		}

		// Otherwise, do a simple comparison
		else {

			// If the two items are not the same type, return false
			if (itemType !== Object.prototype.toString.call(item2)) return false;

			// Else if it's a function, convert to a string and compare
			// Otherwise, just compare
			if (itemType === '[object Function]') {
				if (item1.toString() !== item2.toString()) return false;
			} else {
				if (item1 !== item2) return false;
			}

		}
	};

	// Compare properties
	if (type === '[object Array]') {
		for (var i = 0; i < valueLen; i++) {
			if (compare(value[i], other[i]) === false) return false;
		}
	} else {
		for (var key in value) {
			if (value.hasOwnProperty(key)) {
				if (compare(value[key], other[key]) === false) return false;
			}
		}
	}

	// If nothing failed, return true
	return true;

};

/*Cookie Functions*/

function createCookie(name, value)
{
    document.cookie=name+"="+escape(value)+"; path=/";
}

function readCookie(name)
{
    var re=new RegExp("(?:^|;)\\s?"+name+"=(.*?)(?:;|$)", "i"), result=document.cookie.match(re), output=null;
    if (result!=null)
    {
        output=unescape(result[1]);
    }
    return output;
}

function eraseCookie(name)
{
    var d=new Date();
    document.cookie=name+"=; path=/; expires="+d.toUTCString();
}


text:
/*
Simple library for controlling Adafruit LED 1.2" 8x8 Matrix
https://learn.adafruit.com/adafruit-led-backpack/1-2-8x8-matrix

Wiring:
GND -> Galileo GND
VCC -> Galileo 5V
SDA -> Galileo analog pin 4
SCL -> Galileo analog pin 5
*/

var mraa = require("mraa"); //require mraa
var i2C = new mraa.I2c(0);

// helper function to go from hex val to dec
function char(x) { return parseInt(x, 16); }

// Must be called once before using other functions
function init() {
    console.log("Initializing LED matrix controller");
    i2C.address(0x70);
    i2C.writeByte(char('0x21'));    // Turn on oscillator
    i2C.writeByte(char('0xef'));    // Brightness 15
    i2C.writeByte(char('0x81'));    // No blinking
}

/* Writes the Buffer of 8 bytes in the display's memory
    Attention: matrix columns are mapped to the bits as following:
    7 0 1 2 3 4 5 6
*/
function writeBuffer(buffer)
{
    // Add write command (zero byte) at the head of buffer
    var rawBuffer = new Buffer(buffer.length * 2 + 1);

    rawBuffer[0] = 0x00; // Write command

    for (var i = 0; i < buffer.length; i++)
    {
        rawBuffer[i*2 + 1] = buffer[i];
        rawBuffer[i*2 + 2] = 0;
    }
    i2C.write(rawBuffer);
}

// Clears the matrix
function clear() {
    console.log("LED: clear");
    var allZeroes =
    writeBuffer(new Buffer([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));

}

// Shows a smiling face
function smile() {
    console.log("LED: smile");
    var smiley = new Buffer([0x1E, 0x21, 0xCA, 0xD0, 0xD0, 0xCA, 0x21, 0x1E]);
    writeBuffer(smiley);
}

init();

clear();
smile();


text:
The Lua builtin function `type` has a disadvantage: it only returns the 'primitive'
Lua type of a value.  So if you want to implement your own typing system with custom
type names, `type` won't provide you any interesting information:

```lua
local object = setmetatable({}, { __type = 'object' })
print(type(object)) -- prints 'table'
```

Some libraries (such as the I/O library included with standard Lua) offer alternative
type functions for identifying types used within that library:

```lua
print(io.type(value) or type(value))
```

Typical is a library that offers an enhanced version of `type` that is meant to be
more generic:

```lua
local type = require 'typical'
local object = setmetatable({}, { __type = 'object' })
print(type(object)) -- prints 'object'
```

Typical is *very* simple: it looks for a `__type` metafield on an object.
If it's a function, it passes the value to the function and uses the result
as the type name.  If it's a string, it uses that.  If `__type` is `nil`
or returns `nil`, the builtin `type` is used.

# Library Overview

If you want to use typical just like a function, you can:

```lua
local type = require 'typical'
```

However, the type object is just an alias for `typical.type`:

```lua
local typical = require 'typical'
print(typical.type(value)) -- same as typical(value)
```

Typical also provides other type-related methods for your convenience;
you can read about them in the 'Methods' section.

# Methods

## typical.type(value)

Returns the type name for a value.


text:
<?php
//-----------------------------------------------------------------------------------------------
//My Program-O Version: 2.3.1
//Program-O  chatbot admin area
//Written by Elizabeth Perreau and Dave Morton
//Aug 2011
//for more information and support please visit www.program-o.com
//-----------------------------------------------------------------------------------------------
// wordcensor.php
  $msg = '';
  $upperScripts = <<<endScript

endScript;
  $post_vars = filter_input_array(INPUT_POST);
  $get_vars = filter_input_array(INPUT_GET);
  $request_vars = (array)$post_vars + (array)$get_vars;
  $group = (isset($request_vars['group'])) ? $request_vars['group'] : 1;
  $content  = $template->getSection('SearchWordCensorForm');
  $wc_action = isset($request_vars['action']) ? strtolower($request_vars['action']) : '';
  $wc_id = isset($request_vars['censor_id']) ? $request_vars['censor_id'] : -1;
  if (!empty($wc_action)) {
    switch($wc_action) {
      case 'search':
        $content .= runWordCensorSearch();
        $content .= wordCensorForm();
        break;
      case 'update':
        $x = updateWordCensor();
        $content .= wordCensorForm();
        break;
      case 'delete':
        $content .= ($wc_id >= 0) ? delWordCensor($wc_id) . wordCensorForm() : wordCensorForm();
        break;
      case 'edit':
        $content .= ($wc_id >= 0) ? editWordCensorForm($wc_id) : wordCensorForm();
        break;
      case 'add':
        $x = insertWordCensor();
        $content .= wordCensorForm();
        break;
      default:
        $content .= wordCensorForm();
    }
  }
  else {
    $content .= wordCensorForm();
  }
  $content = str_replace('[group]', $group, $content);

    $topNav        = $template->getSection('TopNav');
    $leftNav       = $template->getSection('LeftNav');
    $main          = $template->getSection('Main');
    $topNavLinks   = makeLinks('top', $topLinks, 12);
    $navHeader     = $template->getSection('NavHeader');
    $rightNav      = $template->getSection('RightNav');
    $leftNavLinks  = makeLinks('left', $leftLinks, 12);
    $rightNavLinks = getWordCensorWords();
    $FooterInfo    = getFooter();
    $errMsgClass   = (!empty($msg)) ? "ShowError" : "HideError";
    $errMsgStyle   = $template->getSection($errMsgClass);
    $noLeftNav     = '';
    $noTopNav      = '';
    $noRightNav    = '';
    $headerTitle   = 'Actions:';
    $pageTitle     = 'My-Program O - Word Censor Editor';
    $mainContent   = $content;
    $mainTitle     = 'Word Censor Editor';

    $mainContent = str_replace('[wordCensorForm]', wordCensorForm(), $mainContent);
    $rightNav    = str_replace('[rightNavLinks]', $rightNavLinks, $rightNav);
    $rightNav    = str_replace('[navHeader]', $navHeader, $rightNav);
    $rightNav    = str_replace('[headerTitle]', paginate(), $rightNav);

  function paginate() {
    global $request_vars;
    $dbConn = db_open();
    $sql = "select count(*) from `wordcensor` where 1";
    if (($result = mysql_query($sql, $dbConn)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
    $row = mysql_fetch_assoc($result);
    mysql_free_result($result);
    $rowCount = $row[0];
    mysql_close($dbConn);
    $lastPage = intval($rowCount / 50);
    $remainder = ($rowCount / 50) - $lastPage;
    if ($remainder > 0) $lastPage++;
    $out = "Censored Words
\n50 words per page:
\n";
    $link=" - [label]";
    $curStart = (isset($request_vars['group'])) ? $request_vars['group'] : 1;
    $firstPage = 1;
    $prev  = ($curStart > ($firstPage + 1)) ? $curStart - 1 : -1;
    $next = ($lastPage > ($curStart + 1)) ? $curStart + 1 : -1;
    $firstLink = ($firstPage != $curStart) ? str_replace('[group]', '1', $link) : '';
    $prevLink = ($prev > 0) ? str_replace('[group]', $prev, $link) : '';
    $curLink = "- $curStart ";
    if (empty($firstLink) and empty($prevLink)) $curLink = $curStart;
    $nextLink = ($next > 0) ? str_replace('[group]', $next, $link) : '';
    $lastLink = ($lastPage > $curStart) ? str_replace('[group]', $lastPage, $link) : '';
    $firstLink = str_replace('[label]', 'first', $firstLink);
    $prevLink = str_replace('[label]', '<<', $prevLink);
    $nextLink = str_replace('[label]', '>>', $nextLink);
    $lastLink = str_replace('[label]', 'last', $lastLink);
    $out .= ltrim("$firstLink\n$prevLink\n$curLink\n$nextLink\n$lastLink", " - ");
    return $out;
  }

  function getWordCensorWords() {
    global $template, $request_vars;
    # pagination variables
    $group = (isset($request_vars['group'])) ? $request_vars['group'] : 1;
    $_SESSION['poadmin']['group'] = $group;
    $startEntry = ($group - 1) * 50;
    $startEntry = ($startEntry < 0) ? 0 : $startEntry;
    $end = $group + 50;
    $_SESSION['poadmin']['page_start'] = $group;
    $dbConn = db_open();
    $curID = (isset($request_vars['id'])) ? $request_vars['id'] : -1;
    $sql = "select `censor_id`,`word_to_censor` from `wordcensor` where 1 order by abs(`censor_id`) asc limit $startEntry, 50;";
    $baseLink = $template->getSection('NavLink');
    $links = '
' . "\n";
    if (($result = mysql_query($sql, $dbConn)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
    $count = 0;
    while ($row = mysql_fetch_assoc($result)) {
      $linkId = $row['censor_id'];
      $linkClass = ($linkId == $curID) ? 'selected' : 'noClass';
      $word_to_censor = $row['word_to_censor'];
      $tmpLink = str_replace('[linkClass]', " class=\"$linkClass\"", $baseLink);
      $linkHref = " href=\"index.php?page=wordcensor&action=edit&censor_id=$linkId&group=$group#$linkId\" name=\"$linkId\"";
      $tmpLink = str_replace('[linkHref]', $linkHref, $tmpLink);
      $tmpLink = str_replace('[linkOnclick]', '', $tmpLink);
      $tmpLink = str_replace('[linkTitle]', " title=\"Edit spelling replace_with for the word '$word_to_censor'\"", $tmpLink);
      $tmpLink = str_replace('[linkLabel]', $word_to_censor, $tmpLink);
      $links .= "$tmpLink\n";
      $count++;
    }
    mysql_free_result($result);
    $page_count = intval($count / 50);
    $_SESSION['poadmin']['page_count'] = $page_count + (($count / 50) > $page_count) ? 1 : 0;
    $links .= "\n
\n";
    return $links;
  }

function wordCensorForm() {
  global $template, $request_vars;
  $out = $template->getSection('WordCensorForm');
  $group = (isset($request_vars['group'])) ? $request_vars['group'] : 1;
  $out  = str_replace('[group]', $group, $out);
  return $out;
}

function insertWordCensor() {
    //global vars
    global $template, $msg, $request_vars;
    $dbConn = db_open();

    $replace_with = mysql_real_escape_string(trim($request_vars['replace_with']));
    $word_to_censor = mysql_real_escape_string(trim($request_vars['word_to_censor']));

    if(($replace_with == "") || ($word_to_censor == "")) {
        $msg = '
You must enter a spelling mistake and the replace_with.
' . "\n";
    }
    else {
        $sql = "INSERT INTO `wordcensor` (`censor_id`, `word_to_censor`, `replace_with`, `bot_exclude`) VALUES (NULL,'$word_to_censor','$replace_with', '')";
        if (($result = mysql_query($sql, $dbConn)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");

        if($result) {
            $msg = '
Correction added.
';
        }
        else {
            $msg = '
There was a problem editing the replace_with - no changes made.
';
        }
    }
    mysql_close($dbConn);

    return $msg;
}

function delWordCensor($id) {
    global $template, $msg;
    $dbConn = db_open();
    if($id=="") {
        $msg = '
There was a problem editing the replace_with - no changes made.
';
    }
    else {
        $sql = "DELETE FROM `wordcensor` WHERE `censor_id` = '$id' LIMIT 1";
        if (($result = mysql_query($sql, $dbConn)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
        if($result) {
            $msg = '
Correction deleted.
';
        }
        else {
            $msg = '
There was a problem editing the replace_with - no changes made.
';
        }
    }
    mysql_close($dbConn);
}

function runWordCensorSearch() {
    //global vars
    global $template, $request_vars;
    $dbConn = db_open();
    $i=0;
    $search = mysql_real_escape_string(trim($request_vars['search']));
    $sql = "SELECT * FROM `wordcensor` WHERE `word_to_censor` LIKE '%$search%' OR `replace_with` LIKE '%$search%' LIMIT 50";
    if (($result = mysql_query($sql, $dbConn)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
    $htmltbl = '

                      word_to_censor
                      Correction
                      Action

';
    while($row=mysql_fetch_assoc($result)) {
        $i++;
        $word_to_censor = (IS_MB_ENABLED) ? mb_strtoupper($row['word_to_censor']) : strtoupper($row['word_to_censor']);
        $replace_with = (IS_MB_ENABLED) ? mb_strtoupper($row['replace_with']) : strtoupper($row['replace_with']);
        $id = $row['censor_id'];
        $group = round(($id / 50));
        $action = "
                    ";
        $htmltbl .= "

                            $word_to_censor
                            $replace_with
                            $action

";
    }
    mysql_free_result($result);
    $htmltbl .= "

";

    if($i >= 50) {
        $msg = "Found more than 50 results for '$search', please refine your search further";
    }
    elseif($i == 0) {
        $msg = "Found 0 results for '$search'. You can use the form below to add that entry.";
        $htmltbl="";
    }
    else {
        $msg = "Found $i results for '$search'";
    }
    $htmlresults = "
$msg
".$htmltbl;
    mysql_close($dbConn);
    return $htmlresults;
}

function editWordCensorForm($id) {
  //global vars
  global $template, $request_vars, $con;
  $group = (isset($request_vars['group'])) ? $request_vars['group'] : 1;
  $form   = $template->getSection('EditWordCensorForm');
  $con = db_open();
  $sql    = "SELECT * FROM `wordcensor` WHERE `censor_id` = '$id' LIMIT 1";
  if (($result = mysql_query($sql, $con)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
  $row    = mysql_fetch_assoc($result);
  $uc_word_to_censor = (IS_MB_ENABLED) ? mb_strtoupper($row['word_to_censor']) : strtoupper($row['word_to_censor']);
  $uc_replace_with = (IS_MB_ENABLED) ? mb_strtoupper($row['replace_with']) : strtoupper($row['replace_with']);
  $form   = str_replace('[censor_id]', $row['censor_id'], $form);
  $form   = str_replace('[word_to_censor]', $uc_word_to_censor, $form);
  $form   = str_replace('[replace_with]', $uc_replace_with, $form);
  $form   = str_replace('[group]', $group, $form);
  mysql_free_result($result);
  return $form;
}

function updateWordCensor() {
  //global vars
  global $template, $msg, $request_vars, $con;
  $con = db_open();
  $word_to_censor = mysql_real_escape_string(trim($request_vars['word_to_censor']));
  $replace_with = mysql_real_escape_string(trim($request_vars['replace_with']));
  $id = trim($request_vars['id']);
  if(($id=="")||($word_to_censor=="")||($replace_with=="")) {
    $msg = '
There was a problem editing the replace_with - no changes made.
';
  }
  else {
    $sql = "UPDATE `wordcensor` SET `word_to_censor` = '$word_to_censor',`replace_with`='$replace_with' WHERE `censor_id`='$id' LIMIT 1";
    if (($result = mysql_query($sql, $con)) === false) throw new Exception('You have a SQL error on line '. __LINE__ . ' of ' . __FILE__ . '. Error message is: ' . mysql_error() . ".
\nSQL = $sql
\n");
    if($result) {
      $msg = '
Correction edited.
';
    }
    else {
      $msg = '
There was a problem editing the replace_with - no changes made.
';
    }
  }
}

?>


text:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point;

typedef CGAL::Delaunay_triangulation_2<K> Triangulation;

// As we only consider finite vertices and edges
// we need the following filter

template <typename T>
struct Is_finite {

  const T* t_;

  Is_finite()
    : t_(NULL)
  {}

  Is_finite(const T& t)
    : t_(&t)
  { }

  template <typename VertexOrEdge>
  bool operator()(const VertexOrEdge& voe) const {
    return ! t_->is_infinite(voe);
  }
};

typedef Is_finite<Triangulation> Filter;
typedef boost::filtered_graph<Triangulation,Filter,Filter> Finite_triangulation;
typedef boost::graph_traits<Finite_triangulation>::vertex_descriptor vertex_descriptor;
typedef boost::graph_traits<Finite_triangulation>::vertex_iterator vertex_iterator;
typedef boost::graph_traits<Finite_triangulation>::edge_descriptor edge_descriptor;

// The BGL makes use of indices associated to the vertices
// We use a std::map to store the index
typedef std::map<vertex_descriptor,int> VertexIndexMap;
VertexIndexMap vertex_id_map;

// A std::map is not a property map, because it is not lightweight
typedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;
VertexIdPropertyMap vertex_index_pmap(vertex_id_map);

int
main(int,char*[])
{
  Triangulation t;
  Filter is_finite(t);
  Finite_triangulation ft(t, is_finite, is_finite);

  Point p ;
  while(std::cin >> p){
    t.insert(p);
  }

  vertex_iterator vit, ve;
  // Associate indices to the vertices
  int index = 0;
  // boost::tie assigns the first and second element of the std::pair
  // returned by boost::vertices to the variables vit and ve
  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){
    vertex_descriptor  vd = *vit;
    vertex_id_map[vd]= index++;
    }

  // We use the default edge weight which is the squared length of the edge
  // This property map is defined in graph_traits_Triangulation_2.h

  // In the function call you can see a named parameter: vertex_index_map
   std::list<edge_descriptor> mst;
   boost::kruskal_minimum_spanning_tree(t,
					std::back_inserter(mst),
					vertex_index_map(vertex_index_pmap));

   std::cout << "The edges of the Euclidean mimimum spanning tree:" << std::endl;

   for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it){
     edge_descriptor ed = *it;
     vertex_descriptor svd = boost::source(ed,t);
     vertex_descriptor tvd = boost::target(ed,t);
     Triangulation::Vertex_handle sv = svd;
     Triangulation::Vertex_handle tv = tvd;
     std::cout << "[ " << sv->point() << "  |  " << tv->point() << " ] " << std::endl;
   }

   return 0;
}


text:
package james.monochrome.data;

import james.monochrome.utils.MapUtils;

public class PositionData {

    private String mapKey;
    private int x, y;

    public PositionData(String mapKey, int x, int y) {
        this.mapKey = mapKey;
        this.x = x;
        this.y = y;
    }

    public PositionData(String mapKey, int sceneX, int sceneY, int tileX, int tileY) {
        this.mapKey = mapKey;
        x = (sceneX * 10) + tileX;
        y = (sceneY * 10) + tileY;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public String getMapKey() {
        return mapKey;
    }

    public int getSceneX() {
        return x / 10;
    }

    public int getSceneY() {
        return y / 10;
    }

    public int getTileX() {
        return x % 10;
    }

    public int getTileY() {
        return y % 10;
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj) || (obj != null && obj instanceof PositionData && MapUtils.getTileId(this).equals(MapUtils.getTileId((PositionData) obj)));
    }
}


text:
"""Off-Policy Evaluation Class to Streamline OPE with Multiple Loggers."""
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union

import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
import seaborn as sns
from sklearn.utils import check_scalar

from ..utils import check_array
from ..utils import check_confidence_interval_arguments
from .estimators import DirectMethod as DM
from .estimators_multi import MultiLoggersBalancedDoublyRobust as BalDR
from .estimators_multi import MultiLoggersNaiveDoublyRobust as NaiveDR
from .estimators_multi import MultiLoggersWeightedDoublyRobust as WeightedDR
from .meta import OffPolicyEvaluation

logger = getLogger(__name__)

@dataclass
class MultiLoggersOffPolicyEvaluation(OffPolicyEvaluation):
    """Class to conduct OPE with multiple loggers using multiple estimators simultaneously.

    Parameters
    -----------
    bandit_feedback: BanditFeedback
        Logged bandit data used to conduct OPE.

    ope_estimators: List[BaseMultiLoggersOffPolicyEstimator]
        List of OPE estimators used to evaluate the policy value of evaluation policy.
        Estimators must follow the interface of `BaseMultiLoggersOffPolicyEstimator`.

    Examples
    ----------

        .. code-block:: python

            # a case of implementing OPE (with multiple loggers) of an synthetic evaluation policy
            >>> from obp.dataset import (
                    SyntheticMultiLoggersBanditDataset,
                    logistic_reward_function,
                )
            >>> from obp.ope import (
                    MultiLoggersOffPolicyEvaluation,
                    MultiLoggersNaiveInverseProbabilityWeighting as NaiveIPW,
                    MultiLoggersBalancedInverseProbabilityWeighting as BalIPW,
                    MultiLoggersWeightedInverseProbabilityWeighting as WeightedIPW,
                )
            >>> from obp.utils import softmax

            # (1) Synthetic Data Generation
            >>> dataset = SyntheticMultiLoggersBanditDataset(
                    n_actions=10,
                    dim_context=5,
                    reward_function=logistic_reward_function,
                    betas=[-5, 0, 5],
                    rhos=[1, 1, 1],
                    random_state=12345,
                )
            >>> bandit_feedback = dataset.obtain_batch_bandit_feedback(n_rounds=10000)

            # (2) Synthetic Evaluation Policy
            >>> expected_reward = bandit_feedback["expected_reward"]
            >>> pi_e = softmax(10 * expected_reward)[:, :, np.newaxis]

            # (3) Off-Policy Evaluation
            >>> ope = MultiLoggersOffPolicyEvaluation(
                    bandit_feedback=bandit_feedback,
                    ope_estimators=[NaiveIPW(), BalIPW(), WeightedIPW()]
                )
            >>> estimated_policy_values = ope.estimate_policy_values(action_dist=pi_e)
            >>> estimated_policy_values

            {'multi_ipw': 0.735773315700805,
            'multi_bal_ipw': 0.7369963734186821,
            'multi_weighted_ipw': 0.7340662935948596}

            # (4) Ground-truth Policy Value of the Synthetic Evaluation Policy
            >>> dataset.calc_ground_truth_policy_value(
                    action_dist=pi_e, expected_reward=expected_reward,
                )

            0.7406153992278186

    """

    def __post_init__(self) -> None:
        """Initialize class."""
        for key_ in ["action", "position", "reward"]:
            if key_ not in self.bandit_feedback:
                raise RuntimeError(f"Missing key of {key_} in 'bandit_feedback'.")
        self.ope_estimators_ = dict()
        self.is_model_dependent = False
        for estimator in self.ope_estimators:
            self.ope_estimators_[estimator.estimator_name] = estimator
            if (
                isinstance(estimator, DM)
                or isinstance(estimator, NaiveDR)
                or isinstance(estimator, BalDR)
                or isinstance(estimator, WeightedDR)
            ):
                self.is_model_dependent = True

    def _create_estimator_inputs(
        self,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
    ) -> Dict[str, Dict[str, np.ndarray]]:
        """Create input dictionary to estimate policy value using subclasses of `BaseOffPolicyEstimator`"""
        check_array(array=action_dist, name="action_dist", expected_dim=3)
        if estimated_rewards_by_reg_model is None:
            pass
        elif isinstance(estimated_rewards_by_reg_model, dict):
            for estimator_name, value in estimated_rewards_by_reg_model.items():
                check_array(
                    array=value,
                    name=f"estimated_rewards_by_reg_model[{estimator_name}]",
                    expected_dim=3,
                )
                if value.shape != action_dist.shape:
                    raise ValueError(
                        f"Expected `estimated_rewards_by_reg_model[{estimator_name}].shape == action_dist.shape`, but found it False."
                    )
        else:
            check_array(
                array=estimated_rewards_by_reg_model,
                name="estimated_rewards_by_reg_model",
                expected_dim=3,
            )
            if estimated_rewards_by_reg_model.shape != action_dist.shape:
                raise ValueError(
                    "Expected `estimated_rewards_by_reg_model.shape == action_dist.shape`, but found it False"
                )
        for var_name, value_or_dict in {
            "estimated_pscore": estimated_pscore,
            "estimated_pscore_avg": estimated_pscore_avg,
        }.items():
            if value_or_dict is None:
                pass
            elif isinstance(value_or_dict, dict):
                for estimator_name, value in value_or_dict.items():
                    check_array(
                        array=value,
                        name=f"{var_name}[{estimator_name}]",
                        expected_dim=1,
                    )
                    if value.shape[0] != action_dist.shape[0]:
                        raise ValueError(
                            f"Expected `{var_name}[{estimator_name}].shape[0] == action_dist.shape[0]`, but found it False"
                        )
            else:
                check_array(array=value_or_dict, name=var_name, expected_dim=1)
                if value_or_dict.shape[0] != action_dist.shape[0]:
                    raise ValueError(
                        f"Expected `{var_name}.shape[0] == action_dist.shape[0]`, but found it False"
                    )

        estimator_inputs = {
            estimator_name: {
                input_: self.bandit_feedback[input_]
                for input_ in ["reward", "action", "position"]
            }
            for estimator_name in self.ope_estimators_
        }
        for estimator_name in self.ope_estimators_:
            for input_ in ["stratum_idx", "pscore", "pscore_avg"]:
                if input_ in self.bandit_feedback:
                    estimator_inputs[estimator_name][input_] = self.bandit_feedback[
                        input_
                    ]
                else:
                    estimator_inputs[estimator_name][input_] = None
            estimator_inputs[estimator_name]["action_dist"] = action_dist
            estimator_inputs = self._preprocess_model_based_input(
                estimator_inputs=estimator_inputs,
                estimator_name=estimator_name,
                model_based_input={
                    "estimated_rewards_by_reg_model": estimated_rewards_by_reg_model,
                    "estimated_pscore": estimated_pscore,
                    "estimated_pscore_avg": estimated_pscore_avg,
                },
            )
        return estimator_inputs

    def estimate_policy_values(
        self,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
    ) -> Dict[str, float]:
        """Estimate the policy value of evaluation policy.

        Parameters
        ------------
        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Expected rewards given each round, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_k(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        Returns
        ----------
        policy_value_dict: Dict[str, float]
            Dictionary containing the policy values estimated by OPE estimators.

        """
        if self.is_model_dependent:
            if estimated_rewards_by_reg_model is None:
                raise ValueError(
                    "When model dependent estimators such as DM or DR are used, `estimated_rewards_by_reg_model` must be given"
                )

        policy_value_dict = dict()
        estimator_inputs = self._create_estimator_inputs(
            action_dist=action_dist,
            estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
            estimated_pscore=estimated_pscore,
            estimated_pscore_avg=estimated_pscore_avg,
        )
        for estimator_name, estimator in self.ope_estimators_.items():
            policy_value_dict[estimator_name] = estimator.estimate_policy_value(
                **estimator_inputs[estimator_name]
            )
        return policy_value_dict

    def estimate_intervals(
        self,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        alpha: float = 0.05,
        n_bootstrap_samples: int = 100,
        random_state: Optional[int] = None,
    ) -> Dict[str, Dict[str, float]]:
        """Estimate confidence intervals of policy values using bootstrap.

        Parameters
        ------------
        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        alpha: float, default=0.05
            Significance level.

        n_bootstrap_samples: int, default=100
            Number of resampling performed in bootstrap sampling.

        random_state: int, default=None
            Controls the random seed in bootstrap sampling.

        Returns
        ----------
        policy_value_interval_dict: Dict[str, Dict[str, float]]
            Dictionary containing confidence intervals of the estimated policy values.

        """
        if self.is_model_dependent:
            if estimated_rewards_by_reg_model is None:
                raise ValueError(
                    "When model dependent estimators such as DM or DR are used, `estimated_rewards_by_reg_model` must be given"
                )

        check_confidence_interval_arguments(
            alpha=alpha,
            n_bootstrap_samples=n_bootstrap_samples,
            random_state=random_state,
        )
        policy_value_interval_dict = dict()
        estimator_inputs = self._create_estimator_inputs(
            action_dist=action_dist,
            estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
            estimated_pscore=estimated_pscore,
            estimated_pscore_avg=estimated_pscore_avg,
        )
        for estimator_name, estimator in self.ope_estimators_.items():
            policy_value_interval_dict[estimator_name] = estimator.estimate_interval(
                **estimator_inputs[estimator_name],
                alpha=alpha,
                n_bootstrap_samples=n_bootstrap_samples,
                random_state=random_state,
            )

        return policy_value_interval_dict

    def summarize_off_policy_estimates(
        self,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        alpha: float = 0.05,
        n_bootstrap_samples: int = 100,
        random_state: Optional[int] = None,
    ) -> Tuple[DataFrame, DataFrame]:
        """Summarize policy values and their confidence intervals estimated by OPE estimators.

        Parameters
        ------------
        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Expected rewards given each round, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        alpha: float, default=0.05
            Significance level.

        n_bootstrap_samples: int, default=100
            Number of resampling performed in bootstrap sampling.

        random_state: int, default=None
            Controls the random seed in bootstrap sampling.

        Returns
        ----------
        (policy_value_df, policy_value_interval_df): Tuple[DataFrame, DataFrame]
            Policy values and their confidence intervals estimated by OPE estimators.

        """
        policy_value_df = DataFrame(
            self.estimate_policy_values(
                action_dist=action_dist,
                estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
                estimated_pscore=estimated_pscore,
                estimated_pscore_avg=estimated_pscore_avg,
            ),
            index=["estimated_policy_value"],
        )
        policy_value_interval_df = DataFrame(
            self.estimate_intervals(
                action_dist=action_dist,
                estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
                estimated_pscore=estimated_pscore,
                estimated_pscore_avg=estimated_pscore_avg,
                alpha=alpha,
                n_bootstrap_samples=n_bootstrap_samples,
                random_state=random_state,
            )
        )
        policy_value_of_behavior_policy = self.bandit_feedback["reward"].mean()
        policy_value_df = policy_value_df.T
        if policy_value_of_behavior_policy <= 0:
            logger.warning(
                f"Policy value of the behavior policy is {policy_value_of_behavior_policy} (<=0); relative estimated policy value is set to np.nan"
            )
            policy_value_df["relative_estimated_policy_value"] = np.nan
        else:
            policy_value_df["relative_estimated_policy_value"] = (
                policy_value_df.estimated_policy_value / policy_value_of_behavior_policy
            )
        return policy_value_df, policy_value_interval_df.T

    def visualize_off_policy_estimates(
        self,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        alpha: float = 0.05,
        is_relative: bool = False,
        n_bootstrap_samples: int = 100,
        random_state: Optional[int] = None,
        fig_dir: Optional[Path] = None,
        fig_name: str = "estimated_policy_value.png",
    ) -> None:
        """Visualize the estimated policy values.

        Parameters
        ----------
        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        alpha: float, default=0.05
            Significance level.

        n_bootstrap_samples: int, default=100
            Number of resampling performed in bootstrap sampling.

        random_state: int, default=None
            Controls the random seed in bootstrap sampling.

        is_relative: bool, default=False,
            If True, the method visualizes the estimated policy values of evaluation policy
            relative to the ground-truth policy value of behavior policy.

        fig_dir: Path, default=None
            Path to store the bar figure.
            If None, the figure will not be saved.

        fig_name: str, default="estimated_policy_value.png"
            Name of the bar figure.

        """
        if fig_dir is not None:
            assert isinstance(fig_dir, Path), "`fig_dir` must be a Path"
        if fig_name is not None:
            assert isinstance(fig_name, str), "`fig_dir` must be a string"

        estimated_round_rewards_dict = dict()
        estimator_inputs = self._create_estimator_inputs(
            action_dist=action_dist,
            estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
            estimated_pscore=estimated_pscore,
            estimated_pscore_avg=estimated_pscore_avg,
        )
        for estimator_name, estimator in self.ope_estimators_.items():
            estimated_round_rewards_dict[
                estimator_name
            ] = estimator._estimate_round_rewards(**estimator_inputs[estimator_name])
        estimated_round_rewards_df = DataFrame(estimated_round_rewards_dict)
        estimated_round_rewards_df.rename(
            columns={key: key.upper() for key in estimated_round_rewards_dict.keys()},
            inplace=True,
        )
        if is_relative:
            estimated_round_rewards_df /= self.bandit_feedback["reward"].mean()

        plt.style.use("ggplot")
        fig, ax = plt.subplots(figsize=(8, 6))
        sns.barplot(
            data=estimated_round_rewards_df,
            ax=ax,
            ci=100 * (1 - alpha),
            n_boot=n_bootstrap_samples,
            seed=random_state,
        )
        plt.xlabel("OPE Estimators", fontsize=25)
        plt.ylabel(
            f"Estimated Policy Value (± {np.int32(100*(1 - alpha))}% CI)", fontsize=20
        )
        plt.yticks(fontsize=15)
        plt.xticks(fontsize=25 - 2 * len(self.ope_estimators))

        if fig_dir:
            fig.savefig(str(fig_dir / fig_name))

    def evaluate_performance_of_estimators(
        self,
        ground_truth_policy_value: float,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        metric: str = "se",
    ) -> Dict[str, float]:
        """Evaluate the accuracy of OPE estimators.

        Note
        ------
        Evaluate the estimation performance of OPE estimators with relative estimation error (relative-EE) or squared error (SE):

        .. math ::

            \\text{Relative-EE} (\\hat{V}; \\mathcal{D}) = \\left|  \\frac{\\hat{V}(\\pi; \\mathcal{D}) - V(\\pi)}{V(\\pi)} \\right|,

        .. math ::

            \\text{SE} (\\hat{V}; \\mathcal{D}) = \\left(\\hat{V}(\\pi; \\mathcal{D}) - V(\\pi) \\right)^2,

        where :math:`V({\\pi})` is the ground-truth policy value of the evalation policy :math:`\\pi_e` (often estimated using on-policy estimation).
        :math:`\\hat{V}(\\pi; \\mathcal{D})` is the policy value estimated by an OPE estimator :math:`\\hat{V}` and logged bandit feedback :math:`\\mathcal{D}`.

        Parameters
        ----------
        ground_truth policy value: float
            Ground_truth policy value of evaluation policy, i.e., :math:`V(\\pi_e)`.
            With Open Bandit Dataset, we use an on-policy estimate of the policy value as its ground-truth.

        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        metric: str, default="se"
            Evaluation metric used to evaluate and compare the estimation performance of OPE estimators.
            Must be either "relative-ee" or "se".

        Returns
        ----------
        eval_metric_ope_dict: Dict[str, float]
            Dictionary containing the value of evaluation metric for the estimation performance of OPE estimators.

        """
        check_scalar(
            ground_truth_policy_value,
            "ground_truth_policy_value",
            float,
        )
        if metric not in ["relative-ee", "se"]:
            raise ValueError(
                f"`metric` must be either 'relative-ee' or 'se', but {metric} is given"
            )
        if metric == "relative-ee" and ground_truth_policy_value == 0.0:
            raise ValueError(
                "`ground_truth_policy_value` must be non-zero when metric is relative-ee"
            )

        eval_metric_ope_dict = dict()
        estimator_inputs = self._create_estimator_inputs(
            action_dist=action_dist,
            estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
            estimated_pscore=estimated_pscore,
            estimated_pscore_avg=estimated_pscore_avg,
        )
        for estimator_name, estimator in self.ope_estimators_.items():
            estimated_policy_value = estimator.estimate_policy_value(
                **estimator_inputs[estimator_name]
            )
            if metric == "relative-ee":
                relative_ee_ = estimated_policy_value - ground_truth_policy_value
                relative_ee_ /= ground_truth_policy_value
                eval_metric_ope_dict[estimator_name] = np.abs(relative_ee_)
            elif metric == "se":
                se_ = (estimated_policy_value - ground_truth_policy_value) ** 2
                eval_metric_ope_dict[estimator_name] = se_
        return eval_metric_ope_dict

    def summarize_estimators_comparison(
        self,
        ground_truth_policy_value: float,
        action_dist: np.ndarray,
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        metric: str = "se",
    ) -> DataFrame:
        """Summarize the performance comparison among OPE estimators.

        Parameters
        ----------
        ground_truth policy value: float
            Ground_truth policy value of evaluation policy, i.e., :math:`V(\\pi_e)`.
            With Open Bandit Dataset, we use an on-policy estimate of the policy value as ground-truth.

        action_dist: array-like, shape (n_rounds, n_actions, len_list)
            Action choice probabilities of the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list), default=None
            Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        metric: str, default="se"
            Evaluation metric used to evaluate and compare the estimation performance of OPE estimators.
            Must be either "relative-ee" or "se".

        Returns
        ----------
        eval_metric_ope_df: DataFrame
            Results of performance comparison among OPE estimators.

        """
        eval_metric_ope_df = DataFrame(
            self.evaluate_performance_of_estimators(
                ground_truth_policy_value=ground_truth_policy_value,
                action_dist=action_dist,
                estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
                estimated_pscore=estimated_pscore,
                estimated_pscore_avg=estimated_pscore_avg,
                metric=metric,
            ),
            index=[metric],
        )
        return eval_metric_ope_df.T

    def visualize_off_policy_estimates_of_multiple_policies(
        self,
        policy_name_list: List[str],
        action_dist_list: List[np.ndarray],
        estimated_rewards_by_reg_model: Optional[
            Union[np.ndarray, Dict[str, np.ndarray]]
        ] = None,
        estimated_pscore: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        estimated_pscore_avg: Optional[Union[np.ndarray, Dict[str, np.ndarray]]] = None,
        alpha: float = 0.05,
        is_relative: bool = False,
        n_bootstrap_samples: int = 100,
        random_state: Optional[int] = None,
        fig_dir: Optional[Path] = None,
        fig_name: str = "estimated_policy_value.png",
    ) -> None:
        """Visualize the estimated policy values.

        Parameters
        ----------
        policy_name_list: List[str]
            List of the names of evaluation policies.

        action_dist_list: List[array-like, shape (n_rounds, n_actions, len_list)]
            List of action choice probabilities of the evaluation policies (can be deterministic), i.e., :math:`\\pi_e(a_i|x_i)`.

        estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) or Dict[str, array-like], default=None
            Estimated expected rewards given context, action, and position, i.e., :math:`\\hat{q}(x_i,a_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict is given, if the dict has the name of an estimator as a key, the corresponding value is used.
            If None, model-dependent estimators such as DM and DR cannot be used.

        estimated_pscore: array-like, shape (n_rounds,), default=None
            Estimated behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_b(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        estimated_pscore_avg: array-like, shape (n_rounds,), default=None
            Estimated average behavior policy (propensity scores), i.e., :math:`\\hat{\\pi}_{avg}(a_i|x_i)`.
            When an array-like is given, all OPE estimators use it.
            When a dict with an estimator's name as its key is given, the corresponding value is used for the estimator.

        alpha: float, default=0.05
            Significance level.

        n_bootstrap_samples: int, default=100
            Number of resampling performed in bootstrap sampling.

        random_state: int, default=None
            Controls the random seed in bootstrap sampling.

        is_relative: bool, default=False,
            If True, the method visualizes the estimated policy values of evaluation policy
            relative to the ground-truth policy value of behavior policy.

        fig_dir: Path, default=None
            Path to store the bar figure.
            If None, the figure will not be saved.

        fig_name: str, default="estimated_policy_value.png"
            Name of the bar figure.

        """
        if len(policy_name_list) != len(action_dist_list):
            raise ValueError(
                "the length of `policy_name_list` must be the same as `action_dist_list`"
            )
        if fig_dir is not None:
            assert isinstance(fig_dir, Path), "`fig_dir` must be a Path"
        if fig_name is not None:
            assert isinstance(fig_name, str), "`fig_dir` must be a string"

        estimated_round_rewards_dict = {
            estimator_name: {} for estimator_name in self.ope_estimators_
        }

        for policy_name, action_dist in zip(policy_name_list, action_dist_list):
            estimator_inputs = self._create_estimator_inputs(
                action_dist=action_dist,
                estimated_rewards_by_reg_model=estimated_rewards_by_reg_model,
                estimated_pscore=estimated_pscore,
                estimated_pscore_avg=estimated_pscore_avg,
            )
            for estimator_name, estimator in self.ope_estimators_.items():
                estimated_round_rewards_dict[estimator_name][
                    policy_name
                ] = estimator._estimate_round_rewards(
                    **estimator_inputs[estimator_name]
                )

        plt.style.use("ggplot")
        fig = plt.figure(figsize=(8, 6.2 * len(self.ope_estimators_)))

        for i, estimator_name in enumerate(self.ope_estimators_):
            estimated_round_rewards_df = DataFrame(
                estimated_round_rewards_dict[estimator_name]
            )
            if is_relative:
                estimated_round_rewards_df /= self.bandit_feedback["reward"].mean()

            ax = fig.add_subplot(len(action_dist_list), 1, i + 1)
            sns.barplot(
                data=estimated_round_rewards_df,
                ax=ax,
                ci=100 * (1 - alpha),
                n_boot=n_bootstrap_samples,
                seed=random_state,
            )
            ax.set_title(estimator_name.upper(), fontsize=20)
            ax.set_ylabel(
                f"Estimated Policy Value (± {np.int32(100*(1 - alpha))}% CI)",
                fontsize=20,
            )
            plt.yticks(fontsize=15)
            plt.xticks(fontsize=25 - 2 * len(policy_name_list))

        if fig_dir:
            fig.savefig(str(fig_dir / fig_name))


text:
package org.mifos.framework.business.service;

import org.mifos.framework.business.BusinessObject;
import org.mifos.framework.security.util.UserContext;

/**
 * Use of this class is @deprecated.
 *
 * BusinessService classes generally return BusinessObject instances. We plan to
 * migrate away from this pattern and define Service classes which return Data
 * Transfer Objects (DTOs) such that the service layer does not expose domain
 * objects.
 */
public interface BusinessService {

    public BusinessObject getBusinessObject(UserContext userContext);

}


text:
title: Remove Elements from a Linked List
localeTitle: 从链接列表中删除元素
---
## 从链接列表中删除元素

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/data-structures/remove-elements-from-a-linked-list/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。


text:
package cop.raml.mocks.tools;

/**
 * @author Oleg Cherednik
 * @since 10.01.2017
 */
@SuppressWarnings("ClassNamingConvention")
public final class JCTree {
    private final String path;

    public JCTree(String path) {
        this.path = path;
    }

    // ========== Object ==========

    @Override
    public String toString() {
        if (path == null)
            throw new RuntimeException("path == null");
        return path;
    }
}


text:
import unittest

import azure.mgmt.databricks
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer

AZURE_LOCATION = 'eastus'

class MgmtDatabricksClientTest(AzureMgmtTestCase):

    def setUp(self):
        super(MgmtDatabricksClientTest, self).setUp()
        self.mgmt_client = self.create_mgmt_client(
            azure.mgmt.databricks.DatabricksClient
        )

    @ unittest.skip("unavailable in track2")
    @ResourceGroupPreparer(location=AZURE_LOCATION)
    def test_databricks(self, resource_group):

        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
        WORKSPACE_NAME = "workspace1"
        RESOURCE_GROUP = "test_mgmt_databricks_test_resource_groups457f10501"

        # Create or update workspace[put]
        BODY = {
          "managed_resource_group_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "",
          "location": "westus"
        }
        result = self.mgmt_client.workspaces.create_or_update(BODY, resource_group.name, WORKSPACE_NAME)
        result = result.result()

        WORKSPACE_NAME_2 = WORKSPACE_NAME + "2"
        # Create or update workspace with custom parameters[put]
        BODY = {
          "managed_resource_group_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "",
          "location": "westus"
        }
        result = self.mgmt_client.workspaces.create_or_update(BODY, resource_group.name, WORKSPACE_NAME)
        result = result.result()

        # Get a workspace with custom parameters[get]
        result = self.mgmt_client.workspaces.get(resource_group.name, WORKSPACE_NAME)

        # Get a workspace[get]
        result = self.mgmt_client.workspaces.get(resource_group.name, WORKSPACE_NAME)

        # Lists workspaces[get]
        result = self.mgmt_client.workspaces.list_by_resource_group(resource_group.name)

        # Lists workspaces[get]
        result = self.mgmt_client.workspaces.list_by_resource_group(resource_group.name)

        # Operations[get]
        result = self.mgmt_client.operations.list()

        # Update a workspace's tags.[patch]
        # BODY = {
        #   "tags": {
        #     "mytag1": "myvalue1"
        #   }
        # }
        TAGS = {
          "mytag1": "myvalue1"
        }
        result = self.mgmt_client.workspaces.update(resource_group.name, WORKSPACE_NAME, TAGS)
        result = result.result()

        # Delete a workspace[delete]
        result = self.mgmt_client.workspaces.delete(resource_group.name, WORKSPACE_NAME)
        result = result.result()

#------------------------------------------------------------------------------
if __name__ == '__main__':
    unittest.main()


text:
package org.apache.ode.bpel.dao;

public interface ResourceRouteDAO {
    public String getUrl();

    public void setUrl(String url);

    public String getMethod();

    public void setMethod(String method);

    public String getPickResponseChannel();

    public void setPickResponseChannel(String pickResponseChannel);

    public int getSelectorIdx();

    public void setSelectorIdx(int selectorIdx);

    public ProcessInstanceDAO getInstance();

}


text:
package com.github.ruediste.c3java.method;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;

import java.lang.reflect.Method;

import org.junit.Test;

public class MethodUtilTest {

    private Method Bab;
    private Method Bb;
    private Method Aa;
    private Method Aab;
    private Method Ap;
    private Method Bp;
    private Method Ac;
    private Method Bc;

    private static class A {
        void a() {
        };

        void ab() {
        };

        private void p() {
        }

        private void c() {
        }

    }

    private static class B extends A {
        @Override
        void ab() {
        };

        void b() {
        };

        private void p() {
        }

        public void c() {
        };

    }

    public MethodUtilTest() throws Throwable {
        Aa = A.class.getDeclaredMethod("a");
        Aab = A.class.getDeclaredMethod("ab");
        Ap = A.class.getDeclaredMethod("p");
        Ac = A.class.getDeclaredMethod("c");

        Bab = B.class.getDeclaredMethod("ab");
        Bb = B.class.getDeclaredMethod("b");
        Bp = B.class.getDeclaredMethod("p");
        Bc = B.class.getDeclaredMethod("c");

    }

    @Test
    public void testGetDeclarations() throws Exception {
        assertThat(MethodUtil.getDeclarations(Aa), contains(Aa));
        assertThat(MethodUtil.getDeclarations(Bb), contains(Bb));
        assertThat(MethodUtil.getDeclarations(Bab), contains(Bab, Aab));
    }

    @Test
    public void testGetDeclarationsPrivate() throws Exception {
        assertThat(MethodUtil.getDeclarations(Ap), contains(Ap));
        assertThat(MethodUtil.getDeclarations(Bp), contains(Bp));
        assertThat(MethodUtil.getDeclarations(Ac), contains(Ac));
        assertThat(MethodUtil.getDeclarations(Bc), contains(Bc));
    }

}


text:
package com.exadel.borsch.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * @author Vlad
 */
public class BorschJdbcDaoSupport extends JdbcDaoSupport {

    private SimpleJdbcInsert jdbcInsert;

    public BorschJdbcDaoSupport(JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
        setJdbcInsert(new SimpleJdbcInsert(jdbcTemplate));
    }

    public SimpleJdbcInsert getJdbcInsert() {
        return jdbcInsert;
    }

    public void setJdbcInsert(SimpleJdbcInsert jdbcInsert) {
        this.jdbcInsert = jdbcInsert;
    }
}


text:
class UserSessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:email])
    if user && user.authenticate(params[:password])
      session[:user_id] = user.id
      flash[:success] = "Thanks for logging in!"
      redirect_to todo_lists_path
    else
      flash[:error] = "There was a problem logging in. Please check your email and password."
      render action: 'new'
    end
  end

  def destroy
    session[:user_id] = nil
    reset_session
    redirect_to root_path, notice: "You have been logged out."
  end
end


text:
/* - Coeus web framework -------------------------
 *
 * Licensed under the Apache License, Version 2.0.
 *
 * Author: Spiros Tzavellas
 */
package com.tzavellas.coeus.core

import org.junit.Test
import org.junit.Assert._
import java.lang.annotation.Annotation

class AnnotationProcessorTest {
  import AnnotationProcessorTest._

  @Test
  def from_annotation_to_method() {
    assertEquals('GET, toHttpMethod("get"))
    assertEquals('POST, toHttpMethod("post"))
    assertEquals('PUT, toHttpMethod("put"))
    assertEquals('DELETE, toHttpMethod("delete"))
    assertEquals('HEAD, toHttpMethod("head"))
    assertEquals('OPTIONS, toHttpMethod("options"))
    assertEquals('TRACE, toHttpMethod("trace"))
    assertEquals('CONNECT, toHttpMethod("connect"))
  }

  @Test
  def is_defined_at_returns_false_for_unknown_annotations() {
    assertFalse(AnnotationProcessor.toHttpMethod.isDefinedAt(annotation("invalid")))
  }

  private def toHttpMethod(objectMethod: String) =
    AnnotationProcessor.toHttpMethod(annotation(objectMethod))

  private def annotation(name: String) =
    classOf[AnnoationTest].getMethod(name).getDeclaredAnnotations.head
}

object AnnotationProcessorTest {
  import javax.xml.bind.annotation.XmlAttribute
  import com.tzavellas.coeus.mvc.annotation._

  class AnnoationTest {
    @Get def get() { }
    @Post def post() { }
    @Put def put() { }
    @Delete def delete() { }
    @HttpMethod(method="head") def head() { }
    @HttpMethod(method="options") def options() { }
    @HttpMethod(method="trace") def trace() { }
    @HttpMethod(method="connect") def connect() { }
    @XmlAttribute def invalid() { }
  }
}


text:
@implementation UIScreen (RCScreen)

+ (BOOL)is4InchDevice {
    return [self fullScreenHeight] == 568 && [self fullScreenWidth] == 320;
}

+ (BOOL)isLargerDevice {
    return [self fullScreenHeight] > 568 || [self fullScreenWidth] > 320;
}

+ (float)fullScreenHeight {
    return [[UIScreen mainScreen] bounds].size.height;
}

+ (float)fullScreenWidth {
    return [[UIScreen mainScreen] bounds].size.width;
}

+ (CGPoint)screenCenter {
    return CGPointMake([self fullScreenWidth] / 2, [self fullScreenHeight] / 2);
}

@end


text:
{% extends "v9/layoutv9.html" %}

{% set title = "Water abstraction licence" %}

{% block page_title %}
    {{title}} - GOV.UK
{% endblock %}

{% block content %}

          Service unavailable

There's a technical problem with the water resources licensing service and it's currently unavailable.

Sorry about this. We'll restore the service as quickly as possible.

If you need assistance, call the Environment Agency helpline 03708 506 506.

{% endblock %}


text:
'use strict';

const routesModule = (controllerModule => {
    let root = null;
    let useHash = true; // Defaults to: false
    let hash = '#!'; // Defaults to: '#'
    const router = new Navigo(null, false);

    let redirectHomeHook = { after: () => router.navigate('/') };

    router
        .on('/', controllerModule.materials.getAll)
        .on('/register', controllerModule.users.register)
        .on('/login', controllerModule.users.login)
        .on('/profiles/:username', params => controllerModule.users.profile(params.username))
        .on('/material/add', controllerModule.materials.showAddForm)
        .on('/materials/:id', params => controllerModule.materials.getOne(params.id)) //{}
        //.on(router.navigate('/'))
        .notFound(function () {
            // called when there is path specified but there is no route matching
            console.log('Not found here');
        })
        .resolve();
})(controllerModule);


text:
'use strict';

var fs = require('fs');
var path = require('path');
var test = require('ava');
var Imagemin = require('../');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof Imagemin === 'function');
});

test('add a plugin to the middleware stack', function (t) {
	t.plan(1);

	var imagemin = new Imagemin()
		.use(function () {});

	t.assert(imagemin.streams.length === 1, imagemin.streams.length);
});

test('set source file', function (t) {
	t.plan(1);

	var imagemin = new Imagemin()
		.src('test.jpg');

	t.assert(imagemin._src === 'test.jpg', imagemin._src);
});

test('set destination folder', function (t) {
	t.plan(1);

	var imagemin = new Imagemin()
		.dest('tmp');

	t.assert(imagemin._dest === 'tmp', imagemin._dest);
});

test('optimize a GIF', function (t) {
	t.plan(2);

	var src = fs.readFileSync(path.join(__dirname, 'fixtures/test.gif'), null);
	var imagemin = new Imagemin()
		.src(path.join(__dirname, 'fixtures/test.gif'))
		.use(Imagemin.gifsicle());

	imagemin.run(function (err, files) {
		t.assert(!err, err);
		t.assert(files[0].contents.length < src.length, files[0].contents.length);
	});
});

test('optimize a JPG', function (t) {
	t.plan(2);

	var src = fs.readFileSync(path.join(__dirname, 'fixtures/test.jpg'), null);
	var imagemin = new Imagemin()
		.src(path.join(__dirname, 'fixtures/test.jpg'))
		.use(Imagemin.jpegtran());

	imagemin.run(function (err, files) {
		t.assert(!err, err);
		t.assert(files[0].contents.length < src.length, files[0].contents.length);
	});
});

test('optimize a PNG', function (t) {
	t.plan(2);

	var src = fs.readFileSync(path.join(__dirname, 'fixtures/test.png'), null);
	var imagemin = new Imagemin()
		.src(path.join(__dirname, 'fixtures/test.png'))
		.use(Imagemin.optipng());

	imagemin.run(function (err, files) {
		t.assert(!err, err);
		t.assert(files[0].contents.length < src.length, files[0].contents.length);
	});
});

test('optimize a SVG', function (t) {
	t.plan(2);

	var src = fs.readFileSync(path.join(__dirname, 'fixtures/test.svg'), null);
	var imagemin = new Imagemin()
		.src(path.join(__dirname, 'fixtures/test.svg'))
		.use(Imagemin.svgo());

	imagemin.run(function (err, files) {
		t.assert(!err, err);
		t.assert(files[0].contents.length < src.length, files[0].contents.length);
	});
});

test('optimize a JPG using buffers', function (t) {
	t.plan(2);

	var src = fs.readFileSync(path.join(__dirname, 'fixtures/test.jpg'), null);
	var imagemin = new Imagemin()
		.src(src)
		.use(Imagemin.jpegtran());

	imagemin.run(function (err, files) {
		t.assert(!err, err);
		t.assert(files[0].contents.length < src.length, files[0].contents.length);
	});
});

test('output error on corrupt images', function (t) {
	t.plan(1);

	var imagemin = new Imagemin()
		.src(path.join(__dirname, 'fixtures/test-corrupt.jpg'))
		.use(Imagemin.jpegtran());

	imagemin.run(function (err) {
		t.assert(err);
	});
});


text:
<ion-view title="Events">

    <ion-nav-buttons side="left">
        <button menu-toggle="left" class="button button-icon button-clear ion-navicon"></button>
    </ion-nav-buttons>

    <ion-content has-header="true" has-tabs="true">

        <ion-list>

            <ion-item ng-repeat="event in events"
                      type="item-text-wrap"
                      ng-click="navToHash('#/topMenu/events/' + event.id)">

{{ event.title }}

{{ event.description }}

            </ion-item>

        </ion-list>

    </ion-content>
</ion-view>


text:
package com.xeiam.xchange.clevercoin.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xeiam.xchange.clevercoin.dto.CleverCoinBaseResponse;

public class CleverCoinDepositAddress extends CleverCoinBaseResponse {

  private final String depositAddress;

  protected CleverCoinDepositAddress(@JsonProperty("address") String depositAddress, @JsonProperty("error") String error) {

    super(error);
    this.depositAddress = depositAddress;
  }

  public String getDepositAddress() {

    return depositAddress;
  }

  @Override
  public String toString() {

    return "CleverCoinDepositAddress [depositAddress=" + depositAddress + "]";
  }

}