text:
<?php

namespace Drupal\Driver;

use Drupal\Exception\BootstrapException,
    Drupal\DrupalExtension\Context\DrupalSubContextFinderInterface;

use Behat\Behat\Exception\PendingException;

/**
 * Fully bootstraps Drupal and uses native API calls.
 */
class DrupalDriver implements DriverInterface, DrupalSubContextFinderInterface {

  /**
   * Track whether Drupal has been bootstrapped.
   *
   * @var bool
   */
  private $bootstrapped = FALSE;

  /**
   * Drupal core object.
   *
   * @var \Drupal\Driver\Cores\CoreInterface
   */
  public $core;

  /**
   * Drupal core version.
   *
   * @var numeric
   */
  public $version;

  /**
   * Set Drupal root and URI.
   */
  public function __construct($drupalRoot, $uri) {
    $this->drupalRoot = realpath($drupalRoot);
    $this->uri = $uri;
    $this->version = $this->getDrupalVersion();
  }

  /**
   * Implements DriverInterface::bootstrap().
   */
  public function bootstrap() {
    $this->getCore()->bootstrap();
    $this->bootstrapped = TRUE;
  }

  /**
   * Implements DriverInterface::isBootstrapped().
   */
  public function isBootstrapped() {
    // Assume the blackbox is always bootstrapped.
    return $this->bootstrapped;
  }

  /**
   * Implements DriverInterface::userCreate().
   */
  public function userCreate(\stdClass $user) {
    $this->getCore()->userCreate($user);
  }

  /**
   * Implements DriverInterface::userDelete().
   */
  public function userDelete(\stdClass $user) {
    $this->getCore()->userDelete($user);
  }

  public function processBatch() {
    $this->getCore()->processBatch();
  }

  /**
   * Implements DriverInterface::userAddRole().
   */
  public function userAddRole(\stdClass $user, $role_name) {
    $this->getCore()->userAddRole($user, $role_name);
  }

  /**
   * Implements DriverInterface::fetchWatchdog().
   */
  public function fetchWatchdog($count = 10, $type = NULL, $severity = NULL) {
    throw new PendingException(sprintf('Currently no ability to access watchdog entries in %s', $this));
  }

  /**
   * Implements DriverInterface::clearCache().
   */
  public function clearCache($type = NULL) {
    $this->getCore()->clearCache();
  }

  /**
   * Implements DrupalSubContextFinderInterface::getPaths().
   */
  public function getSubContextPaths() {
    // Ensure system is bootstrapped.
    if (!$this->isBootstrapped()) {
      $this->bootstrap();
    }

    $paths = array();

    // Get enabled modules.
    $modules = \module_list();
    $paths = array();
    foreach ($modules as $module) {
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . \drupal_get_path('module', $module);
    }

    // Themes.
    // @todo

    // Active profile
    // @todo

    return $paths;
  }

  /**
   * Determine major Drupal version.
   *
   * @throws BootstrapException
   *
   * @see drush_drupal_version()
   */
  function getDrupalVersion() {
    if (!isset($this->drupalVersion)) {
      // Support 6, 7 and 8.
      $version_constant_paths = array(
        // Drupal 6.
        '/modules/system/system.module',
        // Drupal 7.
        '/includes/bootstrap.inc',
        // Drupal 8.
        '/core/vendor/autoload.php',
        '/core/includes/bootstrap.inc',
      );

      if ($this->drupalRoot === FALSE) {
        throw new BootstrapException('`drupal_root` parameter must be defined.');
      }

      foreach ($version_constant_paths as $path) {
        if (file_exists($this->drupalRoot . $path)) {
          require_once $this->drupalRoot . $path;
        }
      }
      if (defined('VERSION')) {
        $version = VERSION;
      }
      elseif (defined('\Drupal::VERSION')) {
        $version = \Drupal::VERSION;
      }
      else {
        throw new BootstrapException('Unable to determine Drupal core version. Supported versions are 6, 7, and 8.');
      }

      // Extract the major version from VERSION.
      $version_parts = explode('.', $version);
      if (is_numeric($version_parts[0])) {
        $this->drupalVersion = (integer) $version_parts[0];
      }
      else {
        throw new BootstrapException(sprintf('Unable to extract major Drupal core version from version string %s.', $version));
      }
    }
    return $this->drupalVersion;
  }

  /**
   * Instantiate and set Drupal core class.
   *
   * @param array $availableCores
   *   A major-version-keyed array of available core controllers.
   */
  public function setCore($availableCores) {
    if (!isset($availableCores[$this->version])) {
      throw new BootstrapException(sprintf('There is no available Drupal core controller for Drupal version %s.', $this->version));
    }
    $this->core = $availableCores[$this->version];
  }

  /**
   * Return current core.
   */
  public function getCore() {
    return $this->core;
  }

  /**
   * Implements DriverInterface::createNode().
   */
  public function createNode($node) {
    return $this->getCore()->nodeCreate($node);
  }

  /**
   * Implements CoreInterface::nodeDelete().
   */
  public function nodeDelete($node) {
    return $this->getCore()->nodeDelete($node);
  }

  /**
   * Implements DriverInterface::runCron().
   */
  public function runCron() {
    if (!$this->getCore()->runCron()) {
      throw new \Exception('Failed to run cron.');
    }
  }

  /**
   * Implements DriverInterface::createTerm().
   */
  public function createTerm(\stdClass $term) {
    return $this->getCore()->termCreate($term);
  }

  /**
   * Implements DriverInterface::termDelete().
   */
  public function termDelete(\stdClass $term) {
    return $this->getCore()->termDelete($term);
  }

  /**
   * Implements DriverInterface::roleCreate().
   */
  public function roleCreate(array $permissions) {
    return $this->getCore()->roleCreate($permissions);
  }

  /**
   * Implements DriverInterface::roleCreate().
   */
  public function roleDelete($rid) {
    $this->getCore()->roleDelete($rid);
  }

}


text: Auto-generated classes for `EXT_mesh_gpu_instancing`

redpajama_set_name: RedPajamaGithub


text:
package com.tlf.msg.admin.web.shiro;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("frameperms")
public class FramePermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
    public Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private CacheManager shiroCacheManager;

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response,
            Object mappedValue) throws IOException {
        Subject user = SecurityUtils.getSubject();
        ShiroUser shiroUser = (ShiroUser) user.getPrincipal();

        HttpServletRequest req = (HttpServletRequest) request;
        Subject subject = getSubject(request, response);
        String uri = req.getRequestURI();
        // String requestURL = req.getRequestURL().toString();
        String contextPath = req.getContextPath();
        if (uri.endsWith("/pre")) {
            uri = uri.substring(0, uri.length() - 4);
        }
        int i = uri.indexOf(contextPath);
        if (i > -1) {
            uri = uri.substring(i + contextPath.length());
        }
        if (StringUtils.isBlank(uri)) {
            uri = "/";
        }
        boolean permitted = false;
        if ("/".equals(uri)) {
            permitted = true;
        } else {
            permitted = subject.isPermitted(uri);
        }
        return permitted;
    }
}


text:
function pfilters = mkpartfilters(filter, psize, num)
% Make part filters from a source filter.
%
% filter  source filter
% psize   size for parts
% num     number of parts to make

% interpolate source filter
filter2x = imresize(filter, 2, 'bicubic');
template = fspecial('average', psize);
alpha = 0.1;

% Initial part placement based on greedy location selection.
energy = sum(max(filter2x, 0).^2, 3);
for k = 1:num
  [x y] = placepart(energy, template);
  f = mkfilter(filter2x, template, x, y, alpha);

  pfilters(k).anchor = [x-1 y-1 1];
  pfilters(k).w = f;
  pfilters(k).alpha = alpha;

  % zero energy in source
  energy = zeroenergy(energy, x, y, template);
end

% sample part placements and pick the best energy covering
maxiter = 1000;
retries = 10;
bestcover = -inf;
best = [];
% retry from randomized starting points
for j = 1:retries
  tmp = pfilters;
  progress = ones(num,1);
  % relax:
  % remove a part at random and look for the best place to put it
  % continue until no more progress can be made (or maxiters)
  for k = 1:maxiter
    if sum(progress) == 0
      break;
    end
    energy = sum(max(filter2x, 0).^2, 3);
    p = ceil(num*rand(1));
    for i = 1:num
      if i ~= p
        energy = zeroenergy(energy, tmp(i).anchor(1)+1, ...
                                    tmp(i).anchor(2)+1, template);
      end
    end
    [x y] = placepart(energy, template);

    if tmp(p).anchor(1)+1 == x && tmp(p).anchor(2)+1 == y
      % new location equals old location
      progress(p) = 0;
      continue;
    end
    progress(p) = 1;

    f = mkfilter(filter2x, template, x, y, alpha);

    tmp(p).anchor = [x-1 y-1 1];
    tmp(p).w = f;
    tmp(p).alpha = alpha;
  end

  % compute the energy covered by this part arrangement
  covered = 0;
  energy = sum(max(filter2x, 0).^2, 3);
  for i = 1:num
    covered = covered + ...
              coveredenergy(energy, tmp(i).anchor(1)+1, ...
                                    tmp(i).anchor(2)+1, template);
    energy = zeroenergy(energy, tmp(i).anchor(1)+1, ...
                                tmp(i).anchor(2)+1, template);
  end
  % record best covering
  if covered > bestcover
    bestcover = covered;
    best = tmp;
  end
end
pfilters = best;

function [x y] = placepart(energy, template)

score = conv2(energy, template, 'valid');
score = padarray(score, [1 1], -inf, 'post');
[v, Y] = max(score);
[v, x] = max(v);
y = Y(x);

function f = mkfilter(w, template, x, y, alpha)

f = w(y:y+size(template,1)-1, x:x+size(template,2)-1, :);
f = max(f, 0);
f = alpha*f/norm(f(:));

function energy = zeroenergy(energy, x, y, template)

energy(y:y+size(template,1)-1, x:x+size(template,2)-1) = 0;

function covered = coveredenergy(energy, x, y, template)

e = energy(y:y+size(template,1)-1, x:x+size(template,2)-1);
covered = sum(e(:).^2);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="55dip"
        android:background="#8866ff00"
        android:gravity="center"
        android:text="程序管理"
        android:textColor="#000000"
        android:textSize="22sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/tv_avail_rom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="内存可用"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tv_avaul_sd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="SD卡可用"
            android:textColor="#000000" />
    </RelativeLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:id="@+id/ll_loading"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:visibility="invisible" >

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="正在加载。。。" />
        </LinearLayout>

        <ListView
            android:id="@+id/lv_app_manager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fastScrollEnabled="true" >
        </ListView>

        <TextView
            android:id="@+id/tv_status"
            android:text="用户程序:6个"
            android:textColor="#ffffff"
            android:background="#ff888888"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </FrameLayout>

</LinearLayout>


text:
<?php
/**
 * Helper functions for displaying a list of items in an ajaxified HTML table.
 *
 * @package WordPress
 * @subpackage List_Table
 * @since 3.1.0
 */

/**
 * Fetches an instance of a WP_List_Table class.
 *
 * @access private
 * @since 3.1.0
 *
 * @global string $hook_suffix
 *
 * @param string $class The type of the list table, which is the class name.
 * @param array  $args  Optional. Arguments to pass to the class. Accepts 'screen'.
 * @return WP_List_Table|bool List table object on success, false if the class does not exist.
 */
function _get_list_table( $class, $args = array() ) {
	$core_classes = array(
		// Site Admin.
		'WP_Posts_List_Table'                         => 'posts',
		'WP_Media_List_Table'                         => 'media',
		'WP_Terms_List_Table'                         => 'terms',
		'WP_Users_List_Table'                         => 'users',
		'WP_Comments_List_Table'                      => 'comments',
		'WP_Post_Comments_List_Table'                 => array( 'comments', 'post-comments' ),
		'WP_Links_List_Table'                         => 'links',
		'WP_Plugin_Install_List_Table'                => 'plugin-install',
		'WP_Themes_List_Table'                        => 'themes',
		'WP_Theme_Install_List_Table'                 => array( 'themes', 'theme-install' ),
		'WP_Plugins_List_Table'                       => 'plugins',

		// Network Admin.
		'WP_MS_Sites_List_Table'                      => 'ms-sites',
		'WP_MS_Users_List_Table'                      => 'ms-users',
		'WP_MS_Themes_List_Table'                     => 'ms-themes',

		// Privacy requests tables.
		'WP_Privacy_Data_Export_Requests_List_Table'  => 'privacy-data-export-requests',
		'WP_Privacy_Data_Removal_Requests_List_Table' => 'privacy-data-removal-requests',
	);

	if ( isset( $core_classes[ $class ] ) ) {
		foreach ( (array) $core_classes[ $class ] as $required ) {
			require_once ABSPATH . 'wp-admin/includes/class-wp-' . $required . '-list-table.php';
		}

		if ( isset( $args['screen'] ) ) {
			$args['screen'] = convert_to_screen( $args['screen'] );
		} elseif ( isset( $GLOBALS['hook_suffix'] ) ) {
			$args['screen'] = get_current_screen();
		} else {
			$args['screen'] = null;
		}

		return new $class( $args );
	}

	return false;
}

/**
 * Register column headers for a particular screen.
 *
 * @see get_column_headers(), print_column_headers(), get_hidden_columns()
 *
 * @since 2.7.0
 *
 * @param string  $screen   The handle for the screen to add help to. This is usually the hook name returned by the
 *                          add_*_page() functions.
 * @param string[] $columns An array of columns with column IDs as the keys and translated column names as the values.
 */
function register_column_headers( $screen, $columns ) {
	new _WP_List_Table_Compat( $screen, $columns );
}

/**
 * Prints column headers for a particular screen.
 *
 * @since 2.7.0
 *
 * @param string|WP_Screen $screen  The screen hook name or screen object.
 * @param bool             $with_id Whether to set the id attribute or not.
 */
function print_column_headers( $screen, $with_id = true ) {
	$wp_list_table = new _WP_List_Table_Compat( $screen );

	$wp_list_table->print_column_headers( $with_id );
}


text: module CabalBounds.Lenses where


text:
using System;
using SpiceSharp.Attributes;
using SpiceSharp.Behaviors;
using SpiceSharp.Simulations;

namespace SpiceSharp.Components.MosfetBehaviors.Level2
{
    /// <summary>
    /// Temperature behavior for a <see cref="Mosfet2"/>
    /// </summary>
    public class TemperatureBehavior : Behavior, ITemperatureBehavior
    {
        /// <summary>
        /// Gets the base parameters.
        /// </summary>
        protected BaseParameters BaseParameters { get; private set; }

        /// <summary>
        /// Gets the model parameters.
        /// </summary>
        protected ModelBaseParameters ModelParameters { get; private set; }

        /// <summary>
        /// Gets the model temperature behavior.
        /// </summary>
        protected ModelTemperatureBehavior ModelTemperature { get; private set; }

        /// <summary>
        /// Gets the source conductance.
        /// </summary>
        [ParameterName("sourceconductance"), ParameterInfo("Conductance at the source")]
        public double SourceConductance { get; private set; }

        /// <summary>
        /// Gets the drain conductance.
        /// </summary>
        [ParameterName("drainconductance"), ParameterInfo("Conductance at the drain")]
        public double DrainConductance { get; private set; }

        /// <summary>
        /// Gets the source resistance.
        /// </summary>
        [ParameterName("rs"), ParameterInfo("Source resistance")]
        public double SourceResistance
        {
            get
            {
                if (SourceConductance > 0.0)
                    return 1.0 / SourceConductance;
                return 0.0;
            }
        }

        /// <summary>
        /// Gets the drain resistance.
        /// </summary>
        [ParameterName("rd"), ParameterInfo("Drain conductance")]
        public double DrainResistance
        {
            get
            {
                if (DrainConductance > 0.0)
                    return 1.0 / DrainConductance;
                return 0.0;
            }
        }

        /// <summary>
        /// Gets or sets the critical source voltage.
        /// </summary>
        [ParameterName("sourcevcrit"), ParameterInfo("Critical source voltage")]
        public double SourceVCritical { get; protected set; }

        /// <summary>
        /// Gets or sets the critical drain voltage.
        /// </summary>
        [ParameterName("drainvcrit"), ParameterInfo("Critical drain voltage")]
        public double DrainVCritical { get; protected set; }

        /// <summary>
        /// Gets the temperature-modified surface mobility.
        /// </summary>
        protected double TempSurfaceMobility { get; private set; }

        /// <summary>
        /// Gets the temperature-modified phi.
        /// </summary>
        protected double TempPhi { get; private set; }

        /// <summary>
        /// Gets the temperature-modified Vbi.
        /// </summary>
        protected double TempVoltageBi { get; private set; }

        /// <summary>
        /// Gets the temperature-modified bulk potential.
        /// </summary>
        protected double TempBulkPotential { get; private set; }

        /// <summary>
        /// Gets the temperature-modified transconductance.
        /// </summary>
        protected double TempTransconductance { get; private set; }

        /// <summary>
        /// Gets the temperature-modified threshold voltage.
        /// </summary>
        protected double TempVt0 { get; private set; }

        /// <summary>
        /// Gets the thermal voltage.
        /// </summary>
        protected double Vt { get; private set; }

        /// <summary>
        /// Gets the temperature-modified drain saturation current.
        /// </summary>
        protected double DrainSatCurrent { get; private set; }

        /// <summary>
        /// Gets the temperature-modified source saturation current.
        /// </summary>
        protected double SourceSatCurrent { get; private set; }

        /// <summary>
        /// Gets the state.
        /// </summary>
        protected BaseSimulationState State { get; private set; }

        /// <summary>
        /// Creates a new instance of the <see cref="TemperatureBehavior"/> class.
        /// </summary>
        /// <param name="name">Name</param>
        public TemperatureBehavior(string name) : base(name)
        {
        }

        /// <summary>
        /// Bind the behavior. for the specified simulation.
        /// </summary>
        /// <param name="simulation">The simulation.</param>
        /// <param name="context">The context.</param>
        public override void Bind(Simulation simulation, BindingContext context)
        {
            base.Bind(simulation, context);

            // Get parameters
            BaseParameters = context.GetParameterSet<BaseParameters>();
            ModelParameters = context.GetParameterSet<ModelBaseParameters>("model");

            // Get behaviors
            ModelTemperature = context.GetBehavior<ModelTemperatureBehavior>("model");

            State = ((BaseSimulation)simulation).RealState;
        }

        /// <summary>
        /// Unbind the behavior.
        /// </summary>
        public override void Unbind()
        {
            base.Unbind();

            State = null;
        }

        /// <summary>
        /// Perform temperature-dependent calculations.
        /// </summary>
        void ITemperatureBehavior.Temperature()
        {
            // Update the width and length if they are not given and if the model specifies them
            if (!BaseParameters.Width.Given && ModelParameters.Width.Given)
                BaseParameters.Width.RawValue = ModelParameters.Width.Value;
            if (!BaseParameters.Length.Given && ModelParameters.Length.Given)
                BaseParameters.Length.RawValue = ModelParameters.Length.Value;

            if (!BaseParameters.Temperature.Given)
                BaseParameters.Temperature.RawValue = State.ThrowIfNotBound(this).Temperature;
            Vt = BaseParameters.Temperature * Constants.KOverQ;
            var ratio = BaseParameters.Temperature / ModelParameters.NominalTemperature;
            var fact2 = BaseParameters.Temperature / Constants.ReferenceTemperature;
            var kt = BaseParameters.Temperature * Constants.Boltzmann;
            var egfet = 1.16 - 7.02e-4 * BaseParameters.Temperature * BaseParameters.Temperature / (BaseParameters.Temperature + 1108);
            var arg = -egfet / (kt + kt) + 1.1150877 / (Constants.Boltzmann * (Constants.ReferenceTemperature + Constants.ReferenceTemperature));
            var pbfact = -2 * Vt * (1.5 * Math.Log(fact2) + Constants.Charge * arg);

            if (ModelParameters.DrainResistance.Given)
            {
                if (!ModelParameters.DrainResistance.Value.Equals(0.0))
                    DrainConductance = 1 / ModelParameters.DrainResistance;
                else
                    DrainConductance = 0;
            }
            else if (ModelParameters.SheetResistance.Given)
            {
                if (!ModelParameters.SheetResistance.Value.Equals(0.0))
                    DrainConductance = 1 / (ModelParameters.SheetResistance * BaseParameters.DrainSquares);
                else
                    DrainConductance = 0;
            }
            else
                DrainConductance = 0;
            if (ModelParameters.SourceResistance.Given)
            {
                if (!ModelParameters.SourceResistance.Value.Equals(0.0))
                    SourceConductance = 1 / ModelParameters.SourceResistance;
                else
                    SourceConductance = 0;
            }
            else if (ModelParameters.SheetResistance.Given)
            {
                if (!ModelParameters.SheetResistance.Value.Equals(0.0))
                    SourceConductance = 1 / (ModelParameters.SheetResistance * BaseParameters.SourceSquares);
                else
                    SourceConductance = 0;
            }
            else
                SourceConductance = 0;

            if (BaseParameters.Length - 2 * ModelParameters.LateralDiffusion <= 0)
                CircuitWarning.Warning(this, "{0}: effective channel length less than zero".FormatString(Name));
            var ratio4 = ratio * Math.Sqrt(ratio);
            TempTransconductance = ModelParameters.Transconductance / ratio4;
            TempSurfaceMobility = ModelParameters.SurfaceMobility / ratio4;
            var phio = (ModelParameters.Phi - ModelTemperature.PbFactor1) / ModelTemperature.Factor1;
            TempPhi = fact2 * phio + pbfact;
            TempVoltageBi = ModelParameters.Vt0 - ModelParameters.MosfetType * (ModelParameters.Gamma * Math.Sqrt(ModelParameters.Phi)) + .5 * (ModelTemperature.EgFet1 - egfet) +
                ModelParameters.MosfetType * .5 * (TempPhi - ModelParameters.Phi);
            TempVt0 = TempVoltageBi + ModelParameters.MosfetType * ModelParameters.Gamma * Math.Sqrt(TempPhi);
            var tempSaturationCurrent = ModelParameters.JunctionSatCur * Math.Exp(-egfet / Vt + ModelTemperature.EgFet1 / ModelTemperature.VtNominal);
            var tempSaturationCurrentDensity = ModelParameters.JunctionSatCurDensity * Math.Exp(-egfet / Vt + ModelTemperature.EgFet1 / ModelTemperature.VtNominal);
            var pbo = (ModelParameters.BulkJunctionPotential - ModelTemperature.PbFactor1) / ModelTemperature.Factor1;
            TempBulkPotential = fact2 * pbo + pbfact;

            if (tempSaturationCurrentDensity <= 0 || BaseParameters.DrainArea.Value <= 0 || BaseParameters.SourceArea.Value <= 0)
            {
                SourceVCritical = DrainVCritical = Vt * Math.Log(Vt / (Constants.Root2 * tempSaturationCurrent));
            }
            else
            {
                DrainVCritical = Vt * Math.Log(Vt / (Constants.Root2 * tempSaturationCurrentDensity * BaseParameters.DrainArea));
                SourceVCritical = Vt * Math.Log(Vt / (Constants.Root2 * tempSaturationCurrentDensity * BaseParameters.SourceArea));
            }

            if (tempSaturationCurrentDensity.Equals(0) || BaseParameters.DrainArea.Value <= 0 || BaseParameters.SourceArea.Value <= 0)
            {
                DrainSatCurrent = tempSaturationCurrent;
                SourceSatCurrent = tempSaturationCurrent;
            }
            else
            {
                DrainSatCurrent = tempSaturationCurrentDensity * BaseParameters.DrainArea;
                SourceSatCurrent = tempSaturationCurrentDensity * BaseParameters.SourceArea;
            }
        }
    }
}


text:
import logging
import os.path
import yaml
from kpm.manifest import ManifestBase

__all__ = ['ManifestChart']
logger = logging.getLogger(__name__)

MANIFEST_FILES = ["Chart.yaml", "Chart.yml"]

class ManifestChart(ManifestBase):

    def __init__(self, package=None, values=None):
        self.values = values
        if package is None:
            self._load_from_path()
        else:
            self._load_yaml(package.manifest)

    def _load_yaml(self, yamlstr):
        try:
            self.update(yaml.load(yamlstr))
        except yaml.YAMLError, exc:
            print "Error in configuration file:"
            if hasattr(exc, 'problem_mark'):
                mark = exc.problem_mark
                print "Error position: (%s:%s)" % (mark.line + 1, mark.column + 1)
            raise exc

    def _load_from_path(self):
        for f in MANIFEST_FILES:
            if os.path.exists(f):
                mfile = f
                break
        with open(mfile) as f:
            self._load_yaml(f.read())

    @property
    def keywords(self):
        return self.get("keywords", [])

    @property
    def engine(self):
        return self.get("engine", "gotpl")

    @property
    def home(self):
        return self.get("home", "")

    @property
    def description(self):
        return self.get("description", "")

    @property
    def version(self):
        return self.get("version", "")

    @property
    def maintainers(self):
        return self.get("maintainers", [])

    @property
    def sources(self):
        return self.get("sources", [])

    @property
    def name(self):
        return self.get("name", [])

    def metadata(self):
        return {"maintainers": self.maintainers, "source": self.sources}


text:
{%- if posts %}

{%- for post in posts %}

        {% if post.published_date %}${localize:(.now - post.published_date)} ago{% endif %}
        {% if .user and post.published and (.user.previous_login is None or .user.previous_login lt post.published_date) %}
        new!
        {% endif %}

${post.title}

        {% if post.type == 'photo' %}
        {% include "photo_fan.html" %}
        {% endif %}

{%- endfor %}

{%- endif %}


text:
// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/runtime.h"

#include <algorithm>
#include <chrono>
#include <string.h>
#include <thread>
#include <unordered_map>

#include <boost/asio/io_context.hpp>
#include <include/libplatform/libplatform.h>

#include "base/logging.h"
#include "base/time.h"
#include "bindings/exception_handler.h"
#include "bindings/frame_observer.h"
#include "bindings/global_scope.h"
#include "bindings/modules/streamer/streamer_host.h"
#include "bindings/runtime_modulator.h"
#include "bindings/timer_queue.h"
#include "bindings/utilities.h"

namespace bindings {

namespace {

// Context extensions that should be enabled on our v8 scope.
const int kContextExtensionCount = 1;
const char* kContextExtensions[] = {
  "v8/statistics",
};

// Map of v8 Isolates to the associated Runtime instances (weak references).
std::unordered_map<v8::Isolate*, std::weak_ptr<Runtime>> g_runtime_instances_;

// String of the v8 flags that should apply to this virtual machine. See flag-definitions.h in
// the v8 source code for a list of all supported command line flags.
const char kRuntimeFlags[] =
    "--expose_gc "
    "--use_strict "

    // Private methods and weak references
    "--harmony_intl_dateformat_day_period "
    "--harmony_intl_segmenter";

// Returns whether |character| represents a line break.
bool IsLineBreak(char character) {
  return character == '\n' || character == '\r';
}

// Returns a string with all line breaks removed from |line|.
std::string RemoveLineBreaks(std::string line) {
  line.erase(std::remove_if(line.begin(), line.end(), IsLineBreak), line.end());
  return line;
}

// Callback for the v8 message handler. Forward the call to the exception handler.
void MessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> error) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime) {
    runtime->GetExceptionHandler()->OnMessage(
      message, error, ExceptionHandler::MessageSource::kScript);
  }
}

// Callback for the v8 fatal error handler. Forward the call to the exception handler.
void FatalErrorCallback(const char* location, const char* message) {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    runtime->GetExceptionHandler()->OnFatalError(location, message);
}

// Callback for uncaught promise rejection events. Output the exception message to the console
// after all, so that developers can pick up on the error and deal with it.
void PromiseRejectCallback(v8::PromiseRejectMessage message) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(isolate);
  if (!runtime)
    return;

  auto promise = message.GetPromise();
  auto value = message.GetValue();

  if (message.GetEvent() == v8::kPromiseHandlerAddedAfterReject) {
    runtime->GetExceptionHandler()->RevokeQueuedMessages(promise);
    return;
  }

  v8::Local<v8::Message> error_message = v8::Exception::CreateMessage(isolate, value);
  if (error_message.IsEmpty())
    return;

  runtime->GetExceptionHandler()->OnMessage(
      error_message, value, ExceptionHandler::MessageSource::kRejectedPromise, promise);
}

}  // namespace

// Declared in utilities.h
v8::Local<v8::Context> GetContext() {
  std::shared_ptr<Runtime> runtime = Runtime::FromIsolate(v8::Isolate::GetCurrent());
  if (runtime)
    return runtime->context();

  return v8::Local<v8::Context>();
}

// static
std::shared_ptr<Runtime> Runtime::FromIsolate(v8::Isolate* isolate) {
  const auto instance = g_runtime_instances_.find(isolate);
  if (instance == g_runtime_instances_.end())
    return nullptr;

  CHECK(!instance->second.expired());
  return instance->second.lock();
}

// static
std::shared_ptr<Runtime> Runtime::Create(Delegate* runtime_delegate,
                                         plugin::PluginController* plugin_controller) {
  auto instance = std::shared_ptr<Runtime>(
      new Runtime(runtime_delegate, plugin_controller));
  CHECK(instance->isolate());

  g_runtime_instances_[instance->isolate()] = instance;
  return instance;
}

Runtime::Runtime(Delegate* runtime_delegate,
                 plugin::PluginController* plugin_controller)
    : global_scope_(new GlobalScope(plugin_controller)),
      runtime_delegate_(runtime_delegate),
      platform_(v8::platform::NewDefaultPlatform()),
      main_thread_io_context_(),
      background_io_context_(),
      background_thread_guard_(boost::asio::make_work_guard(background_io_context_)),
      background_thread_(std::make_unique<boost::thread>(boost::bind(&boost::asio::io_context::run,
                                                                     &background_io_context_))),
      is_ready_(false),
      frame_counter_start_(::base::monotonicallyIncreasingTime()),
      frame_counter_(0) {
  v8::V8::InitializeICU("icudtl.dat");
  v8::V8::InitializePlatform(platform_.get());
  v8::V8::SetFlagsFromString(kRuntimeFlags, sizeof(kRuntimeFlags));
  v8::V8::Initialize();

  allocator_.reset(v8::ArrayBuffer::Allocator::NewDefaultAllocator());

  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = allocator_.get();

  isolate_ = v8::Isolate::New(create_params);
  isolate_scope_.reset(new v8::Isolate::Scope(isolate_));

  exception_handler_.reset(new ExceptionHandler(this, runtime_delegate_));
  isolate_->SetCaptureStackTraceForUncaughtExceptions(true, 15);
  isolate_->AddMessageListener(MessageCallback);
  isolate_->SetFatalErrorHandler(FatalErrorCallback);
  isolate_->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  isolate_->SetPromiseRejectCallback(PromiseRejectCallback);
  isolate_->SetHostImportModuleDynamicallyCallback(
      &RuntimeModulator::ImportModuleDynamicallyCallback);

  timer_queue_.reset(new TimerQueue(this));

  streamer_host_ = std::make_unique<streamer::StreamerHost>(
      plugin_controller, main_thread_io_context_, background_io_context_);

  source_directory_ = base::FilePath::CurrentDirectory().Append("javascript");
}

Runtime::~Runtime() {
  background_thread_guard_.reset();

  global_scope_.reset();
  timer_queue_.reset();
  modulator_.reset();

  isolate_scope_.reset();
  isolate_->Dispose();

  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();
}

void Runtime::Initialize() {
  v8::HandleScope handle_scope(isolate_);

  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_);

  // The global scope is being applied in two steps. First we install all the prototypes (which
  // essentially are functions that may be instantiated), then we install objects, which may
  // include instantiations of previously installed prototypes (e.g. the console global).
  global_scope_->InstallPrototypes(global);

  v8::ExtensionConfiguration configuration(kContextExtensionCount, kContextExtensions);
  v8::Local<v8::Context> context = v8::Context::New(isolate_, &configuration, global);

  v8::Context::Scope context_scope(context);
  global_scope_->InstallObjects(context);
  global_scope_->Finalize();

  context_.Reset(isolate_, context);

  modulator_.reset(new RuntimeModulator(isolate_, source_directory_));
  modulator_->LoadModule(context, /* referrer= */ base::FilePath(), "main.js");
}

void Runtime::SpinUntilReady() {
  while (!is_ready_) {
    std::this_thread::sleep_for(std::chrono::microseconds(500));
    OnFrame();
  }
}

void Runtime::SetReady() {
  is_ready_ = true;
}

void Runtime::GetAndResetFrameCounter(double* duration, double* average_fps) {
  DCHECK(duration && average_fps);

  double current = ::base::monotonicallyIncreasingTime();

  *duration = current - frame_counter_start_;
  *average_fps = frame_counter_ / (*duration / 1000);

  frame_counter_start_ = current;
  frame_counter_ = 0;
}

void Runtime::OnFrame() {
  ++frame_counter_;

  double current_time = ::base::monotonicallyIncreasingTime();

  for (FrameObserver* observer : frame_observers_)
    observer->OnFrame();

  timer_queue_->Run(current_time);

  isolate_->RunMicrotasks();

  if (main_thread_io_context_.stopped())
    main_thread_io_context_.restart();

  main_thread_io_context_.run_one();

  streamer_host_->OnFrame(current_time);

  if (exception_handler_->HasQueuedMessages()) {
    v8::HandleScope handle_scope(isolate_);
    v8::Context::Scope context_scope(context());

    exception_handler_->FlushMessageQueue();
  }
}

void Runtime::AddFrameObserver(FrameObserver* observer) {
  frame_observers_.insert(observer);
}

void Runtime::RemoveFrameObserver(FrameObserver* observer) {
  frame_observers_.erase(observer);
}

}  // namespace bindings


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MorseL.Diagnostics;
using MorseL.Sockets.Middleware;
using Nito.AsyncEx.Synchronous;
using MorseL.Common;
using MorseL.Sockets.Extensions;
using MorseL.Common.WebSockets.Exceptions;

namespace MorseL.Sockets
{
    /// <summary>
    /// <para>Flow of Request</para>
    /// <para>
    /// HTTP Request comes into server (kestrel) and gets passed through HTTP middleware
    /// added to <see cref="Invoke(HttpContext)"/>. The request gets checked for a valid
    /// websocket and ignored by <see cref="MorseLHttpMiddleware"/> if one is not present.
    /// </para>
    /// <para>
    /// Afterwards, a <see cref="WebSocketHandler"/> is created to manage the life of the
    /// websocket. The websocket is accepted and passed to
    /// <see cref="WebSocketHandler.OnConnected(WebSocket, HttpContext)"/> to initiate
    /// the websockets connection. The receive loop is then started on the websocket,
    /// looping and calling
    /// <see cref="WebSocket.ReceiveAsync(ArraySegment{byte}, CancellationToken)"/> to grab
    /// the next data packet.
    /// </para>
    /// <para>
    /// Each received data packet is checked for a text message or a close message. In the
    /// event of a close packet,
    /// <see cref="WebSocketHandler.OnDisconnected(WebSocket, Exception)"/> is called,
    /// otherwise <see cref="WebSocketHandler.ReceiveAsync(Connection, string)"/> is passed
    /// the data packet to handle the incoming packet.
    /// </para>
    /// <para>Exceptions</para>
    /// <para>
    /// Each inbound request marks its own long-running execution flow. The request lasts
    /// for as long as the web socket is connected and thus exceptions can be thrown and
    /// observed through out the entire process.
    /// </para>
    /// </summary>
    public class MorseLHttpMiddleware
    {
        private readonly ILogger _logger;
        private readonly RequestDelegate _next;

        private Type HandlerType { get; }

        public MorseLHttpMiddleware(
            ILogger<MorseLHttpMiddleware> logger, RequestDelegate next, Type handlerType)
        {
            _logger = logger;
            _next = next;
            HandlerType = handlerType;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next(context);
                return;
            }

            var cts = new CancellationTokenSource();
            Exception pendingException = null;

            using (var serviceScope = context.RequestServices.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                var middleware = services.GetServices<IMiddleware>().ToList();

                var handler = ActivatorUtilities.CreateInstance(services, HandlerType) as WebSocketHandler;
                if (handler == null)
                {
                    throw new Exception("Invalid handler type specified. Must be a Hub.");
                }

                var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);

                try
                {
                    // TODO : Consider/Decide on pulling web socket manager outside of handler
                    var connection = await handler.OnConnected(socket, context).ConfigureAwait(false);

                    await Receive(socket, connection, middleware, cts,
                        async (stream) =>
                        {
                            string serializedInvocationDescriptor;

                            try
                            {
                                using (var reader = new StreamReader(stream, new UTF8Encoding(), true, 8192, false))
                                {
                                    serializedInvocationDescriptor = await reader.ReadToEndAsync().ConfigureAwait(false);
                                }
                            }
                            catch (WebSocketClosedException e)
                            {
                                await handler.OnDisconnected(socket, null);
                                return;
                            }

                            // We call the connection arg'd method directly to allow for middleware to override the IChannel
                            var unawaitedTask = Task.Run(async () =>
                            {
                                try
                                {
                                    await handler.ReceiveAsync(connection, serializedInvocationDescriptor).ConfigureAwait(false);
                                }
                                catch (Exception exception)
                                {
                                    // An exception here means it was thrown during message handling (not in the Hub method itself)
                                    // This is a big issue (likely message serialization) and can't be "saved"
                                    // We'll store the exception and rethrow after the receive loop is brought down
                                    pendingException = exception;
                                    cts.Cancel();
                                }
                            }).ConfigureAwait(false);
                        }).ConfigureAwait(false);

                    // Rethrow any exception thrown during message processing that broke our receive loop
                    if (pendingException != null)
                    {
                        ExceptionDispatchInfo.Capture(pendingException).Throw();
                    }
                }
                catch (Exception exception)
                {
                    if (pendingException == null || pendingException != exception)
                    {
                        pendingException = exception;
                    }

                    _logger?.LogError(new EventId(), exception, "Exception thrown during receive loop");

                    if (exception is MorseLException)
                    {
                        // For now, rethrow morsel exceptions
                        throw;
                    }
                }
                finally
                {
                    try
                    {
                        await handler.OnDisconnected(socket, pendingException);
                    }
                    catch (WebSocketException webSocketException)
                    {
                        _logger?.LogWarning(new EventId(), webSocketException, "Exception attempting to close socket");
                    }

                    cts.Dispose();
                }
            }
        }

        private async Task Receive(
            WebSocket socket, Connection connection, List<IMiddleware> middleware,
            CancellationTokenSource cts, Func<Stream, Task> handleMessage)
        {
            using (var receiveCts = new CancellationTokenSource())
            {
                cts.Token.Register(() =>
                {
                    _logger?.LogDebug("Global CTS received cancellation; attempting best effort closure of socket");

                    // If we were told to die - let's attempt a best effort closure
                    // to our connected web socket. This covers the case where we
                    // are manually killing the connection because of a MorseL protocol
                    // error. The web socket is still valid, in these cases, so we can
                    // close normally so the socket knows about it.
                    try
                    {
                        using (var timeoutCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(250)))
                        {
                            socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, timeoutCts.Token);
                        }
                    }
                    // Best effort closure - if an exception is thrown we don't really care
                    catch (Exception e)
                    {
                        _logger?.LogWarning(new EventId(), e, "Received error attempting to respectfully close socket");
                    }

                    // Now kill the receiveCts
                    receiveCts.Cancel();
                });

                while (socket.State == WebSocketState.Open)
                {
                    using (var stream = socket.GetReadStream())
                    {
                        try
                        {
                            await stream.WaitForDataAsync();
                        }
                        catch (WebSocketClosedException e)
                        {
                            // Squelch this exception as we likely received a separate
                            // exception preceeding this one.
                            // But, we don't want to read anymore if we're closed
                            break;
                        }

                        var context = new ConnectionContext(connection, stream);
                        var iterator = middleware.GetEnumerator();
                        var delegator = BuildMiddlewareDelegate(iterator, handleMessage);

                        await delegator
                            .Invoke(context)
                            .ContinueWith(task =>
                            {
                                iterator.Dispose();

                                task.WaitAndUnwrapException();
                            })
                            .ConfigureAwait(false);
                    }
                }
            }
        }

        internal MiddlewareDelegate BuildMiddlewareDelegate(List<IMiddleware>.Enumerator iterator, Func<Stream, Task> handleMessage)
        {
            MiddlewareDelegate delegator = null;
            delegator = async tranformedContext =>
            {
                if (iterator.MoveNext())
                {
                    using (_logger?.Tracer($"Middleware[{iterator.Current.GetType()}].ReceiveAsync(...)"))
                    {
                        await iterator.Current.ReceiveAsync(tranformedContext, delegator).ConfigureAwait(false);
                    }
                }
                else
                {
                    using (_logger?.Tracer("Receive.handleMessage(...)"))
                    {
                        await handleMessage(tranformedContext.Stream);
                    }
                }
            };

            return delegator;
        }
    }
}


text:
var n = 1;

var HalResource = Backbone.RelationalHalResource = RelationalModel.extend({

  initialize: function(attrs, options) {

    this.halEmbeddedId = n++;

    if (this.has('_embedded') && !this.get('_embedded').id) {
      this.get('_embedded').set({ id: this.halEmbeddedId }, { silent: true });
    }

    _.extend(this, _.pick(options || {}, 'halUrlTemplate'));

    this.initializeResource.apply(this, arguments);
  },

  initializeResource: function() {},

  parse: function(response) {

    if (response._embedded) {
      response._embedded.id = this.halEmbeddedId;
    }

    return response;
  },

  url: function() {

    if (this.hasLink('self')) {

      var options = {};
      if (this.halUrlTemplate) {
        options.template = _.result(this, 'halUrlTemplate');
      }

      return this.link('self').href(options);
    } else if (this._cachedHalUrl) {
      return this._cachedHalUrl;
    }

    var halUrl = _.result(this, 'halUrl');
    if (halUrl) {
      $.when(halUrl).then(_.bind(function(url) {
        this._cachedHalUrl = url;
      }, this));
    }

    return halUrl || null;
  },

  link: function(rel) {
    var links = this.get('_links');
    return links ? links.link.apply(links, Array.prototype.slice.call(arguments)) : null;
  },

  hasLink: function(rel) {
    return this.has('_links') && this.get('_links').has(rel);
  },

  fetchHalUrl: function(rels) {
    return this._fetchResource(rels.slice(), $.Deferred(), 'url', this);
  },

  fetchResource: function(rels) {
    return this._fetchResource(rels.slice(), $.Deferred(), 'resource', this);
  },

  _fetchResource: function(rels, deferred, fetchType, resource, response, options) {
    if (!rels.length) {
      return deferred.resolve(resource, response, options);
    }

    var relName = rels.shift(),
        rel = _.isObject(relName) ? relName : { name: relName },
        link = resource.link(rel.name);

    if (fetchType == 'url' && !rels.length) {
      return deferred.resolve(link.href(_.omit(rel, 'name')), resource, response, options);
    }

    link.fetchResource({
      model: rel.model || (rel.name == 'self' ? this : null),
      type: rel.type,
      fetch: {
        error: _.bind(deferred.reject, deferred),
        success: _.bind(this._fetchResource, this, rels, deferred, fetchType)
      }
    });

    return deferred;
  },

  embedded: function(rel) {
    var embedded = this.get('_embedded');
    return embedded ? embedded.embedded.apply(embedded, Array.prototype.slice.call(arguments)) : null;
  },

  hasEmbedded: function(rel) {
    return this.has('_embedded') && this.get('_embedded').has(rel);
  },

  hasSameUri: function(other) {
    if (!other) {
      return false;
    }

    return this.link('self').href() == other.link('self').href();
  },

  isNew: function() {
    return !this.hasLink('self');
  }
});


text:
from __future__ import print_function
import numpy as np
import time, warnings
import itertools
import scipy
from scipy.stats import binned_statistic as binnedstat,chi2
from scipy.optimize import curve_fit
import itertools
from pyfisher import FisherMatrix

def get_pte(chisquare_data,chisquares_sims):
    return chisquares_sims[chisquare_data<chisquares_sims].size / chisquares_sims.size

# Get PTE from samples drawn from a covariance matrix
def sim_pte(data,covmat,nsamples):
    cinv = np.linalg.inv(covmat)
    chisquare = np.dot(data,np.dot(cinv,data))
    samples = np.random.multivariate_normal(data*0,covmat,nsamples)
    chisquares = np.einsum('ik,ik->i', np.einsum('ij,jk->ik',samples,cinv),samples)
    pte = get_pte(chisquare,chisquares)
    return pte

class InverseTransformSampling(object):
    # Sample from an arbitrary 1d PDF
    def __init__(self,xvals,pdf_vals):
        from scipy.interpolate import interp1d

        # spacing between x-values
        dxs = np.diff(xvals)
        if not( np.all(np.isclose(dxs,dxs[0])) ):
            # It might not have to be, but I haven't tested beyond equi-spaced.
            raise Exception("The PDF domain has to be equi-spaced.")

        # Normalize
        norm = np.trapz(pdf_vals,xvals)
        self.xs = xvals
        self.pdf = pdf_vals/norm

        # CDF
        self.cdf = np.cumsum(self.pdf)*dxs[0]
        # Make it sensible. The discreteness will make the behaviour in
        # the tails not quite right.
        self.cdf[0] = 0
        self.cdf[self.cdf>1] = 1
        if not(np.all(self.cdf>=0)): raise Exception
        if not(np.all(self.cdf<=1)): raise Exception
        # inverse CDF
        self.icdf = interp1d(self.cdf,self.xs,bounds_error=False)

    def generate(self,nsamples):
        # CDF^{-1} ( U(0,1) )
        return self.icdf(np.random.uniform(0,1,size=nsamples))

class InverseTransformSampling2D(object):
    # Sample from an arbitrary 2d PDF
    def __init__(self,ys,xs,updf,bounds_error=False):
        self.ys = ys

        # Normalize PDF p(y,x)
        norm = np.trapz(np.trapz(updf,xs),ys)
        pdf = updf / norm
        self.pdf = pdf

        # Marginal PDF p(y)
        mpdf_y = np.trapz(pdf,xs)
        # Prepare to sample from p(y)
        self.its = InverseTransformSampling(ys,mpdf_y)

        # Conditional density p(x | y)
        cpdf = (pdf.T / mpdf_y).T

        # Prepare to sample from p(x | y) for all y
        self.allits = []
        for i in range(len(ys)):
            self.allits.append(InverseTransformSampling(xs,cpdf[i,:]) )

    def generate(self,nsamples):
        # Sample from p(y)
        ysamples = np.asarray(self.its.generate(nsamples))
        # Find index in ys corresponding to sampled y
        # and sample x from corresponding p(x | y)
        diff = np.abs(self.ys-ysamples[:,None])
        inds = np.argmin(diff,axis=1)
        xsamples = np.asarray([self.allits[ind].generate(1)[0] for ind in inds])
        return ysamples,xsamples

def eig_analyze(cmb2d,start=0,eigfunc=np.linalg.eigh,plot_file=None):
    es = eigfunc(cmb2d[start:,start:,...].T)[0]
    print(start,es.min(),np.any(es<0.))
    numw = range(np.prod(es.shape[:-1]))
    pl = io.Plotter(xlabel='n',ylabel='e',yscale='log')
    for ind in range(es.shape[-1]):
        pl.add(numw,np.sort(np.real(es[...,ind].ravel())))
        pl.add(numw,np.sort(np.imag(es[...,ind].ravel())),ls="--")
    pl.done(plot_file)

def get_sigma2(ells,cls,w0,delta_ells,fsky,ell0=0,alpha=1,w0p=None,ell0p=0,alphap=1,clxx=None,clyy=None):
    afact = ((ell0/ells)**(-alpha)) if ell0>1.e-3 else 0.*ells
    nlxx = (w0*np.pi/180./60.)**2 * afact
    if clxx is not None:
        afact = ((ell0p/ells)**(-alphap)) if ell0>1.e-3 else 0.*ells
        nlyy = (w0p*np.pi/180./60.)**2 * afact
        tclxx = clxx + nlxx
        tclyy = clyy + nlyy
        tcl2 = cls**2 + tclxx*tclyy
    else:
        assert clyy is None
        assert w0p is None
        tcl2 = 2 * (cls+nlxx)**2
    return tcl2/(2*ells+1)/fsky/delta_ells

def fit_cltt_power(ells,cls,cltt_func,w0,sigma2,ell0=0,alpha=1,fix_knee=False):
    """
    Fit binned power spectra to a linear model of the form
    A * C_ell + B * w0^2 (ell/ell0)^alpha + C * w0^2
    """
    # Cinv = np.diag(1./sigma2)
    # Cov = np.diag(sigma2)
    sw0 = w0 * np.pi / 180./ 60.
    if fix_knee:
        funcs = [lambda x: sw0**2]
    else:
        funcs = [lambda x: sw0**2, lambda x: sw0**2 * (ell0/x)**(-alpha) if ell0>1e-3 else sw0**2 ]
    bds = (0,np.inf)
    X,_ = curve_fit(lambda x,*args: sum([arg*f(x) for f,arg in zip(funcs,args) ]) , ells, (cls-cltt_func(ells)),
                  p0=[1] if fix_knee else [1,ell0],sigma=np.sqrt(sigma2),absolute_sigma=True,
                  bounds=bds)
    #X,_,_,_ = fit_linear_model(ells,(cls-cltt_func(ells)),Cov,funcs,Cinv=Cinv) # Linear models dont allow bounds
    return lambda x : cltt_func(x) + sum([ coeff*f(x)  for coeff,f in zip(X,funcs)])

def fit_linear_model(x,y,ycov,funcs,dofs=None,deproject=False,Cinv=None,Cy=None):
    """
    Given measurements with known uncertainties, this function fits those to a linear model:
    y = a0*funcs[0](x) + a1*funcs[1](x) + ...
    and returns the best fit coefficients a0,a1,... and their uncertainties as a covariance matrix
    """
    s = solve if deproject else np.linalg.solve
    C = ycov
    y = y[:,None]
    A = np.zeros((y.size,len(funcs)))
    for i,func in enumerate(funcs):
        A[:,i] = func(x)
    CA = s(C,A) if Cinv is None else np.dot(Cinv,A)
    cov = np.linalg.inv(np.dot(A.T,CA))
    if Cy is None: Cy = s(C,y) if Cinv is None else np.dot(Cinv,y)
    b = np.dot(A.T,Cy)
    X = np.dot(cov,b)
    YAX = y - np.dot(A,X)
    CYAX = s(C,YAX) if Cinv is None else np.dot(Cinv,YAX)
    chisquare = np.dot(YAX.T,CYAX)
    dofs = len(x)-len(funcs) if dofs is None else dofs
    pte = 1 - chi2.cdf(chisquare, dofs)
    return X,cov,chisquare/dofs,pte

def fit_linear_model_pte_from_sims(x,y,ycov,funcs,y_fiducial,nsims=100000,deproject=False,Cinv=None,Cy=None):
    X_data,cov_data,chisquare_data,_ = fit_linear_model(x,y,ycov,funcs,dofs=None,deproject=False)
    samples = y_fiducial + np.random.multivariate_normal(y_fiducial*0,ycov,nsims)
    chisquares_sims = []
    for i in range(nsims):
        _,_,chisq,_ = fit_linear_model(x,samples[i],ycov,funcs,dofs=None,deproject=deproject,Cinv=Cinv,Cy=Cy)
        chisquares_sims.append(chisq)
    chisquares_sims = np.asarray(chisquares_sims)
    pte = get_pte(chisquare_data,chisquares_sims)
    return X_data,cov_data,chisquare_data,pte

def fit_gauss(x,y,mu_guess=None,sigma_guess=None):
    ynorm = np.trapz(y,x)
    ynormalized = y/ynorm
    gaussian = lambda t,mu,sigma: np.exp(-(t-mu)**2./2./sigma**2.)/np.sqrt(2.*np.pi*sigma**2.)
    popt,pcov = curve_fit(gaussian,x,ynormalized,p0=[mu_guess,sigma_guess])#,bounds=([-np.inf,0],[np.inf,np.inf]))
    fit_mean = popt[0]
    fit_sigma = popt[1]
    return fit_mean,np.abs(fit_sigma),ynorm,ynormalized

class Solver(object):
    """
    Calculate Cinv . x
    """
    def __init__(self,C,u=None):
        """
        C is an (NxN) covariance matrix
        u is an (Nxk) template matrix for rank-k deprojection
        """
        N = C.shape[0]
        if u is None: u = np.ones((N,1))
        Cinvu = np.linalg.solve(C,u)
        self.precalc = np.dot(Cinvu,np.linalg.solve(np.dot(u.T,Cinvu),u.T))
        self.C = C
    def solve(self,x):
        Cinvx = np.linalg.solve(self.C,x)
        correction = np.dot(self.precalc,Cinvx)
        return Cinvx - correction

def solve(C,x,u=None):
    """
    Typically, you do not want to invert your covariance matrix C, but really just want
    Cinv . x , for some vector x.
    You can get that with np.linalg.solve(C,x).
    This function goes one step further and deprojects a common mode for the entire
    covariance matrix, which is often what is needed.
    """
    N = C.shape[0]
    s = Solver(C,u=u)
    return s.solve(x)

def alpha_from_confidence(c):
    """Returns the number of sigmas that corresponds to enclosure of c % of the
    probability density in a 2D gaussian.

    e.g. alpha_from_confidence(0.683) = 1.52
    """
    return np.sqrt(2.*np.log((1./(1.-c))))

def corner_plot(fishers,labels,fid_dict=None,params=None,confidence_level=0.683,show_1d=False,
                latex_dict=None,colors=itertools.repeat(None),lss=itertools.repeat(None),
                thk=2,center_marker=True,save_file=None,loc='upper right',labelsize=14,ticksize=2,lw=3,**kwargs):
    """Make a triangle/corner plot from Fisher matrices.
    Does not support multiple confidence levels. (Redundant under Gaussian approximation of Fisher)

    fishers -- list of stats.FisherMatrix objects
    labels -- labels corresponding to each Fisher matrix in fishers
    params -- By default (if None) uses all params in every Fisher matrix. If not None, uses only this list of params.
    fid_dict -- dictionary mapping parameter names to fiducial values to center ellipses on
    latex_dict -- dictionary mapping parameter names to LaTeX strings for axes labels. Defaults to parameter names.
    confidence_level -- fraction of probability density enclosed by ellipse
    colors -- list of colors corresponding to fishers
    lss -- list of line styles corresponding to fishers
    """

    from orphics import io
    import matplotlib
    import matplotlib.pyplot as plt
    if params is None:
        ps = [f.params for f in fishers]
        jparams = list(set([p for sub_ps in ps for p in sub_ps]))
    else:
        jparams = params
    numpars = len(jparams)
    alpha = alpha_from_confidence(confidence_level)
    xx = np.array(np.arange(360) / 180. * np.pi)
    circl = np.array([np.cos(xx),np.sin(xx)])

    fig=plt.figure(figsize=(2*(numpars+1),2*(numpars+1)),**kwargs) if show_1d else plt.figure(figsize=(2*numpars,2*numpars),**kwargs)
    startp = 0 if show_1d else 1

    if show_1d:
        sigmas = []
        for fish in fishers:
            sigmas.append(fish.sigmas())
    else:
        sigmas = itertools.repeat(None)

    for i in range(0,numpars):
        for j in range(i+startp,numpars):
            count = 1+(j)*(numpars) + (i+1) -1 if show_1d else 1+(j-1)*(numpars-1) + i
            paramX = jparams[i]
            paramY = jparams[j]
            ax = fig.add_subplot(numpars,numpars,count) if show_1d else fig.add_subplot(numpars-1,numpars-1,count)

            if i>0:
                ax.yaxis.set_visible(False)
            if j!=(numpars-1):
                ax.xaxis.set_visible(False)

            try:
                xval = fid_dict[paramX]
            except:
                xval = 0.
            try:
                yval = fid_dict[paramY]
            except:
                yval = 0.
            try:
                paramlabely = '$%s$' % latex_dict[paramY]
            except:
                paramlabely = '$%s$' % paramY
            try:
                paramlabelx = '$%s$' % latex_dict[paramX]
            except:
                paramlabelx = '$%s$' % paramX
            if center_marker:
                if i==j:
                    ax.axvline(x=xval,ls="--",color='k',alpha=0.5)
                else:
                    ax.plot(xval,yval,'xk',mew=thk)

            for fish,ls,col,lab,sig in zip(fishers,lss,colors,labels,sigmas):

                if i==j:
                    try:
                        s = sig[paramX]
                    except:
                        continue
                    nsigma = 5
                    xs = np.linspace(xval-nsigma*s,xval+nsigma*s,1000)
                    from scipy.stats import norm
                    g = norm.pdf(xs,loc=xval,scale=s)
                    ax.plot(xs,g/g.max())
                    continue

                try:
                    chisq = fish.marge_var_2param(paramX,paramY)
                except:
                    ax.plot([xval],[yval],linewidth=0,color=col,ls=ls,label=lab,alpha=0) # just to iterate the colors and ls
                    continue
                Lmat = np.linalg.cholesky(chisq)
                ansout = np.dot(alpha*Lmat,circl)
                ax.plot(ansout[0,:]+xval,ansout[1,:]+yval,linewidth=lw,color=col,ls=ls,label=lab)
            if (i==0):
                ax.set_ylabel(paramlabely, fontsize=labelsize,weight='bold')
            if (j == (numpars-1)):
                ax.set_xlabel(paramlabelx, fontsize=labelsize,weight='bold')

    handles, labels = ax.get_legend_handles_labels()
    legend = fig.legend(handles, labels,prop={'size':labelsize},numpoints=1,frameon = 0,loc=loc, bbox_to_anchor = (-0.1,-0.1,1,1),bbox_transform = plt.gcf().transFigure,**kwargs)

    if save_file is None:
        plt.show()
    else:
        plt.savefig(save_file, bbox_inches='tight')
        print(io.bcolors.OKGREEN+"Saved plot to", save_file+io.bcolors.ENDC)

class OQE(object):
    """Optimal Quadratic Estimator for likelihoods that
    are Gaussian in the model parameters.

    WARNING: This class has not been tested thoroughly.

    Given a fiducial covariance matrix for the data and derivatives
    of the covariance matrix w.r.t. each parameter of interest,
    this class precalculates things like the Fisher matrix when
    initialized.

    Subsequently, given a data vector, it returns the OQEstimate
    as a dictionary in the parameters.
    """
    def __init__(self,fid_cov,dcov_dict,fid_params_dict,invert=False,deproject=True,templates=None):

        self.params = dcov_dict.keys()
        self.fids = fid_params_dict
        Nparams = len(self.params)
        self.invert = invert
        if invert:
            self.Cinv = self._inv(fid_cov)

        if templates is not None: assert deproject
        self.biases = {}
        self.ps = {}
        for param in self.params:
            if not(invert):
                if deproject:
                    solution = solve(fid_cov,dcov_dict[param],u=templates)
                else:
                    solution = np.linalg.solve(fid_cov,dcov_dict[param])
            self.ps[param] = np.dot(self.Cinv,dcov_dict[param]) if invert else solution.copy()
            self.biases[param] = np.trace(self.ps[param])

        self.Fisher = np.zeros((Nparams,Nparams))
        param_combs = itertools.combinations_with_replacement(self.params,2)
        for param1,param2 in param_combs:
            i = self.params.index(param1)
            j = self.params.index(param2)
            self.Fisher[i,j] = 0.5 * np.trace(np.dot(self.ps[param1],self.ps[param2]))
            if j!=i: self.Fisher[j,i] = self.Fisher[i,j]

        self.Finv = self._inv(self.Fisher)

        self.marg_errors = np.diagonal(self.Finv)**(1./2.)

        if not(invert):
            if deproject:
                self.s = Solver(fid_cov,u=templates)
                self.solver = lambda x: self.s.solve(x)
            else:
                self.solver = lambda x: np.linalg.solve(fid_cov,x)

    def sigma(self):
        return dict(zip(self.params,self.marg_errors.tolist()))

    def estimate(self,data):
        vec = []
        for param in self.params:
            cinvdat = np.dot(self.Cinv,data) if self.invert else self.solver(data)
            fcore = np.dot(np.dot(data.T,self.ps[param]),cinvdat)
            bsubbed = fcore - self.biases[param]
            assert bsubbed.size == 1
            vec.append(bsubbed)
        vec = np.asarray(vec)
        ans = 0.5 * np.dot(self.Finv,vec)
        ans = dict(zip(self.params,ans.tolist()))
        res = {}
        for param in self.params:
            res[param] = self.fids[param] + ans[param]
        return res

    def _inv(self,cov):
        # return np.linalg.pinv(cov)
        return np.linalg.inv(cov)
        # return scipy.linalg.pinv2(cov)

class OQESlim(object):
    def __init__(self,fid_cov,dcov_dict,fid_params_dict,templates=None):

        self.params = dcov_dict.keys()
        self.fids = fid_params_dict
        Nparams = len(self.params)
        self.biases = {}
        self.ps = {}
        for param in self.params:
            solution = solve(fid_cov,dcov_dict[param],u=templates)
            self.ps[param] = solution.copy()
            self.biases[param] = np.trace(self.ps[param])

        self.Fisher = np.zeros((Nparams,Nparams))
        param_combs = itertools.combinations_with_replacement(self.params,2)
        for param1,param2 in param_combs:
            i = self.params.index(param1)
            j = self.params.index(param2)
            self.Fisher[i,j] = 0.5 * np.trace(np.dot(self.ps[param1],self.ps[param2]))
            if j!=i: self.Fisher[j,i] = self.Fisher[i,j]

        self.Finv = np.linalg.inv(self.Fisher)
        self.marg_errors = np.diagonal(self.Finv)**(1./2.)

        self.s = Solver(fid_cov,u=templates)
        self.solver = lambda x: self.s.solve(x)

    def sigma(self):
        return dict(zip(self.params,self.marg_errors.tolist()))

    def estimate(self,data):
        vec = []
        for param in self.params:
            cinvdat = self.solver(data)
            fcore = np.dot(np.dot(data.T,self.ps[param]),cinvdat)
            bsubbed = fcore - self.biases[param]
            assert bsubbed.size == 1
            vec.append(bsubbed)
        vec = np.asarray(vec)
        ans = 0.5 * np.dot(self.Finv,vec)
        ans = dict(zip(self.params,ans.tolist()))
        res = {}
        for param in self.params:
            res[param] = self.fids[param] + ans[param]
        return res

class CinvUpdater(object):

    def __init__(self,cinvs,logdets,profile):
        self.cinvs = cinvs
        self.logdets = logdets

        u = profile.reshape((len(profile),1))
        v = u.copy()
        vT = v.T
        self.update_unnormalized = []
        self.det_unnormalized = []
        for Ainv in cinvs:
            self.update_unnormalized.append( np.dot(Ainv, np.dot(np.dot(u,vT), Ainv)) )
            self.det_unnormalized.append( np.dot(vT, np.dot(Ainv, u)) )

    def get_cinv(self,index,amplitude):

        det_update = 1.+(amplitude**2.)*self.det_unnormalized[index]
        cinv_updated = self.cinvs[index] - (amplitude**2.)*( self.update_unnormalized[index]/ det_update)
        return  cinv_updated , np.log(det_update)+self.logdets[index]

def eig_pow(C,exponent=-1,lim=1.e-8):
    e,v = np.linalg.eigh(C)
    emax = np.max(e)
    mask = e<emax*lim
    e[~mask] **= exponent
    e[mask]=0.
    return (v*e).dot(v.T)

def sm_update(Ainv, u, v=None):
    """Compute the value of (A + uv^T)^-1 given A^-1, u, and v.
    Uses the Sherman-Morrison formula."""

    v = u.copy() if v is None else v
    u = u.reshape((len(u),1))
    v = v.reshape((len(v),1))
    vT = v.T

    ldot = np.dot(vT, np.dot(Ainv, u))
    assert ldot.size==1
    det_update = 1.+ldot.ravel()[0]

    ans = Ainv - (np.dot(Ainv, np.dot(np.dot(u,vT), Ainv)) / det_update)
    return ans, det_update

def cov2corr(mat):
    diags = np.diagonal(mat).T
    xdiags = diags[:,None,...]
    ydiags = diags[None,:,...]
    corr = mat/np.sqrt(xdiags*ydiags)
    return corr

def correlated_hybrid_matrix(data_covmat,theory_covmat=None,theory_corr=None,cap=True,cap_off=0.99):
    """
    Given a diagonal matrix data_covmat,
    and a theory matrix theory_covmat or its correlation matrix theory_corr,
    produce a hybrid non-diagonal matrix that has the same diagonals as the data matrix
    but has correlation coefficient given by theory.
    """
    if theory_corr is None:
        assert theory_covmat is not None
        theory_corr = cov2corr(theory_covmat)
    r = theory_corr

    def _cap(imat,cval,csel):
        imat[imat>1] = 1
        imat[imat<-1] = -1
        imat[csel][imat[csel]>cval] = cval
        imat[csel][imat[csel]>-cval] = -cval

    d = data_covmat.copy()
    sel = np.where(~np.eye(d.shape[0],dtype=bool))
    d[sel] = 1
    dcorr = 1./cov2corr(d)
    if cap: _cap(r,cap_off,sel)
    fcorr = dcorr * r
    d[sel] = fcorr[sel]
    return d

class Stats(object):
    """
    An MPI enabled helper container for
    1) 1d measurements whose statistics need to be calculated
    2) 2d cumulative stacks

    where different MPI cores may be calculating different number
    of 1d measurements or 2d stacks.
    """

    def __init__(self,comm=None,root=0,loopover=None,tag_start=333):
        """
        comm - MPI.COMM_WORLD object
        tag_start - MPI comm tags start at this integer
        """

        if comm is not None:
            self.comm = comm
        else:
            from orphics.mpi import fakeMpiComm
            self.comm = fakeMpiComm()

        self.rank = self.comm.Get_rank()
        self.numcores = self.comm.Get_size()
        self.columns = {}

        self.vectors = {}
        self.little_stack = {}
        self.little_stack_count = {}
        self.tag_start = tag_start
        self.root = root
        if loopover is None:
            self.loopover = list(range(root+1,self.numcores))
        else:
            self.loopover = loopover

    def add_to_stats(self,label,vector,exclude=False):
        """
        Append the 1d vector to a statistic named "label".
        Create a new one if it doesn't already exist.
        """
        assert label!='stats', "Sorry, 'stats' is a forbidden label."

        vector = np.asarray(vector)

        if np.iscomplexobj(vector):
            print("ERROR: stats on complex arrays not supported. Do the real and imaginary parts separately.")
            raise TypeError

        if not(label in list(self.vectors.keys())):
            self.vectors[label] = []
            self.columns[label] = vector.shape
        if not(exclude):
            self.vectors[label].append(vector)

    def add_to_stack(self,label,arr,exclude=False):
        """
        This is just an accumulator, it can't track statisitics.
        Add arr to a cumulative stack named "label". Could be 2d arrays.
        Create a new one if it doesn't already exist.
        """
        assert label!='stats', "Sorry, 'stats' is a forbidden label."

        if np.iscomplexobj(arr):
            print("ERROR: stacking of complex arrays not supported. Stack the real and imaginary parts separately.")
            raise TypeError
        if not(label in list(self.little_stack.keys())):
            self.little_stack[label] = arr*0.
            self.little_stack_count[label] = 0
        if not(exclude):
            self.little_stack[label] += arr
            self.little_stack_count[label] += 1

    def get_stacks(self,verbose=True):
        """
        Collect from all MPI cores and calculate stacks.
        """

        if self.rank in self.loopover:

            for k,label in enumerate(self.little_stack.keys()):
                self.comm.send(self.little_stack_count[label], dest=self.root, tag=self.tag_start*3000+k)

            for k,label in enumerate(self.little_stack.keys()):
                send_dat = np.array(self.little_stack[label]).astype(np.float64)
                self.comm.Send(send_dat, dest=self.root, tag=self.tag_start*10+k)

        elif self.rank==self.root:
            self.stacks = {}
            self.stack_count = {}

            for k,label in enumerate(self.little_stack.keys()):
                self.stack_count[label] = self.little_stack_count[label]
                for core in self.loopover:
                    if verbose: print(f"{label} waiting for count from core ", core , " / ", self.numcores)
                    data = self.comm.recv(source=core, tag=self.tag_start*3000+k)
                    self.stack_count[label] += data

            for k,label in enumerate(self.little_stack.keys()):
                self.stacks[label] = self.little_stack[label]
            for core in self.loopover:
                if verbose: print(f"Waiting for data from core ", core , " / ", self.numcores)
                for k,label in enumerate(self.little_stack.keys()):
                    expected_shape = self.little_stack[label].shape
                    data_vessel = np.empty(expected_shape, dtype=np.float64)
                    self.comm.Recv(data_vessel, source=core, tag=self.tag_start*10+k)
                    self.stacks[label] += data_vessel

            for k,label in enumerate(self.little_stack.keys()):
                self.stacks[label] /= self.stack_count[label]

    def get_stats(self,verbose=True,skip_stats=False):
        """
        Collect from all MPI cores and calculate statistics for
        1d measurements.
        """

        if self.rank in self.loopover:
            for k,label in enumerate(self.vectors.keys()):
                self.comm.send(np.array(self.vectors[label]).shape[0], dest=self.root, tag=self.tag_start*2000+k)

            for k,label in enumerate(self.vectors.keys()):
                send_dat = np.array(self.vectors[label]).astype(np.float64)
                self.comm.Send(send_dat, dest=self.root, tag=self.tag_start+k)

        else:
            self.stats = {}
            self.numobj = {}
            for k,label in enumerate(self.vectors.keys()):
                self.numobj[label] = []
                self.numobj[label].append(np.array(self.vectors[label]).shape[0])
                for core in self.loopover: #range(1,self.numcores):
                    if verbose: print(f"{label} waiting for size from core ", core , " / ", self.numcores)
                    data = self.comm.recv(source=core, tag=self.tag_start*2000+k)
                    self.numobj[label].append(data)

            for k,label in enumerate(self.vectors.keys()):
                self.vectors[label] = np.array(self.vectors[label])
            for core in self.loopover: #range(1,self.numcores):
                if verbose: print(f"Waiting for data from core ", core , " / ", self.numcores)
                for k,label in enumerate(self.vectors.keys()):
                    expected_shape = (self.numobj[label][core],)+self.columns[label]
                    data_vessel = np.empty(expected_shape, dtype=np.float64)
                    self.comm.Recv(data_vessel, source=core, tag=self.tag_start+k)
                    try:
                        self.vectors[label] = np.append(self.vectors[label],data_vessel,axis=0)
                    except: # in case rank 0 has no data because it is not participating
                        self.vectors[label] = data_vessel

            if not(skip_stats):
                for k,label in enumerate(self.vectors.keys()):
                    self.stats[label] = get_stats(self.vectors[label])
            #self.vectors = {}

    def dump(self,path):
        for d,name in zip([self.vectors,self.stacks],['vectors','stack']):
            for key in d.keys():
                np.save(f"{path}/mstats_dump_{name}_{key}.npy",d[key])
        for key in self.stats.keys():
            for skey in self.stats[key].keys():
                np.savetxt(f"{path}/mstats_dump_stats_{key}_{skey}.txt",np.atleast_1d(self.stats[key][skey]))

def load_stats(path):
    import glob,re
    class S:
        pass
    s = S()
    s.vectors = {}
    s.stats = {}
    s.stacks = {}
    for sstr,sdict in zip(['vectors','stack'],[s.vectors,s.stacks]):
        vfiles = glob.glob(f"{path}/mstats_dump_{sstr}_*.npy")
        for vfile in vfiles:
            key = re.search(rf'mstats_dump_{sstr}_(.*?).npy', vfile).group(1)
            sdict[key] = np.load(f"{path}/mstats_dump_{sstr}_{key}.npy")

    vfiles = glob.glob(f"{path}/mstats_dump_stats_*_mean.txt")
    keys = []
    for vfile in vfiles:
        key = re.search(rf'mstats_dump_stats_(.*?)_mean.txt', vfile).group(1)
        keys.append(key)
    for key in keys:
        s.stats[key] = {}
        vfiles = glob.glob(f"{path}/mstats_dump_stats_{key}_*.txt")
        for vfile in vfiles:
            skey = re.search(rf'mstats_dump_stats_{key}_(.*?).txt', vfile).group(1)
            arr = np.loadtxt(f"{path}/mstats_dump_stats_{key}_{skey}.txt")
            if arr.size==1: arr = arr.ravel()[0]
            s.stats[key][skey] = arr
    return s

def npspace(minim,maxim,num,scale="lin"):
    if scale=="lin" or scale=="linear":
        return np.linspace(minim,maxim,num)
    elif scale=="log":
        return np.logspace(np.log10(minim),np.log10(maxim),num)

class bin2D(object):
    def __init__(self, modrmap, bin_edges):
        self.centers = (bin_edges[1:]+bin_edges[:-1])/2.
        self.digitized = np.digitize(modrmap.reshape(-1), bin_edges,right=True)
        self.bin_edges = bin_edges
        self.modrmap = modrmap

    def bin(self,data2d,weights=None,err=False,get_count=False,mask_nan=False):
        if weights is None:
            if mask_nan:
                keep = ~np.isnan(data2d.reshape(-1))
            else:
                keep = np.ones((data2d.size,),dtype=bool)
            count = np.bincount(self.digitized[keep])[1:-1]
            res = np.bincount(self.digitized[keep],(data2d).reshape(-1)[keep])[1:-1]/count
            if err:
                meanmap = self.modrmap.copy().reshape(-1) * 0
                for i in range(self.centers.size): meanmap[self.digitized==i] = res[i]
                std = np.sqrt(np.bincount(self.digitized[keep],((data2d-meanmap.reshape(self.modrmap.shape))**2.).reshape(-1)[keep])[1:-1]/(count-1)/count)
        else:
            count = np.bincount(self.digitized,weights.reshape(-1))[1:-1]
            res = np.bincount(self.digitized,(data2d*weights).reshape(-1))[1:-1]/count
        if get_count:
            assert not(err) # need to make more general
            return self.centers,res,count
        if err:
            assert not(get_count)
            return self.centers,res,std
        return self.centers,res

class bin1D:
    '''
    * Takes data defined on x0 and produces values binned on x.
    * Assumes x0 is linearly spaced and continuous in a domain?
    * Assumes x is continuous in a subdomain of x0.
    * Should handle NaNs correctly.
    '''

    def __init__(self, bin_edges):

        self.update_bin_edges(bin_edges)

    def update_bin_edges(self,bin_edges):

        self.bin_edges = bin_edges
        self.numbins = len(bin_edges)-1
        self.cents = (self.bin_edges[:-1]+self.bin_edges[1:])/2.

        self.bin_edges_min = self.bin_edges.min()
        self.bin_edges_max = self.bin_edges.max()

    def bin(self,ix,iy,stat=np.nanmean):
        x = ix.copy()
        y = iy.copy()
        # this just prevents an annoying warning (which is otherwise informative) everytime
        # all the values outside the bin_edges are nans
        y[x<self.bin_edges_min] = 0
        y[x>self.bin_edges_max] = 0

        # pretty sure this treats nans in y correctly, but should double-check!
        bin_means = binnedstat(x,y,bins=self.bin_edges,statistic=stat)[0]

        return self.cents,bin_means

def bin_in_annuli(data2d, modrmap, bin_edges):
    binner = bin2D(modrmap, bin_edges)
    return binner.bin(data2d)

def get_stats(binned_vectors):
    '''
    Returns statistics given an array-like object
    each row of which is an independent sample
    and each column holds possibly correlated
    binned values.

    The statistics are returned as a dictionary with
    keys:
    1. mean
    2. cov
    3. covmean
    4. err
    5. errmean
    6. corr
    '''
    # untested!

    arr = np.asarray(binned_vectors)

    N = arr.shape[0]
    ret = {}
    ret['mean'] = np.nanmean(arr,axis=0)
    ret['cov'] = np.cov(arr.transpose())
    ret['covmean'] = ret['cov'] / N
    if arr.shape[1]==1:
        ret['err'] = np.sqrt(ret['cov'])
    else:
        ret['err'] = np.sqrt(np.diagonal(ret['cov']))
    ret['errmean'] = ret['err'] / np.sqrt(N)

    # correlation matrix
    if arr.shape[1]==1:
        ret['corr'] = 1.
    else:
        ret['corr'] = cov2corr(ret['cov'])

    return ret

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print('%r %2.2f sec' % \
              (method.__name__,te-ts))
        return result

    return timed


text:
package de.sjanusch;

import de.sjanusch.bot.Bot;
import de.sjanusch.runner.BotRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;

public class Xmpp implements Runnable {

  private static final Logger logger = LoggerFactory.getLogger(Xmpp.class);

  private final BotRunner botRunner;

  private final Bot bot;

  @Inject
  public Xmpp(final BotRunner botRunner, final Bot bot) {
    this.botRunner = botRunner;
    this.bot = bot;
  }

  @Override
  public void run() {
    final Thread t = botRunner.runBotDesync(bot);
    try {
      t.join();
    } catch (InterruptedException e) {
      logger.error("InterruptedException: " + e.getMessage());
    }
    t.start();
    logger.debug("Lunchbot started");
  }
}


text:
//初始枚举数据
/**
 *
 * @param enumUrl 请求头路径
 * @param enumType 查询类型
 * @param optionId 下拉框ID
 * @param isAllValue 是否有全选择
 * @param optionValue 默认值
 */
function initEnumData(methodUrl,optionId,optionType,isAllValue,enumSearchData,optionValue){
	$.ajax({
	 		url:methodUrl,
	 		contentType:"application/json",
	 		type:"get",
	 		dataType:"json",
	 		success:function(result){
	 			enumSearchData = result;
	 			evaluationSelection(result,optionId,optionType,optionValue,isAllValue,true);
	 		}
 	});
}
//赋值下拉框值
function evaluationSelection(result,optionId,optionType,optionValue,isAllValue,isShowOption){
	var optionObj = document.getElementById(optionId);
	if(isShowOption==true){
		if(optionObj.length<=0){
		    optionObj.options.remove(0,1);
		    if(isAllValue==true){
				optionObj.options.add(new Option("全选",""));
			}
			for (var i=0;i<result.length;i++){
		 		var obj = result[i];
		 		if(optionType == "enum"){
		 			optionObj.options.add(new Option(obj.text,obj.value));
		 		}
		 		if(optionType == "role"){
		 			optionObj.options.add(new Option(obj.name,obj.id));
		 		}
		 		if(optionType == "pd"){
		 			optionObj.options.add(new Option((obj.name+"--"+obj.version),obj.id));
		 		}
		 	}
		}
	}
	if(optionValue!=null && optionObj.length>0){
		for(var i=0;i<optionObj.length;i++){
			if(optionObj[i].value == initVal){
				optionObj[i].selected = true;
				break;
			}
		}

	}
}

/**
 * 是否为空
 * @param value 要判断的值
 * @returns
 */
function contentIsEmpty(value){
	if(value==null || value==""){
		return "";
	}
	return value;
}

/**
 * 截取字符串
 * @param content 需要截取的字符内容
 * @param showChar 截取后显示的字符
 * @param len 截取长度
 * @returns
 */
function charsSubstring(content,len,showChar){
	if(contentIsEmpty(content)==""){
		return "";
	}
	if(content.length>=len){

		return content.substring(0,len)+showChar;
	}
	return content;
}


text:
package xorm

import (
	"path/filepath"
)

func (engine *Engine) RegisterSqlTemplate(sqlt SqlTemplate, Cipher ...Cipher) error {
	engine.SqlTemplate = sqlt
	if len(Cipher) > 0 {
		engine.SqlTemplate.SetSqlTemplateCipher(Cipher[0])
	}
	err := filepath.Walk(engine.SqlTemplate.RootDir(), engine.SqlTemplate.WalkFunc)
	if err != nil {
		return err
	}

	return nil
}

func (engine *Engine) LoadSqlTemplate(filepath string) error {
	return engine.SqlTemplate.LoadSqlTemplate(filepath)
}

func (engine *Engine) BatchLoadSqlTemplate(filepathSlice []string) error {
	return engine.SqlTemplate.BatchLoadSqlTemplate(filepathSlice)
}

func (engine *Engine) ReloadSqlTemplate(filepath string) error {
	return engine.SqlTemplate.ReloadSqlTemplate(filepath)
}

func (engine *Engine) BatchReloadSqlTemplate(filepathSlice []string) error {
	return engine.SqlTemplate.BatchReloadSqlTemplate(filepathSlice)
}

func (engine *Engine) AddSqlTemplate(key string, sqlTemplateStr string) error {
	return engine.SqlTemplate.AddSqlTemplate(key, sqlTemplateStr)
}

func (engine *Engine) UpdateSqlTemplate(key string, sqlTemplateStr string) error {
	return engine.SqlTemplate.UpdateSqlTemplate(key, sqlTemplateStr)
}

func (engine *Engine) RemoveSqlTemplate(key string) {
	engine.SqlTemplate.RemoveSqlTemplate(key)
}

func (engine *Engine) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error {
	return engine.SqlTemplate.BatchAddSqlTemplate(key, sqlTemplateStrMap)

}

func (engine *Engine) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error {
	return engine.SqlTemplate.BatchUpdateSqlTemplate(key, sqlTemplateStrMap)

}

func (engine *Engine) BatchRemoveSqlTemplate(key []string) {
	engine.SqlTemplate.BatchRemoveSqlTemplate(key)
}


text:
<?php

namespace SensioLabs\Melody\Tests\Handler;

use SensioLabs\Melody\Handler\GistHandler;

class GistHandlerTest extends \PHPUnit_Framework_TestCase
{
    const SINGLE_URL = 'https://gist.github.com/csarrazi/7494d27255d0561157b8';
    const MULTI_URL  = 'https://gist.github.com/alexandresalome/e1dcf99dedadd4838a99';

    private $handler;

    protected function setUp()
    {
        $this->handler = new GistHandler();
    }

    protected function tearDown()
    {
        $this->handler = null;
    }

    public function provideSupports()
    {
        return array(
            array(__DIR__ . '/../fixtures/foo.php', false),
            array(__DIR__ . '/../fixtures/foobar.php', false),
            array(__DIR__ . '/../fixtures', false),
            array('https://gist.github.com/foobar/7494d27255d0561157b8', true),
            array('https://gist.github.com/foobar/7494d27255d0561157b8', true),
            array('https://gist.github.com/foobar-/7494d27255d0561157b8', true),
            array('https://gist.github.com/foo-bar/7494d27255d0561157b8', true),
            array('https://gist.github.com/-foobar/7494d27255d0561157b8', false),
            array('https://gist.github.com/thisusernameistoolongandshouldnotbevalid/7494d27255d0561157b8', false),
            array('https://gist.github.com/thisusernameisnttoolongandshouldbevalid/7494d27255d0561157b8', true),
            array('foobar/7494d27255d0561157b8', true),
            array('foobar-/7494d27255d0561157b8', true),
            array('foo-bar/7494d27255d0561157b8', true),
            array('-foobar/7494d27255d0561157b8', false),
            array('thisusernameistoolongandshouldnotbevalid/7494d27255d0561157b8', false),
            array('thisusernameisnttoolongandshouldbevalid/7494d27255d0561157b8', true),
        );
    }

    /**
     * @dataProvider provideSupports
     */
    public function testSupports($url, $expected)
    {
        $this->assertEquals($expected, $this->handler->supports($url));
    }

    public function testCreateResource()
    {
        $resource = $this->handler->createResource(self::SINGLE_URL);

        $this->assertInstanceOf('SensioLabs\Melody\Resource\Resource', $resource);
        $this->assertContains('$composer', $resource->getContent());
        $this->assertContains('twig/twig', $resource->getContent());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testCreateResourceWithMultipleFileInGist()
    {
        $this->handler->createResource(self::MULTI_URL);
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Cache;

use PhpCsFixer\Cache\Cache;
use PhpCsFixer\Cache\FileHandler;
use PhpCsFixer\Cache\Signature;
use PhpCsFixer\Cache\SignatureInterface;
use PhpCsFixer\Tests\TestCase;
use Symfony\Component\Filesystem\Exception\IOException;

/**
 * @author Andreas Möller <am@localheinz.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Cache\FileHandler
 */
final class FileHandlerTest extends TestCase
{
    protected function tearDown(): void
    {
        parent::tearDown();

        $file = $this->getFile();

        if (file_exists($file)) {
            unlink($file);
        }
    }

    public function testImplementsHandlerInterface(): void
    {
        $file = $this->getFile();

        $handler = new FileHandler($file);

        static::assertInstanceOf(\PhpCsFixer\Cache\FileHandlerInterface::class, $handler);
    }

    public function testConstructorSetsFile(): void
    {
        $file = $this->getFile();

        $handler = new FileHandler($file);

        static::assertSame($file, $handler->getFile());
    }

    public function testReadReturnsNullIfFileDoesNotExist(): void
    {
        $file = $this->getFile();

        $handler = new FileHandler($file);

        static::assertNull($handler->read());
    }

    public function testReadReturnsNullIfContentCanNotBeDeserialized(): void
    {
        $file = $this->getFile();

        file_put_contents($file, 'hello');

        $handler = new FileHandler($file);

        static::assertNull($handler->read());
    }

    public function testReadReturnsCache(): void
    {
        $file = $this->getFile();

        $signature = $this->createSignature();

        $cache = new Cache($signature);

        file_put_contents($file, $cache->toJson());

        $handler = new FileHandler($file);

        $cached = $handler->read();

        static::assertInstanceOf(\PhpCsFixer\Cache\CacheInterface::class, $cached);
        static::assertTrue($cached->getSignature()->equals($signature));
    }

    public function testWriteThrowsIOExceptionIfFileCanNotBeWritten(): void
    {
        $file = __DIR__.'/non-existent-directory/.php-cs-fixer.cache';

        $this->expectException(IOException::class);
        $this->expectExceptionMessageMatches(sprintf(
            '#^Directory of cache file "%s" does not exists.#',
            preg_quote($file, '#')
        ));

        $cache = new Cache($this->createSignature());

        $handler = new FileHandler($file);

        $handler->write($cache);
    }

    public function testWriteWritesCache(): void
    {
        $file = $this->getFile();

        $cache = new Cache($this->createSignature());

        $handler = new FileHandler($file);

        $handler->write($cache);

        static::assertFileExists($file);

        $actualCacheJson = file_get_contents($file);

        static::assertSame($cache->toJson(), $actualCacheJson);
    }

    public function testWriteCacheToDirectory(): void
    {
        $dir = __DIR__.'/../Fixtures/cache-file-handler';

        $handler = new FileHandler($dir);

        $this->expectException(IOException::class);
        $this->expectExceptionMessageMatches(sprintf(
            '#^%s$#',
            preg_quote('Cannot write cache file "'.realpath($dir).'" as the location exists as directory.', '#')
        ));

        $handler->write(new Cache($this->createSignature()));
    }

    public function testWriteCacheToNonWriteableFile(): void
    {
        $file = __DIR__.'/../Fixtures/cache-file-handler/cache-file';
        if (is_writable($file)) {
            static::markTestSkipped(sprintf('File "%s" must be not writeable for this tests.', realpath($file)));
        }

        $handler = new FileHandler($file);

        $this->expectException(IOException::class);
        $this->expectExceptionMessageMatches(sprintf(
            '#^%s$#',
            preg_quote('Cannot write to file "'.realpath($file).'" as it is not writable.', '#')
        ));

        $handler->write(new Cache($this->createSignature()));
    }

    public function testWriteCacheFilePermissions(): void
    {
        $file = __DIR__.'/../Fixtures/cache-file-handler/rw_cache.test';
        @unlink($file);

        static::assertFileDoesNotExist($file);

        $handler = new FileHandler($file);
        $handler->write(new Cache($this->createSignature()));

        static::assertFileExists($file);
        static::assertTrue(@is_file($file), sprintf('Failed cache "%s" `is_file`.', $file));
        static::assertTrue(@is_writable($file), sprintf('Failed cache "%s" `is_writable`.', $file));
        static::assertTrue(@is_readable($file), sprintf('Failed cache "%s" `is_readable`.', $file));

        @unlink($file);
    }

    private function getFile(): string
    {
        return __DIR__.'/.php-cs-fixer.cache';
    }

    private function createSignature(): SignatureInterface
    {
        return new Signature(
            PHP_VERSION,
            '2.0',
            '    ',
            PHP_EOL,
            ['foo' => true, 'bar' => false],
        );
    }
}


text:
@implementation LeaveModel

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"leaveId":@"id", @"sendPersons": @"copySendPersons", @"sendPersonList": @"copySendPersonList"};
}

@end