text:
import numpy as np
import importlib.util
import border_conditions
import postprocess
import matplotlib.pyplot as plt
import border_conditions as b
from mpl_toolkits import mplot3d

# TODO chsnge type of imort module
spec = importlib.util.spec_from_file_location("kir", "../utils/convection_diffusion_equation_solution/kir.py")
kir = importlib.util.module_from_spec(spec)
spec.loader.exec_module(kir)

spec = importlib.util.spec_from_file_location("beam_warming",
                                              "../utils/convection_diffusion_equation_solution/beam_warming.py")
beam_warming = importlib.util.module_from_spec(spec)
spec.loader.exec_module(beam_warming)

spec = importlib.util.spec_from_file_location("weno", "../utils/WENO_method/WENOmethod.py")
weno = importlib.util.module_from_spec(spec)
spec.loader.exec_module(weno)

spec = importlib.util.spec_from_file_location("bicompact", "../utils/bicompact_method/bicompact.py")
bicompact = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bicompact)

spec = importlib.util.spec_from_file_location("tvd", "../utils/TVD_method/TVDMethod.py")
tvd = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tvd)

spec = importlib.util.spec_from_file_location("McCormack", "../utils/convection_diffusion_equation_solution/McCormack.py")
McCormack = importlib.util.module_from_spec(spec)
spec.loader.exec_module(McCormack)

p = 0  # index of pressure in values array
v = 1  # index of velocity in values array

class Solver:
    """
    Solver class for simulations.
    Time axis is labed as t, spaces ax, ay
    TODO get type of border conditions from user
    cfl - Kur's number c*tau/h
    TODO In this task grid - it's a time slice
    """

    def __init__(self, problem):
        self.cfl = 0.1  # TODO change this parametrs to user's propertyies
        self._dimension = problem.dimension
        self.problem = problem
        if(self._dimension != 2):
            self.matrix_of_eigns = problem.model.lambda_matrix
            self.omega_matrix = problem.model.omega_matrix
            self.inv_matrix = problem.model.inverse_omega_matrix
        self._grid = problem._grid.grid
        self.source = problem.source
        self.type = problem._type
        self.buffering_step = problem._buffering_step
        self.v_p = problem.model.env_prop.v_p
        self.tension = problem.tension
        self.time_step = problem._time_step
        self.end_time = problem._end_time
        self.x_start = problem._x_start
        self.x_end = problem._x_end
        self.y_start = problem._y_start
        self.y_end = problem._y_end
        self.spatial_step = problem._x_step
        self._graph = problem.graph
        # self.time_step = self.cfl*self.spatial_step/self.v_p
        if self._dimension == 1:
            self.solve_1D()
        else:
            self.solve_2D()

    def solve_1D(self):
        grid = self._grid
        source_of_grid = self.source
        # time_step = self.time_step
        matrix_of_eigns = self.problem.model.lambda_matrix
        omega_matrix = self.problem.model.omega_matrix
        inv_matrix = self.problem.model.inverse_omega_matrix
        grid_prev_t = np.zeros(grid.shape)
        grid_next_t = np.zeros(grid.shape)
        # let's imagine that grid has not information about time
        # for t in range(1, grid.shape[0]):
        ##get only pressure values : array[:, 0]
        time = np.arange(0, self.end_time, self.time_step)
        source_of_grid.update_source_in_grid(grid_prev_t, self._dimension)
        result_grid = np.zeros((len(time), grid.shape[0], grid.shape[1]))

        for i in range(self.problem.grid._t_size - 1):
            grid_prev_t = self._generate_border_conditions(grid_prev_t,  i)
            ##for seismic
            # grid_prev_t =  border_conditions.border_condition_1d(grid_prev_t, self.problem._type, "applied_force","absorb",
            #                                 self.problem._method, force_left=100)

            # source_of_grid.update_source_in_grid(grid_next_t) ##TODO
            for k in range(1, grid_next_t.shape[0]):
                for j in self.tension.values():
                    grid_next_t[k - 1][i][j] = grid_prev_t[k][i][j]
            for k in range(len(grid_prev_t)):  # recieve Riman's invariant
                grid_prev_t[k][i] = np.dot(omega_matrix, grid_prev_t[k][i])
            # TODO add new method
            if (self.problem._method == 'kir'):
                for index in self.tension.values():
                    grid_next_t[:, i + 1, index] = kir.kir(grid_prev_t[:, i, index], self.spatial_step,
                                                     matrix_of_eigns[index][index], self.time_step)
            elif (self.problem._method == 'beam_warming'):
                for index in self.tension.values():
                    grid_next_t[:, i + 1, index] = beam_warming.beam_warming(self.time_step, self.spatial_step, grid_prev_t[:, i, index], matrix_of_eigns[index][index])

            elif (self.problem._method == 'bicompact'):
                for index in self.tension.values():
                    grid_next_t[:, i + 1, index] = bicompact.bicompact_method(matrix_of_eigns[index][index], self.time_step,
                                                                       self.spatial_step, grid_prev_t[:, i, index])

            elif (self.problem._method == 'McCormack'):
                for index in self.tension.values():
                    grid_next_t[:, i + 1, index] = McCormack.McCormack(grid_prev_t[:, i, index], self.spatial_step,
                                                     matrix_of_eigns[index][index], self.time_step)
            elif (self.problem._method == 'weno'):
                for index in self.tension.values():
                    grid_next_t[:, i + 1, index] = weno.WENOmethod(matrix_of_eigns[index][index], self.time_step,
                                                            self.spatial_step, grid_prev_t[:, i, index])

            for k in range(grid_next_t.shape[0]):  # recieve Riman's invariant
                grid_next_t[k][i + 1] = np.dot(inv_matrix, grid_next_t[k][i + 1])
            grid_prev_t = grid_next_t

            #
            # if (i < result_grid.shape[0] - 1):
            #
            #result_grid[i + 1] = grid_next_t
        postprocess.do_postprocess(grid_next_t, self.buffering_step,
                                    self.x_start, self.x_end, self.type,
                                    self.time_step)

        return grid_next_t
        # TODO add saving to file every N time steps

    def solve_2D_acoustic(self):
        pass

    def solve_2D_seismic(self):
        pass

    def solver(self, i, k, grid):
        grid_next_t = np.zeros(grid.shape)
        for j in range(grid.shape[k]):
            if k == 1:
                grid_prev = grid[:, j, :, :]
                matrix = self.problem.model.omega_a_matrix
                matrix_inverse = self.problem.model.inverse_omega_a_matrix
                self.spatial_step = self.problem._x_step
                directions = b.Directions.X
                lambda_matrix = self.problem.model._lamda_a_matrix
            else:
                grid_prev = grid[j, :, :, :]
                matrix = self.problem.model.omega_b_matrix
                matrix_inverse = self.problem.model.inverse_omega_b_matrix
                self.spatial_step = self.problem._y_step
                directions = b.Directions.Y
                lambda_matrix = self.problem.model._lamda_b_matrix
            grid_next = np.zeros(grid_prev.shape)
            grid_prev = self._generate_border_conditions(grid_prev, i, directions)
            for z in range(grid_prev.shape[0]):  # recieve Riman's invariant
                grid_prev[z][i] = np.dot(matrix, grid_prev[z][i])
            if (self.problem._method == 'kir'):
                for index in self.tension.values():
                    grid_next[:, i + 1, index] = kir.kir(grid_prev[:, i, index], self.spatial_step,
                                                         lambda_matrix[index][index], self.time_step)
            elif (self.problem._method == 'bicompact'):
                for index in self.tension.values():
                    grid_next[:, i + 1, index] = bicompact.bicompact_method(lambda_matrix[index][index],
                                                                                self.time_step,
                                                                                self.spatial_step,
                                                                                grid_prev[:, i, index])
            elif (self.problem._method == 'McCormack'):
                for index in self.tension.values():
                    grid_next[:, i + 1, index] = McCormack.McCormack(grid_prev[:, i, index], self.spatial_step,
                                                                       lambda_matrix[index][index], self.time_step)

            for z in range(grid_next.shape[0]):  # recieve Riman's invariant
                grid_next[z][i + 1] = np.dot(matrix_inverse, grid_next[z][i + 1])
            if(k == 1):
                grid_next_t[:, j, i, :] = grid_next[:, i + 1, :]
            else:
                grid_next_t[j, :, i, :] = grid_next[:, i + 1, :]
        return grid_next_t

    def solve_splitted_2D(self):
        """
        Method for splitted 2d problem to two 1d equation on one time slice
        """
        grid = self._grid
        for i in range((grid.shape[2] - 1)):
            grid_next_t_a = self.solver(i, 1, grid)
            grid_next_t_b = self.solver(i, 0, grid)
            grid[:,:, i + 1,:] = self.problem.n[0] * grid_next_t_a[:,:, i,:] + self.problem.n[1] * grid_next_t_b[:,:, i, :]
        return grid

    def solve_2D(self):
        grid = self._grid
        self.source.update_source_in_grid(grid, self._dimension)
        grid = self.solve_splitted_2D()
        print('Result grid shape: ' + str(grid.shape))
        j = 1
        if self._graph == 2:
            postprocess.do_2_postprocess(grid[:, :, :, j], self.buffering_step,
                                         self.x_start, self.x_end, self.y_start, self.y_end, self.problem.type,
                                         np.min(np.min(np.min(grid[:, :, :, j]))),
                                         np.max(np.max(np.max(grid[:, :, :, j]))),
                                         self.time_step)
        else:
            postprocess.do_3_postprocess(grid[:,:,:,j],self.buffering_step,
                                         self.x_start, self.x_end, self.y_start, self.y_end, self.problem.type,
                                         np.min(np.min(np.min(grid[:, :, :, j]))),
                                         np.max(np.max(np.max(grid[:, :, :, j]))),
                                         self.time_step)

    def _generate_border_conditions(self, grid, time = 0, direction=b.Directions.X):
        if self._dimension == 1:
            return border_conditions.border_condition_1d(
                grid, self.problem._type,
                self.problem._left_boundary_conditions,
                self.problem._right_boundary_conditions,
                self.problem._method, time, self.problem._force_left, self.problem._force_right)
        elif self._dimension == 2:
            return border_conditions.border_condition_2d(
                grid, self.problem._type,
                self.problem._left_boundary_conditions,
                self.problem._right_boundary_conditions,
                self.problem._method, time, direction)

    def _generate_right_border_conditions(self, grid, time):
        return border_conditions.border_condition_2d(grid, self.problem._type, self.problem._left_boundary_conditions,
                                                     self.problem._right_boundary_conditions,
                                                     self.problem._method, time = 0)


text:
<?php

namespace newerton\fancybox;

use yii\web\AssetBundle;

/**
 * Class FancyBoxHelpersAsset
 * @package newerton\fancybox
 */
class FancyBoxHelpersAsset extends AssetBundle
{
    /**
     * @var string
     */
    public $sourcePath = '@vendor/newerton/yii2-fancybox/src/assets/';

    /**
     * @var string[]
     */
    public $js = [
        'helpers/jquery.fancybox-buttons.js',
        'helpers/jquery.fancybox-media.js',
        'helpers/jquery.fancybox-thumbs.js'
    ];

    /**
     * @var string[]
     */
    public $css = [
        'helpers/jquery.fancybox-buttons.css',
        'helpers/jquery.fancybox-thumbs.css'
    ];

    /**
     * @var string[]
     */
    public $depends = [
        'yii\web\JqueryAsset',
        'newerton\fancybox\FancyBoxAsset',
    ];

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bio\ClickerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

use Bio\ClickerBundle\Form\ClickerGlobalType;
use Bio\DataBundle\Objects\Database;

/**
 * @Route("/admin/clicker")
 */
class AdminController extends Controller {
    /**
     * @Route("/", name="clicker_instruct")
     * @Template()
     */
    public function instructionAction() {
        return array('title' => 'Clickers');
    }

    /**
     * @Route("/manage", name="manage_clickers")
     * @Template()
     */
    public function manageAction(Request $request) {
        $flash = $request->getSession()->getFlashBag();

        $db = new Database($this, 'BioClickerBundle:ClickerGlobal');
        $global = $db->findOne(array());

        $form = $this->createForm(new ClickerGlobalType(), $global)
            ->add('save', 'submit');

        if ($request->getMethod() === "POST") {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $db->close();
                $flash->set('success', 'Changes saved.');
            } else {
                $flash->set('failure', 'Changes not saved.');
            }
        }

        $students = $this->getDoctrine()
                         ->getManager()
                         ->getRepository('BioClickerBundle:Clicker')
                         ->getUnregisteredStudents();

        return array(
            'form' => $form->createView(),
            'students' => $students,
            'title' => 'Manage Clickers'
        );
    }

    /**
     * @Route("/download", name="download_list")
     */
    public function downloadAction(Request $request) {

        // get data
        $repo = $this->getDoctrine()
                     ->getManager()
                     ->getRepository('BioClickerBundle:Clicker');

        $clickers = $repo->findAll();
        $unregistered = $repo->getUnregisteredStudents();

        // build response
        $response = $this->render('BioClickerBundle:Admin:download.xls.twig', array(
            'clickers' => $clickers,
            'unregistered' => $unregistered
        ));

        $response->headers->set(
            "Content-Type", 'application/vnd.ms-excel'
        );

        $response->headers->set(
            'Content-Disposition', ('attachment; filename="clickerReg.xls"')
        );

        return $response;
    }

    /**
     * @Route("/clear", name="clear_list")
     * @Template()
     */
    public function clearAction(Request $request) {
        $flash = $request->getSession()->getFlashBag();

        // this form is a simple checkbox that `must` be
        // checked in order for the form to be valid
    	$form = $this->createFormBuilder()
    		->add('confirmation', 'checkbox', array(
                'constraints' => new Assert\True(
                    array('message' => 'You must confirm.')
                    )
                )
            )
    		->add('clear', 'submit', array('label' => 'Clear Clickers'))
    		->getForm();

        // only if the form is submitted and is valid
        // do we try to clear the clicker registrations
    	if ($request->getMethod() === "POST") {
    		$form->handleRequest($request);

    		if ($form->isValid()) {
    			$this->getDoctrine()
                     ->getManager()
                     ->getRepository('BioClickerBundle:Clicker')
                     ->removeAll();

		        $flash->set('success', 'All clicker registrations cleared.');
                return $this->redirect($this->generateUrl('clear_list'));
    		} else {
                $flash->set('failure', 'Invalid form.');
            }
    	}

    	return array('form' => $form->createView(), 'title' => 'Clear Registrations');
    }
}


text:
<?php

namespace Contributte\GopayInline\Api\Objects;

class Recurrence extends AbstractObject
{

	/** @var string */
	public $cycle;

	/** @var float */
	public $period;

	/** @var string */
	public $dateTo;

	/**
	 * ABSTRACT ****************************************************************
	 */

	/**
	 * @return array
	 */
	public function toArray()
	{
		return [
			'recurrence_cycle' => $this->cycle,
			'recurrence_period' => $this->period,
			'recurrence_date_to' => $this->dateTo,
		];
	}

}


text:
class AdminController < ApplicationController
  # 管理者用-現在のアカウント設定
  def admin_current_user
    if session[:admin_user_id] && $settings && session[:admin_servicename] == $settings['servicename']
      @admin_current_user ||= User.find(session[:admin_user_id])
    end
  end
  helper_method :admin_current_user

  # 管理者ログインチェック
  def admin_authorize
    unless admin_current_user
      flash[:notice] = t('login_notice')
      session[:jumpto] = request.parameters
      redirect_to admin_login_index_path
    end
  end
end


text:
@interface ChatiPhoneClient : ChatClient

@property (nonatomic, strong, readonly) NSOperationQueue *requestQueue;
- (CSTcpRequest *)tcpRequestWithChatMessage:(ChatMessage *)request;

+ (ChatiPhoneClient *)iPhone;

- (BOOL)loginWithTheAccount:(NSString *)account password:(NSString *)password;
- (BOOL)connectToTheHost:(NSString *)secret;
- (void)disconnect;

//重载super
- (BOOL)registerManager:(id <ChatiPhoneProtocol>)manager forKey:(NSString *)key;
- (id<ChatiPhoneProtocol>)managerForKey:(NSString *)key;
@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-7
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.10.24 at 10:41:34 PM CDT
//

package org.statmantis.mport.mlb.gen;

import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for inningHip complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="inningHip">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="des" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="x" type="{http://www.w3.org/2001/XMLSchema}decimal" />
 *       <attribute name="y" type="{http://www.w3.org/2001/XMLSchema}decimal" />
 *       <attribute name="batter" type="{http://www.w3.org/2001/XMLSchema}long" />
 *       <attribute name="pitcher" type="{http://www.w3.org/2001/XMLSchema}long" />
 *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="team" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="inning" type="{http://www.w3.org/2001/XMLSchema}int" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "inningHip")
public class InningHip {

    @XmlAttribute(name = "des")
    protected String des;
    @XmlAttribute(name = "x")
    protected BigDecimal x;
    @XmlAttribute(name = "y")
    protected BigDecimal y;
    @XmlAttribute(name = "batter")
    protected Long batter;
    @XmlAttribute(name = "pitcher")
    protected Long pitcher;
    @XmlAttribute(name = "type")
    protected String type;
    @XmlAttribute(name = "team")
    protected String team;
    @XmlAttribute(name = "inning")
    protected Integer inning;

    /**
     * Gets the value of the des property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDes() {
        return des;
    }

    /**
     * Sets the value of the des property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDes(String value) {
        this.des = value;
    }

    /**
     * Gets the value of the x property.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getX() {
        return x;
    }

    /**
     * Sets the value of the x property.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setX(BigDecimal value) {
        this.x = value;
    }

    /**
     * Gets the value of the y property.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getY() {
        return y;
    }

    /**
     * Sets the value of the y property.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setY(BigDecimal value) {
        this.y = value;
    }

    /**
     * Gets the value of the batter property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getBatter() {
        return batter;
    }

    /**
     * Sets the value of the batter property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setBatter(Long value) {
        this.batter = value;
    }

    /**
     * Gets the value of the pitcher property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getPitcher() {
        return pitcher;
    }

    /**
     * Sets the value of the pitcher property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setPitcher(Long value) {
        this.pitcher = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     * Gets the value of the team property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTeam() {
        return team;
    }

    /**
     * Sets the value of the team property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTeam(String value) {
        this.team = value;
    }

    /**
     * Gets the value of the inning property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getInning() {
        return inning;
    }

    /**
     * Sets the value of the inning property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setInning(Integer value) {
        this.inning = value;
    }

}


text:
package org.apache.mesos.state;

import java.util.Iterator;

import java.util.concurrent.Future;

/**
 * An abstraction of "state" (possibly between multiple distributed
 * components) represented by "variables" (effectively key/value
 * pairs). Variables are versioned such that setting a variable in the
 * state will only succeed if the variable has not changed since last
 * fetched. Varying implementations of state provide varying
 * replicated guarantees.
 *

 * Note that the semantics of 'fetch' and 'store' provide
 * atomicity. That is, you can not store a variable that has changed
 * since you did the last fetch. That is, if a store succeeds then no
 * other writes have been performed on the variable since your fetch.
 *
 * Example:
 *

 * {@code
 *   State state = new ZooKeeperState();
 *   Future<Variable> variable = state.fetch("machines");
 *   Variable machines = variable.get();
 *   machines = machines.mutate(...);
 *   variable = state.store(machines);
 *   machines = variable.get();
 * }
 *

 */
public interface State {
  /**
   * Returns an immutable "variable" representing the current value
   * from the state associated with the specified name.
   *
   * @param name  The name of the variable.
   *
   * @return      A future of the variable.
   *
   * @see Variable
   */
  Future<Variable> fetch(String name);

  /**
   * Returns an immutable "variable" representing the current value in
   * the state if updating the specified variable in the state was
   * successful, otherwise returns null.
   *
   * @param variable  The variable to be stored.
   *
   * @return          A future of a variable with the new value on success,
   *                  or null on failure.
   *
   * @see Variable
   */
  Future<Variable> store(Variable variable);

  /**
   * Returns true if successfully expunged the variable from the state
   * or false if the variable did not exist or was no longer valid.
   *
   * @param variable  The variable to be expunged.
   *
   * @return          A future of true on success, false on failure.
   *
   * @see Variable
   */
  Future<Boolean> expunge(Variable variable);

  /**
   * Returns an iterator of variable names in the state.
   *
   * @return A future of an iterator over all variable names in the state.
   */
  Future<Iterator<String>> names();
}


text:
// ------------------------------------------------------------------------------
//  <auto-generated>
//      This code was generated by SpecFlow (http://www.specflow.org/).
//      SpecFlow Version:1.9.0.77
//      SpecFlow Generator Version:1.9.0.0
//      Runtime Version:4.0.30319.42000
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace Orchard.AcceptanceTests.Features.Setup
{
    using TechTalk.SpecFlow;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [NUnit.Framework.TestFixtureAttribute()]
    [NUnit.Framework.DescriptionAttribute("Setup")]
    public partial class SetupFeature
    {

        private static TechTalk.SpecFlow.ITestRunner testRunner;

#line 1 "Setup.feature"
#line hidden

        [NUnit.Framework.TestFixtureSetUpAttribute()]
        public virtual void FeatureSetup()
        {
            testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
            TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Setup", "", ProgrammingLanguage.CSharp, ((string[])(null)));
            testRunner.OnFeatureStart(featureInfo);
        }

        [NUnit.Framework.TestFixtureTearDownAttribute()]
        public virtual void FeatureTearDown()
        {
            testRunner.OnFeatureEnd();
            testRunner = null;
        }

        [NUnit.Framework.SetUpAttribute()]
        public virtual void TestInitialize()
        {
        }

        [NUnit.Framework.TearDownAttribute()]
        public virtual void ScenarioTearDown()
        {
            testRunner.OnScenarioEnd();
        }

        public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
        {
            testRunner.OnScenarioStart(scenarioInfo);
        }

        public virtual void ScenarioCleanup()
        {
            testRunner.CollectScenarioErrors();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Create a site")]
        [NUnit.Framework.IgnoreAttribute()]
        public virtual void CreateASite()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Create a site", new string[] {
                        "ignore"});
#line 4
this.ScenarioSetup(scenarioInfo);
#line 5
 testRunner.When("I create a site", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 6
 testRunner.Then("I should be able to see that site", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
            this.ScenarioCleanup();
        }
    }
}
#pragma warning restore
#endregion


text:
package com.epimorphics.appbase.security;

import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.SaltedAuthenticationInfo;
import org.apache.shiro.util.ByteSource;

/**
 * Interface abstraction for the store of registered users. The actual
 * user credentials are not stored since we rely on OpenID for that.
 * Stores permissions of the form "{action}:{target}" using the Shiro
 * WildcardPermission syntax but this interface works at the level of strings.
 *
 * @author Dave Reynolds
 */
public interface UserStore {

    /** ID of a pseudo user which stores the global permissions available to anyone logged in */
    public static final String AUTH_USER_ID = "http://localhost/anon";

    /**
     * Link this store to a specific authorization realm
     */
    public void setRealm(AppRealm realm);

    /**
     * Register a new user.
     * Return true if the new registration succeeded, false if the user is already registered.
     */
    public boolean register(UserInfo user);

    /**
     * Test if a user is registered. Returns their user information and credentials
     * if they are or null if not registered. Stored and returned credentials are salt-hashed
     * to make it easy to allow user defined passwords in the future, redundant for
     * generated passwords. If the user has no credentials or they have timed out then
     * the credentials will be null.
     *
     * @param id the openid identifier string authenticated by the user
     */
    public SaltedAuthenticationInfo checkUser(String id);

    /**
     * Unregister a user, removing them and any permissions from the store
     */
    public void unregister(String id);

    /**
     * Store new credentials for the user
     *
     * @param id the openid identifier string authenticated by the user
     * @param credentials the password to store
     * @param minstolive the time-to-livefor the credentials in minutes
     */
    public void setCredentials(String id, ByteSource credentials, int minstolive);

    /**
     * Create a new random password, set it and return it.
     *

     * Yes, the return ought to be a char[] to allow for reseting but the
     * use case will be creating string serializations of the key in any case
     * to send it out so the added security of using char[] is zero.

     */
    public String createCredentials(String id, int minstolive);

    /**
     * Remove the credentials for the user
     */
    public void removeCredentials(String id);

    /**
     * Return all the permissions and rolefor this user
     */
    public Set<String> getPermissions(String id);

    /**
     * Record a new permission for this user.
     */
    public void addPermision(String id, String permission);

    /**
     * Remove the specific matching permission for this user
     */
    public void removePermission(String id, String permission);

    /**
     * Remove permissions from this user for the given path.
     * Only relevant in applications that use action:path structure.
     */
    public void removePermissionsOn(String id, String target);

    /**
     * Return the set of users who have some explicit permission over the given path
     * Only relevant in applications that use action:path structure.
     */
    public List<UserPermission> authorizedOn(String target);

    /**
     * Return the set of users whose name includes the given string
     */
    public List<UserInfo> listUsers(String match);

    /**
     * Return the user info for the given user ID, or null if not found
     */
    public UserInfo getUser(String id);

}


text:
qc::is safe_html
==============

part of [Is API](../is.md)

Usage
-----
`qc::is safe_html string`

Description
-----------
Checks if the given string containts only safe HTML elements and attributes.

See [Safe HTML] for more information regarding safe elements, attributes, and values.

Examples
--------
```tcl

% qc::is safe_html {<foo>bar</foo>}
0
% qc::is safe_html {<img src="http://link.to.image" />}
1
% qc::is safe_html {It doesn't have to be just HTML. There can be content that might include HTML <pre><code class="language-tcl">puts Hello World</code></pre>}
1
% qc::is safe_html {<div id="content">Foo</div>}
0
```

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"
[Safe HTML]: ../safe_html.md


text:
<?php

/**
 * ShopSchedule update view.
 *
 * @var yii\base\View $this View
 * @var modules\directory\models\ShopSchedule $model Model
 */

use modules\directory\Module as DirectoryModule;
use yii\bootstrap\Modal;

Modal::begin([
    'id' => 'schedule-modal',
    'header' => '<h2>'.DirectoryModule::t('shop-schedule', 'MODAL_TITLE_UPDATE').'</h2>',
]);
echo $this->render(
    '_form',
    [
        'model' => $model,
        'formModel' => $formModel,
    ]
);
Modal::end();
$this->registerJS('
     $("#schedule-modal").modal("show");
', \yii\web\View::POS_END);


text:
package com.odong.fly.gui;

import com.odong.core.util.JsonHelper;
import com.odong.fly.MyException;
import com.odong.fly.camera.CameraUtil;
import com.odong.fly.serial.SerialUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * User: flamen
 * Date: 13-8-25
 * Time: 下午12:27
 */
@Component("gui.dialog")
public class Dialog {

    public void exit() {
        confirm("exit", () -> {
            if (serialUtil.hasOpen() || cameraUtil.hasOpen()) {
                logger.error("当前串口状态[{}]", jsonHelper.object2json(serialUtil.getStatus()));
                logger.error("当前摄像头状态[{}]", jsonHelper.object2json(cameraUtil.getStatus()));
                error("stillOpen");
            } else {
                System.exit(0);
            }
        }, null);
    }

    public void confirm(String key, Runnable yes, Runnable no) {
        switch (JOptionPane.showConfirmDialog(
                mainFrame,
                message.getMessage("dialog." + key + ".message"),
                message.getMessage("dialog." + key + ".title"),
                JOptionPane.YES_NO_OPTION)) {
            case JOptionPane.YES_OPTION:
                if (yes != null) {
                    yes.run();
                }
                break;
            case JOptionPane.NO_OPTION:
                if (no != null) {
                    no.run();
                }
                break;
        }
    }

    public void error(MyException.Type type) {
        JOptionPane.showMessageDialog(mainFrame,
                message.getMessage("exception." + type.name()),
                type.name(),
                JOptionPane.ERROR_MESSAGE);
    }

    public void error(String key) {
        JOptionPane.showMessageDialog(mainFrame,
                message.getMessage("dialog." + key + ".message"),
                message.getMessage("dialog." + key + ".title"),
                JOptionPane.ERROR_MESSAGE);
    }

    public void info(String key) {
        JOptionPane.showMessageDialog(mainFrame,
                message.getMessage("dialog." + key + ".message"),
                message.getMessage("dialog." + key + ".title"),
                JOptionPane.INFORMATION_MESSAGE);
    }

    @Resource
    private Message message;
    @Resource
    private JFrame mainFrame;
    @Resource
    private SerialUtil serialUtil;
    @Resource
    private JsonHelper jsonHelper;
    @Resource
    private CameraUtil cameraUtil;
    private final static Logger logger = LoggerFactory.getLogger(Dialog.class);

    public void setJsonHelper(JsonHelper jsonHelper) {
        this.jsonHelper = jsonHelper;
    }

    public void setSerialUtil(SerialUtil serialUtil) {
        this.serialUtil = serialUtil;
    }

    public void setCameraUtil(CameraUtil cameraUtil) {
        this.cameraUtil = cameraUtil;
    }

    public void setMainFrame(JFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public void setMessage(Message message) {
        this.message = message;
    }
}


text:
proj = tcp
settings = --settings=$(proj).settings
test_settings = --settings=$(proj).test_settings

test:
	django-admin.py test core provider $(test_settings) --failfast --noinput

run:
	foreman start

db:
	django-admin.py syncdb $(settings)

migrate:
	django-admin.py migrate $(settings)

user:
	django-admin.py createsuperuser $(settings)

shell:
	django-admin.py shell $(settings)

dbshell:
	django-admin.py dbshell $(settings)

makemessages:
	cd $(proj) && django-admin.py makemessages -a $(settings)

compilemessages:
	cd $(proj) && django-admin.py compilemessages $(settings)

sdist:
	python setup.py sdist

doc:
	sphinx-build -b html docs output


text:
require File.join(File.dirname(__FILE__), '..', 'lib','pidfile')

describe PidFile do
  before(:each) do
    @pidfile = PidFile.new(:pidfile => "rspec.pid")
  end

  after(:each) do
    @pidfile.release
  end

  #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  # Builder Tests
  #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#

  it "should set defaults upon instantiation" do
    @pidfile.pidfile.should == "rspec.pid"
    @pidfile.piddir.should == "/tmp"
    @pidfile.pidpath.should == "/tmp/rspec.pid"
  end

  it "should secure pidfiles left behind and recycle them for itself" do
    @pidfile.release
    fakepid = 99999999 # absurd number
    open("/tmp/foo.pid", "w") {|f| f.puts fakepid }
    pf = PidFile.new(:pidfile => "foo.pid")
    PidFile.pid(pf.pidpath).should == Process.pid
    pf.should be_an_instance_of PidFile
    pf.pid.should_not == fakepid
    pf.pid.should be_a_kind_of Integer
    pf.release
  end

  it "should create a pid file upon instantiation" do
    File.exists?(@pidfile.pidpath).should be_true
  end

  it "should create a pidfile containing same PID as process" do
    @pidfile.pid.should == Process.pid
  end

  it "should know if pidfile exists or not" do
    @pidfile.pidfile_exists?.should be_true
    @pidfile.release
    @pidfile.pidfile_exists?.should be_false
  end

  it "should be able to tell if a process is running" do
    @pidfile.alive?.should be_true
  end

  it "should remove the pidfile when the calling application exits" do
    fork do
      exit
    end
    PidFile.pidfile_exists?.should be_false
  end

  it "should raise an error if a pidfile already exists" do
    lambda { PidFile.new(:pidfile => "rspec.pid") }.should raise_error
  end

  it "should know if a process exists or not - Class method" do
    PidFile.running?('/tmp/rspec.pid').should be_true
    PidFile.running?('/tmp/foo.pid').should be_false
  end

  it "should know if it is running - Class method" do
    pf = PidFile.new
    PidFile.running?.should be_true
    pf.release
    PidFile.running?.should be_false
  end

  it "should know if it's alive or not" do
    @pidfile.alive?.should be_true
    @pidfile.release
    @pidfile.alive?.should be_false
  end

  it "should remove pidfile and set pid to nil when released" do
    @pidfile.release
    @pidfile.pidfile_exists?.should be_false
    @pidfile.pid.should be_nil
  end

  it "should give a DateTime value for locktime" do
    @pidfile.locktime.should be_an_instance_of Time
  end
end


text:
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Test for Bug 341604</title>
  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>

<body onLoad="doStuff()">
  I should NOT be opened by a sandboxed iframe via any method
</body>
</html>

<script>
  function doStuff() {
    console.log("file_iframe_sandbox_window_open_fail.html");
    window.opener.ok(false, "sandboxed documents should NOT be able to open windows");
    self.close();
  }
</script>


text:
package pack1Unrelated;

class D extends target.pack1.C {}


text: module.exports = ['out/*'];


text:
composer install
php app/console doctrine:database:drop --force
php app/console doctrine:database:create
php app/console doctrine:migrations:migrate --no-interaction
php app/console doctrine:fixtures:load --no-interaction

bundle install
npm install --save bower gulp uglify-js uglifycss
npm install
npm shrinkwrap
node_modules/.bin/bower install --config.interactive=false
node_modules/.bin/gulp build

php app/console assets:install --symlink
php app/console assetic:dump


text:
COMMAND_BASE_DIR = File.join(File.dirname(__FILE__), 'command')

require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_constants'))
require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_parser'))
require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_serializer'))
require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_io'))
require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_runner'))
require File.normalize_path(File.join(COMMAND_BASE_DIR, 'command_client'))


text:
- improve error messages
- add option to disable check for type of property value as remoteStorage
  specification violates WebFinger specification

## 1.0.0 (2015-10-06)
- **BREAKING**: update API to allow providing a `Client` instance
- **BREAKING**: change option handling
- update Guzzle dependency

## 0.1.2
- change license to Apache 2.0

## 0.1.1
- restore `getLinkRelations()`

## 0.1.0
- initial release


text:
import io
import logging
import PIL.Image

from smqtk.representation.data_element.file_element import DataElement

def is_loadable_image(data_element):
    """
    Determine if an image is able to be loaded by PIL.

    :param data_element: A data element to check
    :type data_element: DataElement

    :return: Whether or not the image is loadable
    :rtype: bool

    """
    log = logging.getLogger(__name__)

    try:
        PIL.Image.open(io.BytesIO(data_element.get_bytes()))
        return True
    except IOError, ex:
        # noinspection PyProtectedMember
        log.debug("Failed to convert '%s' bytes into an image "
                  "(error: %s). Skipping", data_element, str(ex))
        return False

def is_valid_element(data_element, valid_content_types=None, check_image=False):
    """
    Determines if a given data element is valid.

    :param data_element: Data element
    :type data_element: str

    :param valid_content_types: List of valid content types, or None to skip
        content type checking.
    :type valid_content_types: iterable | None

    :param check_image: Whether or not to try loading the image with PIL. This
        often catches issues that content type can't, such as corrupt images.
    :type check_image: bool

    :return: Whether or not the data element is valid
    :rtype: bool

    """
    log = logging.getLogger(__name__)

    if (valid_content_types is not None and
        data_element.content_type() not in valid_content_types):
        log.debug("Skipping file (invalid content) type for "
                  "descriptor generator (data_element='%s', ct=%s)",
                  data_element, data_element.content_type())
        return False

    if check_image and not is_loadable_image(data_element):
        return False

    return isinstance(data_element, DataElement)


text:
		<title>Member List</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">

				Main Page
				Class Hierarchy
				Compound List
				Compound Members

PxConstraintVisualizationFlag Member List

This is the complete list of members for PxConstraintVisualizationFlag, including all inherited members.

eLIMITS enum value	PxConstraintVisualizationFlag

eLOCAL_FRAMES enum value	PxConstraintVisualizationFlag

Enum enum name	PxConstraintVisualizationFlag

Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. www.nvidia.com


text:
from __future__ import division

import numpy as np
from .linear import STTransform

class PanZoomTransform(STTransform):
    """Pan-zoom transform

    Parameters
    ----------
    canvas : instance of Canvas | None
        The canvas to attch to.
    aspect : float | None
        The aspect ratio to apply.
    **kwargs : dict
        Keyword arguments to pass to the underlying `STTransform`.
    """
    def __init__(self, canvas=None, aspect=None, **kwargs):
        self._aspect = aspect
        self.attach(canvas)
        STTransform.__init__(self, **kwargs)
        self.on_resize(None)

    def attach(self, canvas):
        """Attach this tranform to a canvas

        Parameters
        ----------
        canvas : instance of Canvas
            The canvas.
        """
        self._canvas = canvas
        canvas.events.resize.connect(self.on_resize)
        canvas.events.mouse_wheel.connect(self.on_mouse_wheel)
        canvas.events.mouse_move.connect(self.on_mouse_move)

    @property
    def canvas_tr(self):
        return STTransform.from_mapping(
            [(0, 0), self._canvas.size],
            [(-1, 1), (1, -1)])

    def on_resize(self, event):
        """Resize handler

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        if self._aspect is None:
            return
        w, h = self._canvas.size
        aspect = self._aspect / (w / h)
        self.scale = (self.scale[0], self.scale[0] / aspect)
        self.shader_map()

    def on_mouse_move(self, event):
        """Mouse move handler

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        if event.is_dragging:
            dxy = event.pos - event.last_event.pos
            button = event.press_event.button

            if button == 1:
                dxy = self.canvas_tr.map(dxy)
                o = self.canvas_tr.map([0, 0])
                t = dxy - o
                self.move(t)
            elif button == 2:
                center = self.canvas_tr.map(event.press_event.pos)
                if self._aspect is None:
                    self.zoom(np.exp(dxy * (0.01, -0.01)), center)
                else:
                    s = dxy[1] * -0.01
                    self.zoom(np.exp(np.array([s, s])), center)

            self.shader_map()

    def on_mouse_wheel(self, event):
        """Mouse wheel handler

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        self.zoom(np.exp(event.delta * (0.01, -0.01)), event.pos)


text:
package tests.org.w3c.dom;

import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargetClass;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.DOMException;

import javax.xml.parsers.DocumentBuilder;

/**
 *     The "setNamedItemNS(arg)" method for a
 *    NamedNodeMap should raise INUSE_ATTRIBUTE_ERR DOMException if
 *    arg is an Attr that is already an attribute of another Element object.
 *
 *    Retrieve an attr node from the third "address" element whose local name
 *    is "domestic" and namespaceURI is "http://www.netzero.com".
 *    Invoke method setNamedItemNS(arg) on the map of the first "address" element with
 *    arg being the attr node from above.  Method should raise
 *    INUSE_ATTRIBUTE_ERR DOMException.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='INUSE_ATTRIBUTE_ERR'])
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-setNamedItemNS
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-setNamedItemNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='INUSE_ATTRIBUTE_ERR'])
*/
@TestTargetClass(NamedNodeMap.class)
public final class SetNamedItemNS extends DOMTestCase {

    DOMDocumentBuilderFactory factory;

    DocumentBuilder builder;

    protected void setUp() throws Exception {
        super.setUp();
        try {
            factory = new DOMDocumentBuilderFactory(DOMDocumentBuilderFactory
                    .getConfiguration2());
            builder = factory.getBuilder();
        } catch (Exception e) {
            fail("Unexpected exception" + e.getMessage());
        }
    }

    protected void tearDown() throws Exception {
        factory = null;
        builder = null;
        super.tearDown();
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Verifies DOMException with INUSE_ATTRIBUTE_ERR code.",
        method = "setNamedItemNS",
        args = {org.w3c.dom.Node.class}
    )
   public void testSetNamedItemNS1() throws Throwable {
      Document doc;
      NodeList elementList;
      Node anotherElement;
      NamedNodeMap anotherMap;
      Node arg;
      Node testAddress;
      NamedNodeMap map;

      doc = (Document) load("staffNS", builder);
      elementList = doc.getElementsByTagName("address");
      anotherElement = elementList.item(2);
      anotherMap = anotherElement.getAttributes();
      arg = anotherMap.getNamedItemNS("http://www.netzero.com", "domestic");
      testAddress = elementList.item(0);
      map = testAddress.getAttributes();

      {
         boolean success = false;
         try {
            map.setNamedItemNS(arg);
          } catch (DOMException ex) {
            success = (ex.code == DOMException.INUSE_ATTRIBUTE_ERR);
         }
         assertTrue("throw_INUSE_ATTRIBUTE_ERR", success);
      }
}
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Verifies DOMException with WRONG_DOCUMENT_ERR code.",
        method = "setNamedItemNS",
        args = {org.w3c.dom.Node.class}
    )
   public void testSetNamedItemNS2() throws Throwable {
          String namespaceURI = "http://www.usa.com";
          String qualifiedName = "dmstc:domestic";
          Document doc;
          Document anotherDoc;
          Node arg;
          NodeList elementList;
          Node testAddress;
          NamedNodeMap attributes;

          doc = (Document) load("staffNS", builder);
          anotherDoc = (Document) load("staffNS", builder);
          arg = anotherDoc.createAttributeNS(namespaceURI, qualifiedName);
          arg.setNodeValue("Maybe");
          elementList = doc.getElementsByTagName("address");
          testAddress = elementList.item(0);
          attributes = testAddress.getAttributes();

          {
             boolean success = false;
             try {
                attributes.setNamedItemNS(arg);
              } catch (DOMException ex) {
                success = (ex.code == DOMException.WRONG_DOCUMENT_ERR);
             }
             assertTrue("throw_WRONG_DOCUMENT_ERR", success);
          }
    }
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Verifies positive fnctionality.",
        method = "getNamedItemNS",
        args = {java.lang.String.class, java.lang.String.class}
    )
   public void testSetNamedItemNS3() throws Throwable {
          String namespaceURI = "http://www.nist.gov";
          String qualifiedName = "prefix:newAttr";
          Document doc;
          Node arg;
          NodeList elementList;
          Node testAddress;
          NamedNodeMap attributes;
          Node retnode;
          String value;

          doc = (Document) load("staffNS", builder);
          arg = doc.createAttributeNS(namespaceURI, qualifiedName);
          arg.setNodeValue("newValue");
          elementList = doc.getElementsByTagName("address");
          testAddress = elementList.item(0);
          attributes = testAddress.getAttributes();
          attributes.setNamedItemNS(arg);
          retnode = attributes.getNamedItemNS(namespaceURI, "newAttr");
          value = retnode.getNodeValue();
          assertEquals("throw_Equals", "newValue", value);
          }

// Assumes validation.
//   public void testSetNamedItemNS4() throws Throwable {
//          String namespaceURI = "http://www.w3.org/2000/xmlns/";
//          String localName = "local1";
//          Document doc;
//          NodeList elementList;
//          Node testAddress;
//          NodeList nList;
//          Node child;
//          NodeList n2List;
//          Node child2;
//          NamedNodeMap attributes;
//          Node arg;
//
//          int nodeType;
//          doc = (Document) load("staffNS", builder);
//          elementList = doc.getElementsByTagName("gender");
//          testAddress = elementList.item(2);
//          nList = testAddress.getChildNodes();
//          child = nList.item(0);
//          nodeType = (int) child.getNodeType();
//
//          if (1 == nodeType) {
//              child = doc.createEntityReference("ent4");
//          assertNotNull("createdEntRefNotNull", child);
//          }
//        n2List = child.getChildNodes();
//          child2 = n2List.item(0);
//          assertNotNull("notnull", child2);
//          attributes = child2.getAttributes();
//          arg = attributes.getNamedItemNS(namespaceURI, localName);
//
//          {
//             boolean success = false;
//             try {
//                attributes.setNamedItemNS(arg);
//              } catch (DOMException ex) {
//                success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR);
//             }
//             assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR", success);
//          }
//    }
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Verifies positive fnctionality.",
        method = "setNamedItemNS",
        args = {org.w3c.dom.Node.class}
    )
   public void testSetNamedItemNS5() throws Throwable {
          String namespaceURI = "http://www.usa.com";
          String qualifiedName = "dmstc:domestic";
          Document doc;
          Node arg;
          NodeList elementList;
          Node testAddress;
          NamedNodeMap attributes;
          Node retnode;
          String value;
          doc = (Document) load("staffNS", builder);
          arg = doc.createAttributeNS(namespaceURI, qualifiedName);
          arg.setNodeValue("newValue");
          elementList = doc.getElementsByTagName("address");
          testAddress = elementList.item(0);
          attributes = testAddress.getAttributes();
          retnode = attributes.setNamedItemNS(arg);
          value = retnode.getNodeValue();
          assertEquals("throw_Equals", "Yes", value);
          }

}


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

using ArbiterInternal;

public partial class Arbiter {

	public class Tournament {

		public enum StatusType {
			Unknown,
			Initializing,
			InProgress,
			Complete
		}

		public string Id                		{ get { return this.id; } }
		public StatusType Status        		{ get { return this.status; } }
		public List<TournamentUser> Users     	{ get { return this.users; } }
		public List<string> Winners				{ get { return this.winners; } }

		public Tournament( string id, StatusType status, List<TournamentUser> users, List<string> winners ) {
			this.id = id;
			this.status = status;
			this.users = users;
			this.winners = winners;
		}

		public bool GetScoreForUserId( string userId, out int score ) {
			foreach( var user in this.users ) {
				if( user.Id == userId && user.HasScore ) {
					score = user.Score.Value;
					return true;
				}
			}
			score = 0;
			return false;
		}

		public bool GetScoreForOtherUserId( string userId, out int score ) {
			foreach( var user in this.users ) {
				if( user.Id != userId && user.HasScore ) {
					score = user.Score.Value;
					return true;
				}
			}
			score = 0;
			return false;
		}

		public bool UserCanReportScore( string id ) {
			bool rv = false;
			this.users.ForEach( user => {
				if( user.Id == id && user.Paid && !user.HasScore ) {
					rv = true;
				}
			});
			return rv;
		}

		public bool UserHasViewed( string id ) {
			bool rv = false;
			this.users.ForEach( user => {
				if( user.Id == id && user.Viewed ) {
					rv = true;
				}
			});
			return rv;
		}

		public override string ToString() {
			string rv = "[Tournament "+
				"id:"+this.id+", "+
				"status:"+this.status+", "+
				"users:[";
			this.users.ForEach( user => {
				rv += user +", ";
			});
			rv += "]]";
			return rv;
		}

		private string id;
		private StatusType status;
		private List<TournamentUser> users;
		private List<string> winners;
	}

	public class TournamentUser {

		public string Id            { get { return this.id; } }
		public string Username		{ get { return this.username; } set { this.username = value; } }
		public bool Viewed			{ get { return this.viewed; } set { this.viewed = value; } }
		public bool Paid			{ get { return this.paid; } set { this.paid = value; } }
		public bool HasScore		{ get { return this.score.HasValue; } }
		public int? Score           { get { return this.score; } set { this.score = value; } }

		public TournamentUser( string id ) {
			this.id = id;
			this.paid = false;
			this.viewed = false;
			this.score = null;
			this.username = null;
		}

		public void SetScore( int score ) {
			this.score = score;
		}

		public override string ToString() {
			return "[Id:"+Id+", username:"+Username+", viewed:"+viewed+", paid:"+paid+", score:"+Score+"]";
		}

		private string id;
		private string username;
		private bool viewed;
		private bool paid;
		private int? score;

	}

}


text:
<?php
if (isset($_helpers) && $assets = $_helpers['assets']) {
  $assets->includeJs('js/foo.js', 'js/bar.js');
  $assets->includeJs('js/bar.js');
  $assets->includeCss('css/foo.css');
}
?>

Javascript and CSS Include Example


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType ApplicationStatusCodeType
 * @xmlName ApplicationStatusCode
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\ApplicationStatusCode
 */
class ApplicationStatusCode extends ApplicationStatusCodeType
{
} // end class ApplicationStatusCode


text:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

def make_author_graph(papers):
    G = nx.Graph()

    counts = papers.groupby('author').apply(len)
    for paper, df in papers.groupby('url'):
        authors = df['author']
        for author in authors:
            if not G.has_node(author):
                G.add_node(author)
                G.node[author]['papers'] = counts[author]

        for i, author1 in enumerate(authors):
            for author2 in authors[(i + 1):]:
                if not G.has_edge(author1, author2):
                    G.add_edge(author1, author2)
                    G.edge[author1][author2]['weight'] = 0
                G.edge[author1][author2]['weight'] += 1

    return G

def draw(G, with_labels=False, n=10, threshold=1):
    nodes = set([v for v in G if G.node[v]['papers'] >= threshold])
    subgraph = G.subgraph(nodes)
    labels = {v: v for v in subgraph if G.degree(v) >= n}

    node_color = np.array([float(G.node[v]['papers']) for v in subgraph])
    node_color = node_color - node_color.min()
    node_color = node_color / node_color.max()
    node_color = 1 - node_color

    node_size = [(G.degree(v) ** 2) * 2 for v in subgraph]

    nx.draw(
        subgraph,
        node_color=node_color,
        node_size=node_size,
        with_labels=with_labels,
        labels=labels,
        cmap=plt.cm.Reds_r,
        alpha=0.8)


text:
class MethodCallLogger

  def initialize
    @recorders = []
    @method_log = []
  end

  def register(*rec_objects)
    rec_objects.each do |rec|
      rec._on_method_call{|r| method_log << [r, r._last_method] }
      recorders << rec
    end
  end

  attr_reader :recorders, :method_log

end


text:
package storage

import (
	"context"
	"io"
	"net/http"

	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/pingcap/errors"
	backuppb "github.com/pingcap/kvproto/pkg/brpb"
	berrors "github.com/pingcap/tidb/br/pkg/errors"
)

// Permission represents the permission we need to check in create storage.
type Permission string

const (
	// AccessBuckets represents bucket access permission
	// it replace the origin skip-check-path.
	AccessBuckets Permission = "AccessBucket"

	// ListObjects represents listObjects permission
	ListObjects Permission = "ListObjects"
	// GetObject represents GetObject permission
	GetObject Permission = "GetObject"
	// PutObject represents PutObject permission
	PutObject Permission = "PutObject"
)

// WalkOption is the option of storage.WalkDir.
type WalkOption struct {
	// walk on SubDir of specify directory
	SubDir string
	// ObjPrefix used fo prefix search in storage.
	// it can save lots of time when we want find specify prefix objects in storage.
	// For example. we have 10000 <Hash>.sst files and 10 backupmeta.(\d+) files.
	// we can use ObjPrefix = "backupmeta" to retrieve all meta files quickly.
	ObjPrefix string
	// ListCount is the number of entries per page.
	//
	// In cloud storages such as S3 and GCS, the files listed and sent in pages.
	// Typically a page contains 1000 files, and if a folder has 3000 descendant
	// files, one would need 3 requests to retrieve all of them. This parameter
	// controls this size. Note that both S3 and GCS limits the maximum to 1000.
	//
	// Typically you want to leave this field unassigned (zero) to use the
	// default value (1000) to minimize the number of requests, unless you want
	// to reduce the possibility of timeout on an extremely slow connection, or
	// perform testing.
	ListCount int64
}

// ReadSeekCloser is the interface that groups the basic Read, Seek and Close methods.
type ReadSeekCloser interface {
	io.Reader
	io.Seeker
	io.Closer
}

// Uploader upload file with chunks.
type Uploader interface {
	// UploadPart upload part of file data to storage
	UploadPart(ctx context.Context, data []byte) error
	// CompleteUpload make the upload data to a complete file
	CompleteUpload(ctx context.Context) error
}

// Writer is like io.Writer but with Context, create a new writer on top of Uploader with NewUploaderWriter.
type Writer interface {
	// Write writes to buffer and if chunk is filled will upload it
	Write(ctx context.Context, p []byte) (int, error)
	// Close writes final chunk and completes the upload
	Close(ctx context.Context) error
}

// ExternalStorage represents a kind of file system storage.
type ExternalStorage interface {
	// WriteFile writes a complete file to storage, similar to os.WriteFile, but WriteFile should be atomic
	WriteFile(ctx context.Context, name string, data []byte) error
	// ReadFile reads a complete file from storage, similar to os.ReadFile
	ReadFile(ctx context.Context, name string) ([]byte, error)
	// FileExists return true if file exists
	FileExists(ctx context.Context, name string) (bool, error)
	// DeleteFile delete the file in storage
	DeleteFile(ctx context.Context, name string) error
	// Open a Reader by file path. path is relative path to storage base path
	Open(ctx context.Context, path string) (ExternalFileReader, error)
	// WalkDir traverse all the files in a dir.
	//
	// fn is the function called for each regular file visited by WalkDir.
	// The argument `path` is the file path that can be used in `Open`
	// function; the argument `size` is the size in byte of the file determined
	// by path.
	WalkDir(ctx context.Context, opt *WalkOption, fn func(path string, size int64) error) error

	// URI returns the base path as a URI
	URI() string

	// Create opens a file writer by path. path is relative path to storage base path
	Create(ctx context.Context, path string) (ExternalFileWriter, error)
	// Rename file name from oldFileName to newFileName
	Rename(ctx context.Context, oldFileName, newFileName string) error
}

// ExternalFileReader represents the streaming external file reader.
type ExternalFileReader interface {
	io.ReadCloser
	io.Seeker
}

// ExternalFileWriter represents the streaming external file writer.
type ExternalFileWriter interface {
	// Write writes to buffer and if chunk is filled will upload it
	Write(ctx context.Context, p []byte) (int, error)
	// Close writes final chunk and completes the upload
	Close(ctx context.Context) error
}

// ExternalStorageOptions are backend-independent options provided to New.
type ExternalStorageOptions struct {
	// SendCredentials marks whether to send credentials downstream.
	//
	// This field should be set to false if the credentials are provided to
	// downstream via external key managers, e.g. on K8s or cloud provider.
	SendCredentials bool

	// NoCredentials means that no cloud credentials are supplied to BR
	NoCredentials bool

	// HTTPClient to use. The created storage may ignore this field if it is not
	// directly using HTTP (e.g. the local storage).
	HTTPClient *http.Client

	// CheckPermissions check the given permission in New() function.
	// make sure we can access the storage correctly before execute tasks.
	CheckPermissions []Permission

	// S3Retryer is the retryer for create s3 storage, if it is nil,
	// defaultS3Retryer() will be used.
	S3Retryer request.Retryer

	// CheckObjectLockOptions check the s3 bucket has enabled the ObjectLock.
	// if enabled. it will send the options to tikv.
	CheckS3ObjectLockOptions bool
}

// Create creates ExternalStorage.
//
// Please consider using `New` in the future.
func Create(ctx context.Context, backend *backuppb.StorageBackend, sendCreds bool) (ExternalStorage, error) {
	return New(ctx, backend, &ExternalStorageOptions{
		SendCredentials: sendCreds,
		HTTPClient:      nil,
	})
}

// New creates an ExternalStorage with options.
func New(ctx context.Context, backend *backuppb.StorageBackend, opts *ExternalStorageOptions) (ExternalStorage, error) {
	switch backend := backend.Backend.(type) {
	case *backuppb.StorageBackend_Local:
		if backend.Local == nil {
			return nil, errors.Annotate(berrors.ErrStorageInvalidConfig, "local config not found")
		}
		return NewLocalStorage(backend.Local.Path)
	case *backuppb.StorageBackend_Hdfs:
		if backend.Hdfs == nil {
			return nil, errors.Annotate(berrors.ErrStorageInvalidConfig, "hdfs config not found")
		}
		return NewHDFSStorage(backend.Hdfs.Remote), nil
	case *backuppb.StorageBackend_S3:
		if backend.S3 == nil {
			return nil, errors.Annotate(berrors.ErrStorageInvalidConfig, "s3 config not found")
		}
		return NewS3Storage(backend.S3, opts)
	case *backuppb.StorageBackend_Noop:
		return newNoopStorage(), nil
	case *backuppb.StorageBackend_Gcs:
		if backend.Gcs == nil {
			return nil, errors.Annotate(berrors.ErrStorageInvalidConfig, "GCS config not found")
		}
		return NewGCSStorage(ctx, backend.Gcs, opts)
	case *backuppb.StorageBackend_AzureBlobStorage:
		return newAzureBlobStorage(ctx, backend.AzureBlobStorage, opts)
	default:
		return nil, errors.Annotatef(berrors.ErrStorageInvalidConfig, "storage %T is not supported yet", backend)
	}
}


text:
\hypertarget{vanleer_8h}{}\section{vanleer.\+h File Reference}
\label{vanleer_8h}\index{vanleer.\+h@{vanleer.\+h}}
{\ttfamily \#include \char`\"{}global.\+h\char`\"{}}\newline
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
double \hyperlink{vanleer_8h_addbd15668a2d3f3d086c14bb917dd5a8}{vanleer} (double, double)
\end{DoxyCompactItemize}

\subsection{Function Documentation}
\mbox{\Hypertarget{vanleer_8h_addbd15668a2d3f3d086c14bb917dd5a8}\label{vanleer_8h_addbd15668a2d3f3d086c14bb917dd5a8}}
\index{vanleer.\+h@{vanleer.\+h}!vanleer@{vanleer}}
\index{vanleer@{vanleer}!vanleer.\+h@{vanleer.\+h}}
\subsubsection{\texorpdfstring{vanleer()}{vanleer()}}
{\footnotesize\ttfamily double vanleer (\begin{DoxyParamCaption}\item[{double}]{,  }\item[{double}]{ }\end{DoxyParamCaption})}


text:
<?php

// Copyright (c) 2016, Volo, LLC of South Carolina, USA

require_once('../base/AbstractGateway.php');

class TokGateway extends AbstractTokGateway {

protected $URLTest = 'https://sandbox.2checkout.com/checkout/api/1/XXXX/rs/authService';
protected $URLLive = 'https://www.2checkout.com/checkout/api/1/XXXX/rs/authService';

protected $URLTestRefund = 'https://sandbox.2checkout.com/api/sales/refund_invoice';
protected $URLLiveRefund = 'https://www.2checkout.com/api/sales/refund_invoice';

protected $SellerID = '';
protected $MerchantOrderID = '';
protected $Username = '';
protected $Password = '';

public function setUsername($sUsername) {
	$this->Username = $sUsername;
}

public function setPassword($sPassword) {
	$this->Password = $sPassword;
}

public function setSellerID($sSellerID) {
	$this->SellerID = $sSellerID;
}

public function setMerchantOrderID($sMerchantOrderID) {
	$this->MerchantOrderID = $sMerchantOrderID;
}

public function adjustBilling($asBilling) {
	$asTemp = (object) $asBilling;
	$asBilling = $asTemp;
	$a = array(
		'name' => @ $asBilling->billingName,
		'addrLine1' => @ $asBilling->billingAddress1,
		'addrLine2' => @ $asBilling->billingAddress2,
		'city' => @ $asBilling->billingCity,
		'state' => @ $asBilling->billingState,
		'zipCode' => @ $asBilling->billingPostcode,
		'country' => @ $asBilling->billingCountry,
		'email' => @ $asBilling->billingEmail,
		'phoneNumber' => @ $asBilling->billingPhone
	);
	$sTest = $a['name'];
	if (empty($sTest)) {
		$a['name'] = @ $asBilling->name;
	}
	$sTest = $a['email'];
	if (empty($sTest)) {
		$a['email'] = @ $asBilling->email;
	}
	return $a;
}

public function adjustShipping($asShipping) {
	$asTemp = (object) $asShipping;
	$asShipping = $asTemp;
	$a = array(
		'cust_shippingName' => @ $asShipping->shippingName,
		'cust_shippingAddrLine1' => @ $asShipping->shippingAddress1,
		'cust_shippingAddrLine2' => @ $asShipping->shippingAddress2,
		'cust_shippingCity' => @ $asShipping->shippingCity,
		'cust_shippingState' => @ $asShipping->shippingState,
		'cust_shippingZipCode' => @ $asShipping->shippingPostcode,
		'cust_shippingCountry' => @ $asShipping->shippingCountry,
		'cust_shippingPhoneNumber' => @ $asShipping->shippingPhone
	);
	$sTest = $a['cust_shippingName'];
	if (empty($sTest)) {
		$a['cust_shippingName'] = @ $asShipping->name;
	}
	return $a;
}

public function sendCharge(
	$sURL,
	$sAPIKey,
	$bTestMode,
	$bDebugMode,
	$bVerifySSL,
	$asBilling,
	$asShipping,
	$asCharge
) {

	$sSellerID = $this->SellerID;
	$sMerchantOrderID = $this->MerchantOrderID;
	$sMerchantOrderID = (empty($sMerchantOrderID)) ? uniqid() : $sMerchantOrderID;
	$sURL = str_replace('XXXX',$sSellerID,$sURL);

	$oResponse = (object) array();
	$oResponse->isSuccess = FALSE;
	$oResponse->TransID = NULL;
	$oResponse->FailCode = NULL;
	$oResponse->FailMessage = NULL;
	// translate the Billing, Shipping, and Purchase arrays as necessary for 2Checkout charges
	$asFields = array(
		'sellerId' => $sSellerID,
		'merchantOrderId' => $sMerchantOrderID,
		'token' => @ $asCharge['token'],
		'currency' => @ $asCharge['currency'],
		'total' => @ $asCharge['amount'],
	);
	if (is_array($asBilling)) {
		$nCount = count($asBilling);
		if ($nCount > 0) {
			$asFields['billingAddr'] = $this->adjustBilling($asBilling);
		}
	}
	if (is_array($asShipping)) {
		$nCount = count($asShipping);
		if ($nCount > 0) {
			$asShipping = $this->adjustShipping($asShipping);
			$asFields = array_merge($asFields,$asShipping);
		}
	}
	$sDescTest = @ $asCharge['description'];
	if ($sDescTest) {
		$asFields['cust_description'] = $sDescTest;
	}
	$asFields['privateKey'] = $sAPIKey;
	// do the http connection with the data
	$sFields = json_encode($asFields);
	$nLen = mb_strlen($sFields,'UTF-8');
	$asOpt = array (
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_HTTPHEADER =>
		array (
			'content-type:application/json',
			"content-length:$nLen",
		),
		CURLOPT_USERAGENT => '2Checkout PHP/0.1.0%s',
		CURLOPT_POSTFIELDS => $sFields,
	);
	$hCurl = curl_init($sURL);
if ($bDebugMode) {
echo "\nCURL OPTIONS = \n";
print_r($asOpt);
echo "\n";
}
	curl_setopt_array($hCurl,$asOpt);
	curl_setopt($hCurl, CURLOPT_SSL_VERIFYPEER, $bVerifySSL);
	$sResponse = curl_exec($hCurl);
if ($bDebugMode) {
echo "\nRAW RESPONSE = \n$sResponse\n";
}
	$nErr = 0;
	$nResponseCode = 0;
	if ($sResponse === FALSE) {
		$nErr = curl_errno($hCurl);
		$sErr = curl_error($hCurl);
if ($bDebugMode) {
echo "\nCURL ERROR = $sErr ($nErr)\n";
}
		// debug with $nErr or $sErr if you want
	} else {
		$nResponseCode = curl_getinfo($hCurl, CURLINFO_HTTP_CODE);
		$nResponseCode = intval($nResponseCode);
if ($bDebugMode) {
echo "\nCURL RESPONSE CODE = $nResponseCode\n";
}
		// debug with $nResponseCode if you want
	}
	$nResponseCode = intval($nResponseCode);
	curl_close($hCurl);

	// parse the response and update our $oResponse object
	if ($nErr > 0) {
		$oResponse->FailMessage = "Error communicating with 2Checkout payment system.";
		return $oResponse;
	}
	if ($nResponseCode >= 400) {
		$oResponse->FailCode = $nResponseCode;
	}
	if ($nResponseCode == 400) {
		@ $oJSON = json_decode($sResponse);
		$sMessage = @ $oJSON->exception->errorMsg;
		$sCode = @ $oJSON->exception->errorCode;
		if (!empty($sCode)) {
			$oResponse->FailCode = $sCode;
			$oResponse->FailMessage = $sMessage;
			return $oResponse;
		}
		$oResponse->FailMessage = "Error from 2Checkout payment system. The request was unacceptable, often due to missing a required parameter, or an invalid token.";
		return $oResponse;
	}
	if ($nResponseCode == 401) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. No valid API key provided.";
		return $oResponse;
	}
	if ($nResponseCode == 402) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The parameters were valid but the request failed.";
		return $oResponse;
	}
	if ($nResponseCode == 404) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The requested resource doesn't exist.";
		return $oResponse;
	}
	if ($nResponseCode == 409) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The request conflicts with another request (perhaps due to using the same idempotent key).";
		return $oResponse;
	}
	if ($nResponseCode == 429) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Too many requests hit the API too quickly.";
		return $oResponse;
	}
	if ($nResponseCode >= 500) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Unknown error.";
		return $oResponse;
	}
	if (strpos($sResponse,'}') === FALSE) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Incomplete JSON.";
		return $oResponse;
	}
	$oJSON = json_decode($sResponse);
if ($bDebugMode) {
echo "\nJSON OBJECT = \n";
print_r($oJSON);
echo "\n";
}
	$bSuccess = @ $oJSON->response->responseCode;
	$sTransID = @ $oJSON->response->orderNumber;
	$oResponse->isSuccess = (($bSuccess == 'APPROVED') and ($sTransID != ''));
	$oResponse->TransID = $sTransID;
	if (!$oResponse->isSuccess) {
		$oResponse->FailMessage = @ $oJSON->exception->errorMsg;
		$oResponse->FailCode = @ $oJSON->exception->errorCode;
	}
	return $oResponse;
}

public function sendRefund(
	$sURL, // ignore in this case, we'll override with a custom one for refunds
	$sAPIKey,
	$bTestMode,
	$bDebugMode,
	$bVerifySSL,
	$sChargeID,
	$nAmount // ignored by 2CO in this case
) {
	$sUser = $this->Username;
	$sPass = $this->Password;
	$bTestMode = $this->TestMode;
	$sURL = ($bTestMode) ? $this->URLTestRefund : $this->URLLiveRefund;

	$oResponse = (object) array();
	$oResponse->isSuccess = FALSE;
	$oResponse->TransID = NULL;
	$oResponse->FailCode = NULL;
	$oResponse->FailMessage = NULL;
	$asFields = array(
		'sale_id' => $sChargeID,
		'comment' => 'Customer decided the item did not meet expectations and it was within their refund period.',
		'category' => 2 // did not like item
	);
	// do the http connection with the data
	$sFields = json_encode($asFields);
	$nLen = strlen($sFields);
	$asOpt = array (
		CURLOPT_HEADER => 0,
		CURLOPT_POST => 0,
		CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
		CURLOPT_USERPWD => "$sUser:$sPass",
		CURLOPT_HTTPHEADER =>  array("Accept: application/json"),
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_USERAGENT => '2Checkout PHP/0.1.0%s',
		CURLOPT_POSTFIELDS => $sFields
	);
	$hCurl = curl_init($sURL);
if ($bDebugMode) {
echo "\nCURL OPTIONS = \n";
print_r($asOpt);
echo "\n";
}
	curl_setopt_array($hCurl,$asOpt);
	curl_setopt($hCurl, CURLOPT_SSL_VERIFYPEER, $bVerifySSL);
	$sResponse = curl_exec($hCurl);
if ($bDebugMode) {
echo "\nRAW RESPONSE = \n$sResponse\n";
}
	$nErr = 0;
	$nResponseCode = 0;
	if ($sResponse === FALSE) {
		$nErr = curl_errno($hCurl);
		$sErr = curl_error($hCurl);
if ($bDebugMode) {
echo "\nCURL ERROR = $sErr ($nErr)\n";
}
		// debug with $nErr or $sErr if you want
	} else {
		$nResponseCode = curl_getinfo($hCurl, CURLINFO_HTTP_CODE);
		$nResponseCode = intval($nResponseCode);
if ($bDebugMode) {
echo "\nCURL RESPONSE CODE = $nResponseCode\n";
}
		// debug with $nResponseCode if you want
	}
	$nResponseCode = intval($nResponseCode);
	curl_close($hCurl);

	// parse the response and update our $oResponse object
	if ($nErr > 0) {
		$oResponse->FailMessage = "Error communicating with 2Checkout payment system.";
		return $oResponse;
	}
	if ($nResponseCode >= 400) {
		$oResponse->FailCode = $nResponseCode;
	}
	if ($nResponseCode == 400) {
		@ $oJSON = json_decode($sResponse);
		$sMessage = @ $oJSON->exception->errorMsg;
		$sCode = @ $oJSON->exception->errorCode;
		if (!empty($sCode)) {
			$oResponse->FailCode = $sCode;
			$oResponse->FailMessage = $sMessage;
			return $oResponse;
		}
		$oResponse->FailMessage = "Error from 2Checkout payment system. The request was unacceptable, often due to missing a required parameter, or an invalid token.";
		return $oResponse;
	}
	if ($nResponseCode == 401) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. No valid API key provided.";
		return $oResponse;
	}
	if ($nResponseCode == 402) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The parameters were valid but the request failed.";
		return $oResponse;
	}
	if ($nResponseCode == 404) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The requested resource doesn't exist.";
		return $oResponse;
	}
	if ($nResponseCode == 409) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. The request conflicts with another request (perhaps due to using the same idempotent key).";
		return $oResponse;
	}
	if ($nResponseCode == 429) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Too many requests hit the API too quickly.";
		return $oResponse;
	}
	if ($nResponseCode >= 500) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Unknown error.";
		return $oResponse;
	}
	if (strpos($sResponse,'}') === FALSE) {
		$oResponse->FailMessage = "Error from 2Checkout payment system. Incomplete JSON.";
		return $oResponse;
	}
	$oJSON = json_decode($sResponse);
if ($bDebugMode) {
echo "\nJSON OBJECT = \n";
print_r($oJSON);
echo "\n";
}
	$bSuccess = @ $oJSON->response->responseCode;
	$sTransID = @ $oJSON->response->orderNumber;
	$oResponse->isSuccess = (($bSuccess == 'APPROVED') and ($sTransID != ''));
	$oResponse->TransID = $sTransID;
	if (!$oResponse->isSuccess) {
		$oResponse->FailMessage = @ $oJSON->exception->errorMsg;
		$oResponse->FailCode = @ $oJSON->exception->errorCode;
	}
	return $oResponse;

}

} // end TokGateway


text:
function [q_data, t_data, ee_info,idx_t_infeasible] = ladderIK(r,ts,q0,qstar,ee_info,ladder_opts,ikoptions)
  nq = r.getNumPositions();

  pelvis = r.findLinkId('pelvis');
  utorso = r.findLinkId('utorso');
  neck_joint = findPositionIndices(r,'neck');
  knee_joints = [findPositionIndices(r,'l_leg_kny'); ...
                 findPositionIndices(r,'r_leg_kny')];
  arm_joints = findPositionIndices(r,'arm');

  if ~isfield(ladder_opts,'use_quasistatic_constraint')
    ladder_opts.use_quasistatic_constraint =  true;
  end
  if ~isfield(ladder_opts,'use_com_constraint')
    ladder_opts.use_com_constraint =          false;
  end
  if ~isfield(ladder_opts,'use_incr_com_constraint')
    ladder_opts.use_incr_com_constraint =     false;
  end
  if ~isfield(ladder_opts,'use_final_com_constraint')
    ladder_opts.use_final_com_constraint =    true;
  end
  if ~isfield(ladder_opts,'use_arm_constraints')
    ladder_opts.use_arm_constraints =         false;
  end
  if ~isfield(ladder_opts,'use_pelvis_gaze_constraint')
    ladder_opts.use_pelvis_gaze_constraint =  true;
  end
  if ~isfield(ladder_opts,'use_pelvis_constraint')
    ladder_opts.use_pelvis_constraint =       true;
  end
  if ~isfield(ladder_opts,'use_utorso_constraint')
    ladder_opts.use_utorso_constraint =       true;
  end
  if ~isfield(ladder_opts,'use_knee_constraint')
    ladder_opts.use_knee_constraint =         true;
  end
  if ~isfield(ladder_opts,'use_ankle_constraint')
    ladder_opts.use_ankle_constraint =        true;
  end
  if ~isfield(ladder_opts,'use_neck_constraint')
    ladder_opts.use_neck_constraint =         true;
  end
  if ~isfield(ladder_opts,'use_swing_foot_euler_constraint')
    ladder_opts.use_swing_foot_euler_constraint =         false;
  end
  if ~isfield(ladder_opts,'compute_intro')
    ladder_opts.compute_intro = false;
  end
  if ~isfield(ladder_opts,'smooth_output');
    ladder_opts.smooth_output = false;
  end
  if ~isfield(ladder_opts,'smoothing_span');
    ladder_opts.smoothing_span = 5;
  end
  if ~isfield(ladder_opts,'smoothing_method');
    ladder_opts.smoothing_method = 'moving';
  end

  if ~isfield(ladder_opts,'shrink_factor')
    ladder_opts.shrink_factor = 0.1;
  end
  if ~isfield(ladder_opts,'final_shrink_factor')
    ladder_opts.shrink_factor = 0.5;
  end
  if ~isfield(ladder_opts,'utorso_threshold')
    ladder_opts.utorso_threshold = 25*pi/180;
  end
  if ~isfield(ladder_opts,'pelvis_gaze_threshold')
    ladder_opts.pelvis_gaze_threshold = 20*pi/180;
  end
  if ~isfield(ladder_opts,'ankle_limit')
    ladder_opts.ankle_limit = 25*pi/180;
  end
  if ~isfield(ladder_opts,'knee_lb')
    ladder_opts.knee_lb = 30*pi/180*ones(size(knee_joints));
  end
  if ~isfield(ladder_opts,'knee_ub')
    ladder_opts.knee_ub = inf*pi/180*ones(size(knee_joints));
  end
  if ~isfield(ladder_opts,'hand_threshold')
    ladder_opts.hand_threshold = sin(1*pi/180);
  end
  if ~isfield(ladder_opts,'hand_cone_threshold')
    ladder_opts.hand_cone_threshold = sin(1*pi/180);
  end
  if ~isfield(ladder_opts,'hand_pos_tol')
    ladder_opts.hand_pos_tol = 0.01;
  end
  if ~isfield(ladder_opts,'pelvis_threshold')
    ladder_opts.pelvis_threshold = 0.05;
  end
  if ~isfield(ladder_opts,'com_tol')
    ladder_opts.com_tol = 0.1;
  end
  if ~isfield(ladder_opts,'com_incr_tol')
    ladder_opts.com_incr_tol = 0.02;
  end
  if ~isfield(ladder_opts,'com_tol_max')
    ladder_opts.com_tol_max = 0.5;
  end
  if ~isfield(ladder_opts,'arm_tol_total')
    ladder_opts.arm_tol_total = 30*pi/180;
  end
  if ~isfield(ladder_opts,'verbose')
    ladder_opts.verbose = false;
  end
  com_tol_vec = [ladder_opts.com_tol;ladder_opts.com_tol;NaN];
  com_incr_tol_vec = [ladder_opts.com_incr_tol;ladder_opts.com_incr_tol;NaN];

  % time spacing of samples for IK
  nt = length(ts);

  logical2str = @(b) regexprep(sprintf('%i',b),{'1','0'},{' ON ',' OFF '});
  fprintf('\n');
  fprintf('Constraint Summary\n');
  fprintf('==================================\n');
  fprintf('Name                      Status    Tolerance\n');
  fprintf('QS Constraint             %s        %4.2f\n', logical2str(ladder_opts.use_quasistatic_constraint),ladder_opts.shrink_factor);
  fprintf('Incr. COM Constraint:     %s        %4.2f m\n', logical2str(ladder_opts.use_incr_com_constraint), ladder_opts.com_incr_tol);
  fprintf('COM Constraint:           %s        %4.2f m\n', logical2str(ladder_opts.use_com_constraint), ladder_opts.com_tol);
  fprintf('Final COM Constraint:     %s\n', logical2str(ladder_opts.use_final_com_constraint));
  fprintf('Pelvis Constraint:        %s        %4.2f m\n', logical2str(ladder_opts.use_pelvis_constraint), ladder_opts.pelvis_threshold);
  fprintf('Pelvis GazeConstraint:    %s        %4.2f deg\n', logical2str(ladder_opts.use_pelvis_gaze_constraint),ladder_opts.pelvis_gaze_threshold*180/pi);
  fprintf('Torso Constraint:         %s        %4.2f deg\n', logical2str(ladder_opts.use_utorso_constraint),ladder_opts.utorso_threshold*180/pi);
  fprintf('Knee Constraint:          %s        [%4.2f deg, %4.2f deg]\n', logical2str(ladder_opts.use_knee_constraint),ladder_opts.knee_lb(1)*180/pi,ladder_opts.knee_ub(1)*180/pi);
  fprintf('Neck Constraint:          %s\n', logical2str(ladder_opts.use_neck_constraint));
  fprintf('Ankle Constraint:         %s\n', logical2str(ladder_opts.use_ankle_constraint));
  fprintf('Arm Constraints (incr):   %s        %4.2f deg\n', logical2str(ladder_opts.use_arm_constraints),ladder_opts.arm_tol*180/pi);

  hand_grasped(1) = ~isempty(ee_info.hands(1));
  hand_grasped(2) = ~isempty(ee_info.hands(1));

  basic_constraints = {};

  tf = ts(end);

  if ladder_opts.use_knee_constraint
    knee_constraint = PostureConstraint(r);
    knee_constraint = knee_constraint.setJointLimits(knee_joints, ...
      ladder_opts.knee_lb, ...
      ladder_opts.knee_ub);
    basic_constraints = [basic_constraints, {knee_constraint}];
  end

  if ladder_opts.use_neck_constraint
    neck_constraint = PostureConstraint(r);
    neck_constraint = neck_constraint.setJointLimits(neck_joint,q0(neck_joint),q0(neck_joint));
    basic_constraints = [basic_constraints, {neck_constraint}];
  end

  kinsol = doKinematics(r,q0);
  if ladder_opts.use_utorso_constraint
    utorso_posquat = forwardKin(r,kinsol,utorso,[0;0;0],2);
    basic_constraints = [ ...
      basic_constraints, ...
      {WorldGazeOrientConstraint(r,utorso,[0;0;1],utorso_posquat(4:7),ladder_opts.utorso_threshold,90*pi/180)}];
  end

  pelvis_xyzrpy = forwardKin(r,kinsol,pelvis,[0;0;0],1);
  o_T_pelvis = HT(pelvis_xyzrpy(1:3),pelvis_xyzrpy(4),pelvis_xyzrpy(5),pelvis_xyzrpy(6));
  if ladder_opts.use_pelvis_constraint
    basic_constraints = [ ...
      basic_constraints, ...
      {WorldPositionInFrameConstraint(r,pelvis, ...
      [0;0;0], o_T_pelvis, [NaN;-ladder_opts.pelvis_threshold;NaN], ...
      [NaN;ladder_opts.pelvis_threshold;NaN])}];
  end

  if ladder_opts.use_pelvis_gaze_constraint
    basic_constraints = [ ...
      basic_constraints, ...
      {WorldGazeDirConstraint(r,pelvis,[0;0;1],[0;0;1],ladder_opts.pelvis_gaze_threshold)}];
  end

  rpy_tol_max = 30*pi/180;
  foot_retract_max = 0.1;
  foot_retract_vec = foot_retract_max*o_T_pelvis(1:3,1:3)*[-1;0;0];
  for i=1:2
    deriv = fnder(ee_info.feet(i).traj);
    t_moving = ts(any(abs(eval(deriv,ts)) > 0,1));
    if isempty(t_moving)
      ee_info.feet(i).rpy_tol_traj = PPTrajectory(foh([0,tf],repmat([0,0],3,1)));
    else
      t_move0 = t_moving(1);
      t_movef = t_moving(end);
      ee_info.feet(i).rpy_tol_traj = ...
        PPTrajectory(foh([0,linspace(t_move0,t_movef,4),tf],repmat([0,0,rpy_tol_max,0,0,0],3,1)));
      ee_info.feet(i).foot_retract_traj = ...
        PPTrajectory(foh([0,linspace(t_move0,t_movef,5),tf],[zeros(3,2),repmat(foot_retract_vec(1:3),1,2),zeros(3,3)]));
    end
  end

  if ladder_opts.verbose
    msg = '  0%%';
    fprintf(['Progress: ',msg]);
    len_prev_msg = length(sprintf(msg));
  end
  n_err = 0;
  first_err = true;
  err_segments = [];

  q_seed = q0;
  q_nom = qstar;
  q = zeros(nq,nt);
  q(:,1) = q_seed;
  constraint_array = cell(nt,1);
  idx_t_infeasible = false(1,nt);
  for i=1:nt
    t_data = ts(i);
    constraints = basic_constraints;

    foot_supported(1) = ( eval(ee_info.feet(1).support_traj,t_data) && eval(ee_info.feet(1).support_traj,ts(min(i+1,nt))) );
    foot_supported(2) = ( eval(ee_info.feet(2).support_traj,t_data) && eval(ee_info.feet(2).support_traj,ts(min(i+1,nt))) );

    if ladder_opts.use_arm_constraints
      arm_constraint = PostureConstraint(r);
      if i==1
        arm_constraint = arm_constraint.setJointLimits(arm_joints,q0(arm_joints)-ladder_opts.arm_tol,q0(arm_joints)+ladder_opts.arm_tol);
      else
        arm_constraint = arm_constraint.setJointLimits(arm_joints,q(arm_joints,i-1)-ladder_opts.arm_tol,q(arm_joints,i-1)+ladder_opts.arm_tol);
      end
      constraints = [constraints, {arm_constraint}];
    end
    if ladder_opts.use_ankle_constraint && any(foot_supported)
      for j = 1:2
        if foot_supported(j)
          ankle_constraint = PostureConstraint(r);
          ankle_constraint = ankle_constraint.setJointLimits( ...
            findPositionIndices(r,r.getBody(r.getBody(ee_info.feet(j).idx).parent).jointname), ...
            -ladder_opts.ankle_limit, ...
            10*ladder_opts.ankle_limit);
          constraints = [constraints, {ankle_constraint}];
        end
      end
    end
    if ladder_opts.use_quasistatic_constraint && any(foot_supported)
      qsc = QuasiStaticConstraint(r);
      for j = 1:2
        if foot_supported(j)
          qsc = qsc.addContact(ee_info.feet(j).idx,r.getBodyContacts(ee_info.feet(j).idx));
        end
      end
      qsc = qsc.setShrinkFactor(ladder_opts.shrink_factor);
      qsc = qsc.setActive(true);
      constraints = [constraints, {qsc}];
    end
    for j = 1:2
      pos_eq = ee_info.feet(j).traj.eval(t_data);
      rpy_tol = eval(ee_info.feet(j).rpy_tol_traj,t_data);
      foot_retract = eval(ee_info.feet(j).foot_retract_traj,t_data);
      pos_eq(1:2) = pos_eq(1:2) + foot_retract(1:2);
      constraints = [ ...
        constraints, ...
        {WorldPositionConstraint(r,ee_info.feet(j).idx, ...
        ee_info.feet(j).pt(1:3), ...
        pos_eq(1:3),pos_eq(1:3))}];
      if foot_supported(j) || ladder_opts.use_swing_foot_euler_constraint
        constraints = [ ...
          constraints, ...
          {WorldEulerConstraint(r,ee_info.feet(j).idx, ...
          pos_eq(4:6)-rpy_tol, ...
          pos_eq(4:6)+rpy_tol)}];
      end
      if hand_grasped(j)
        pos_min = ee_info.hands(j).min_traj.eval(t_data);
        pos_max = ee_info.hands(j).max_traj.eval(t_data);
        pos_eq = (pos_min+pos_max)/2;
        pelvis_T_rail = eye(4);
        pelvis_T_rail(1:3,1:3) = roty(30*pi/180);
        pelvis_T_rail(1:3,4) = o_T_pelvis(1:3,1:3)\(pos_eq(1:3) - o_T_pelvis(1:3,4));
        o_T_rail = o_T_pelvis*pelvis_T_rail;
        constraints = [ ...
          constraints, ...
          {WorldPositionInFrameConstraint(r, ee_info.hands(j).link_ndx, ...
          ee_info.hands(j).pt, o_T_rail, [-ladder_opts.hand_pos_tol;-ladder_opts.hand_pos_tol;-ladder_opts.hand_pos_tol], [ladder_opts.hand_pos_tol;ladder_opts.hand_pos_tol;ladder_opts.hand_pos_tol]), ...
          WorldQuatConstraint(r,ee_info.hands(j).link_ndx,pos_min(4:7),ladder_opts.hand_threshold)}];
      end
    end

    if i > 1 && ladder_opts.use_incr_com_constraint
      constraints = [ ...
        constraints, ...
        {WorldCoMConstraint(r,com_prev-com_incr_tol_vec,com_prev+com_incr_tol_vec)}];
    end
    if ladder_opts.use_com_constraint
      com = eval(ladder_opts.comtraj,ts(i));
      com(3) = NaN;
      constraints = [ ...
        constraints, ...
        {WorldCoMConstraint(r,com-com_tol_vec,com+com_tol_vec)}];
    end
    [q(:,i),info,infeasible] = inverseKinPointwise(r,t_data,q_seed,q_nom,constraints{:},ikoptions);
    if info > 4
      if ladder_opts.use_com_constraint
        ladder_opts.com_tol_local = ladder_opts.com_tol;
        while info ~= 1 && ladder_opts.com_tol_local < ladder_opts.com_tol_max
          %display(ladder_opts.com_tol_local(1))
          ladder_opts.com_tol_local = ladder_opts.com_tol_local+0.01;
          constraints{end} = WorldCoMConstraint(r,com-ladder_opts.com_tol_local,com+ladder_opts.com_tol_local);
          [q(:,i),info,infeasible] = inverseKinPointwise(r,t_data,q_seed,q(:,i),constraints{:},ikoptions);
        end
%         fprintf('Max com deviation: %5.3f m\n',ladder_opts.com_tol_local);
      end
      if info > 4
        %       disp(infeasible);keyboard
        n_err = n_err+1;
        if first_err
          err_segments(end+1,1) = i/nt;
          first_err = false;
        else
          err_segments(end,2) = i/nt;
        end
        idx_t_infeasible(i) = true;
      else
        first_err = true;
      end
    else
      first_err = true;
%       fprintf('Max com deviation: %5.3f m\n',ladder_opts.com_tol);
    end;
    if ladder_opts.verbose
      msg = '%3.0f%% (No. Errors: %2.0f)';
      fprintf([repmat('\b',1,len_prev_msg), msg],i/nt*100,n_err);
      len_prev_msg = length(sprintf(msg,i/nt*100,n_err));
    end
    if ladder_opts.compute_intro && i==1
      % Compute plan from q0 to q(:,1)
      nt_init = floor(nt/4);
      dt = mean(diff(ts));
      t_init = 0:dt:nt_init*dt;
      q_init_nom = PPTrajectory(foh([t_init(1),t_init(end)],[q0,q(:,1)]));
      q_init = eval(q_init_nom,t_init);
    end
    q_seed = q(:,i);
    constraint_array{i} = constraints;
    kinsol = doKinematics(r,q_seed);
    com_prev = r.getCOM(kinsol);
    com_prev(3) = NaN;
  end
  fprintf('\n');
  q_data = q;
  t_data = ts;
  if ladder_opts.compute_intro
    q_data = [q_init,q];
    t_data = [t_init, ts+t_init(end)+dt];
    idx_t_infeasible = [false(size(t_init)),idx_t_infeasible];
  end
  if ladder_opts.use_final_com_constraint
    % Compute plan from q(:,end) to qf
    nt_end = floor(nt/4);
    dt = mean(diff(ts));
    t_end = 0:dt:nt_end*dt;
    t_end_coarse = linspace(t_end(1),t_end(end),3);
    % com_constraint_f = WorldCoMConstraint(r,com,com,t_end(end)*[1,1]);
    com_constraint_f = QuasiStaticConstraint(r);
    com_constraint_f = com_constraint_f.setActive(true);
    com_constraint_f = com_constraint_f.setShrinkFactor(ladder_opts.final_shrink_factor);
    foot1_pts = r.getBodyContacts(ee_info.feet(1).idx);
    foot2_pts = r.getBodyContacts(ee_info.feet(2).idx);
    com_constraint_f = com_constraint_f.addContact(ee_info.feet(1).idx,foot1_pts,ee_info.feet(2).idx,foot2_pts);
    constraints(cellfun(@(con) isa(con,'WorldCoMConstraint'),constraints)) = [];
    back_z_constraint_f = PostureConstraint(r);
    back_z_constraint_f = back_z_constraint_f.setJointLimits([6;findPositionIndices(r,'back_bkz')],[q0(6);0],[q0(6);0]);

    [qf,info,infeasible] = inverseKin(r,q(:,end),qstar,constraints{1:end},com_constraint_f,back_z_constraint_f,ikoptions);
    if info ~= 1, warning('robotLaderPlanner:badInfo','info = %d',info); end;

    q_end_nom = PPTrajectory(foh([t_end(1),t_end(end)],[q(:,end),qf]));
    end_posture_constraint = PostureConstraint(r,t_end_coarse(end)*[1,1]);
    end_posture_constraint = end_posture_constraint.setJointLimits((1:nq)',qf,qf);
    ikoptions = ikoptions.setAdditionaltSamples(t_end);
    x_end_traj = PPTrajectory(foh(t_end([1,end]),[[q(:,end),qf];zeros(nq,2)]));
    x_end = eval(x_end_traj,t_end);
    q_end = x_end(1:nq,:);
    q_data = [q_data,q_end];
    t_data = [t_data, t_end + t_data(end) + dt];
    idx_t_infeasible = [idx_t_infeasible,repmat(info>10,size(t_end))];
  end
%   display(err_segments);
  if ladder_opts.smooth_output
    for i = 1:nq
      q_data(i,:) = smooth(q_data(i,:)',ladder_opts.smoothing_span);
    end
  end
end


text:
<?php
/**
 * Manage link administration actions.
 *
 * This page is accessed by the link management pages and handles the forms and
 * AJAX processes for link actions.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );

wp_reset_vars( array( 'action', 'cat_id', 'link_id' ) );

if ( ! current_user_can('manage_links') )
	wp_link_manager_disabled_message();

if ( !empty($_POST['deletebookmarks']) )
	$action = 'deletebookmarks';
if ( !empty($_POST['move']) )
	$action = 'move';
if ( !empty($_POST['linkcheck']) )
	$linkcheck = $_POST['linkcheck'];

$this_file = admin_url('link-manager.php');

switch ($action) {
	case 'deletebookmarks' :
		check_admin_referer('bulk-bookmarks');

		//for each link id (in $linkcheck[]) change category to selected value
		if (count($linkcheck) == 0) {
			wp_redirect($this_file);
			exit;
		}

		$deleted = 0;
		foreach ($linkcheck as $link_id) {
			$link_id = (int) $link_id;

			if ( wp_delete_link($link_id) )
				$deleted++;
		}

		wp_redirect("$this_file?deleted=$deleted");
		exit;
		break;

	case 'move' :
		check_admin_referer('bulk-bookmarks');

		//for each link id (in $linkcheck[]) change category to selected value
		if (count($linkcheck) == 0) {
			wp_redirect($this_file);
			exit;
		}
		$all_links = join(',', $linkcheck);
		// should now have an array of links we can change
		//$q = $wpdb->query("update $wpdb->links SET link_category='$category' WHERE link_id IN ($all_links)");

		wp_redirect($this_file);
		exit;
		break;

	case 'add' :
		check_admin_referer('add-bookmark');

		$redir = wp_get_referer();
		if ( add_link() )
			$redir = add_query_arg( 'added', 'true', $redir );

		wp_redirect( $redir );
		exit;
		break;

	case 'save' :
		$link_id = (int) $_POST['link_id'];
		check_admin_referer('update-bookmark_' . $link_id);

		edit_link($link_id);

		wp_redirect($this_file);
		exit;
		break;

	case 'delete' :
		$link_id = (int) $_GET['link_id'];
		check_admin_referer('delete-bookmark_' . $link_id);

		wp_delete_link($link_id);

		wp_redirect($this_file);
		exit;
		break;

	case 'edit' :
		wp_enqueue_script('link');
		wp_enqueue_script('xfn');

		if ( wp_is_mobile() )
			wp_enqueue_script( 'jquery-touch-punch' );

		$parent_file = 'link-manager.php';
		$submenu_file = 'link-manager.php';
		$title = __('Edit Link');

		$link_id = (int) $_GET['link_id'];

		if (!$link = get_link_to_edit($link_id))
			wp_die(__('Link not found.'));

		include( ABSPATH . 'wp-admin/edit-link-form.php' );
		include( ABSPATH . 'wp-admin/admin-footer.php' );
		break;

	default :
		break;
}