text:
<?php

class SPVIDEOLITE_IMP_Vk implements SPVIDEOLITE_CLASS_IImporter
{
	private static $regexp = '#vk\.com.*/video(\-?\d+_\d+)#i';
	private static $regexpIdIndex = 1;
	private static $embedTemplate = '';

	public static function getRegExp() {
		return self::$regexp;
	}

	public static function getRegExpIdentifierIndex() {
		return self::$regexpIdIndex;
	}

	public static function embedApplyVideoId($videoId) {
		$ids = explode('_', $videoId);
		$oid = $ids[0];
		$id = $ids[1];
		$hash = $ids[2];
		$code = str_replace('{videoId}', $id, self::$embedTemplate);
		$code = str_replace('{ownerId}', $oid, $code);
		$code = str_replace('{hash}', $hash, $code);
		return $code;
	}

	public static function getClipIdentifier( $url ) {
		$matches = array();
		if (preg_match(self::$regexp, $url, $matches)) {
			return $matches[self::$regexpIdIndex];
		} else {
			throw new Exception('Unmatched URL of service');
		}
	}

	public static function getClipDetailByUrl( $url ) {
		$id = self::getClipIdentifier( $url );
		return self::getClipDetailByIdentifier($id);
	}

	public static function getClipDetailByIdentifier( $id ) {
		$video = new stdClass;
		# XML data URL
		$file_data = 'http://vk.com/video'.$id;
		$video->html_url = $file_data;

		# XML
		$html = file_get_contents($file_data);

		$matches = array();

		$jsonRegex = '#var\svars\s=\s(.*?)\\\\n#i';
		preg_match_all($jsonRegex, $html, $matches);
		$json = $matches[1][0];
		$json = stripcslashes($json);
		if (substr($json, -1) == ';')
			$json = substr($json, 0, -1);
		$json = json_decode($json, true);

		# Title
		$video->title = $json['md_title'] ? strval($json['md_title']) : null;

		# Description
		$description_query = '#
(.*?)<\/div>#i';
		$description = array();
		preg_match_all($description_query, $html, $description);
		$description = isset($description[1][0])?$description[1][0]:false;
		$video->description = $description ? strval(trim($description)) : null;

		# Tags
		$video->tags = null;

		# Duration
		$video->duration = null;

		# Author & author URL
		$video->author_url = null;

		# Publication date
		$video->date_published = null;

		# Last update date
		$video->date_updated = null;

		# Thumbnails
		$thumbnail = new stdClass;
		$thumbnail->url = preg_replace("/(http\:\/\/|https\:\/\/)/", "//", $json['jpg']);
		$thumbnail->width = 320;
		$thumbnail->height = 240;
		$video->thumbnails[] = $thumbnail;

		# Player URL
		$video->player_url = null;

		# FLV file URL
		$video->files = array();

		# Embed Code
		$video->embedCode = self::embedApplyVideoId($id . '_' . $json['hash2']);
		return $video;
	}
}


text:
php /path/to/composer.phar install --dev

# setup database parameter
sed -i "" -e "s/symfony/symfony-test/g" app/config/parameters.yml
sed -i "" -e "s/database_password: null/database_password: root/g" app/config/parameters.yml

# some command to init project
php app/console doctrine:database:drop --force
php app/console doctrine:database:create
php app/console doctrine:schema:create

# hack to say yes on fixtures load
php app/console doctrine:fixtures:load < /usr/bin/yes

redpajama_set_name: RedPajamaGithub


text:
class Users::RegistrationsRewardsController < Devise::RegistrationsController
  def create

  end

  def sign_up
  end

  def login
    render

  end

end


text:
#include "h2o.h"
#include "h2o/configurator.h"

struct errordoc_configurator_t {
    h2o_configurator_t super;
    h2o_mem_pool_t pool;
    H2O_VECTOR(h2o_errordoc_t) * vars, _vars_stack[H2O_CONFIGURATOR_NUM_LEVELS + 1];
};

static int register_errordoc(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *hash)
{
    struct errordoc_configurator_t *self = (void *)cmd->configurator;
    int status = -1;
    const char *url = NULL;
    size_t i;
    yoml_t *key, *value;

    for (i = 0; i != hash->data.mapping.size; ++i) {
        key = hash->data.mapping.elements[i].key;
        value = hash->data.mapping.elements[i].value;
        if (key->type != YOML_TYPE_SCALAR)
            goto UnknownKeyError;
        if (strcmp(key->data.scalar, "status") == 0) {
            if (status != -1)
                goto KeyAlreadyDefinedError;
            if (h2o_configurator_scanf(cmd, value, "%d", &status) != 0)
                return -1;
            if (!(400 <= status && status <= 599)) {
                h2o_configurator_errprintf(cmd, value, "status must be within range of 400 to 599");
                return -1;
            }
        } else if (strcmp(key->data.scalar, "url") == 0) {
            if (url != NULL)
                goto KeyAlreadyDefinedError;
            if (value->type != YOML_TYPE_SCALAR) {
                h2o_configurator_errprintf(cmd, value, "URL must be a scalar");
                return -1;
            }
            url = value->data.scalar;
        } else {
            goto UnknownKeyError;
        }
    }

    if (status == -1) {
        h2o_configurator_errprintf(cmd, hash, "mandatory key `status` is not defined");
        return -1;
    }
    if (url == NULL) {
        h2o_configurator_errprintf(cmd, hash, "mandatory key `url` is not defined");
        return -1;
    }

    { /* register */
        h2o_vector_reserve(&self->pool, self->vars, self->vars->size + 1);
        h2o_errordoc_t *errordoc = self->vars->entries + self->vars->size++;
        errordoc->status = status;
        errordoc->url = h2o_strdup(&self->pool, url, SIZE_MAX);
    }

    return 0;

UnknownKeyError:
    h2o_configurator_errprintf(cmd, key, "key must be either of: `status`, `url`");
    return -1;
KeyAlreadyDefinedError:
    h2o_configurator_errprintf(cmd, key, "the key cannot be defined more than once");
    return -1;
}

static int on_config_errordoc(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
    switch (node->type) {
    case YOML_TYPE_SEQUENCE: {
        size_t i;
        for (i = 0; i != node->data.sequence.size; ++i) {
            yoml_t *e = node->data.sequence.elements[i];
            if (e->type != YOML_TYPE_MAPPING) {
                h2o_configurator_errprintf(cmd, e, "element must be a mapping");
                return -1;
            }
            if (register_errordoc(cmd, ctx, e) != 0)
                return -1;
        }
        return 0;
    }
    case YOML_TYPE_MAPPING:
        return register_errordoc(cmd, ctx, node);
    default:
        break;
    }

    h2o_configurator_errprintf(cmd, node, "argument must be either of: sequence, mapping");
    return -1;
}

static int on_config_enter(h2o_configurator_t *_self, h2o_configurator_context_t *ctx, yoml_t *node)
{
    struct errordoc_configurator_t *self = (void *)_self;

    if (self->vars == self->_vars_stack) {
        /* entering global level */
        h2o_mem_init_pool(&self->pool);
    }

    /* copy vars */
    memset(&self->vars[1], 0, sizeof(self->vars[1]));
    h2o_vector_reserve(&self->pool, &self->vars[1], self->vars[0].size);
    memcpy(self->vars[1].entries, self->vars[0].entries, sizeof(self->vars[0].entries[0]) * self->vars[0].size);
    self->vars[1].size = self->vars[0].size;

    ++self->vars;
    return 0;
}

static int on_config_exit(h2o_configurator_t *_self, h2o_configurator_context_t *ctx, yoml_t *node)
{
    struct errordoc_configurator_t *self = (void *)_self;

    if (ctx->pathconf != NULL && self->vars->size != 0)
        h2o_errordoc_register(ctx->pathconf, self->vars->entries, self->vars->size);

    --self->vars;
    if (self->vars == self->_vars_stack) {
        /* exitting global level */
        h2o_mem_clear_pool(&self->pool);
    }

    return 0;
}

void h2o_errordoc_register_configurator(h2o_globalconf_t *conf)
{
    struct errordoc_configurator_t *c = (void *)h2o_configurator_create(conf, sizeof(*c));

    /* set default vars */
    c->vars = c->_vars_stack;

    /* setup handlers */
    c->super.enter = on_config_enter;
    c->super.exit = on_config_exit;

    /* reproxy: ON | OFF */
    h2o_configurator_define_command(&c->super, "error-doc", H2O_CONFIGURATOR_FLAG_ALL_LEVELS, on_config_errordoc);
}


text:
package com.jordic.meatapp.POJO.flickr;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Size {

    @SerializedName("label")
    @Expose
    public String label;
    @SerializedName("width")
    @Expose
    public String width;
    @SerializedName("height")
    @Expose
    public String height;
    @SerializedName("source")
    @Expose
    public String source;
    @SerializedName("url")
    @Expose
    public String url;
    @SerializedName("media")
    @Expose
    public String media;

}


text:
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import AdRequestTime from '../computed/ad-request-time.js';

import * as i18n from 'lighthouse/core/lib/i18n/i18n.js';
import LongTasks from '../computed/long-tasks.js';
import {auditNotApplicable} from '../messages/common-strings.js';
import {Audit} from 'lighthouse';
import {getAttributableUrl} from '../utils/tasks.js';
import {isAdScript} from '../utils/resource-classification.js';

const UIStrings = {
  /* Title of the audit */
  title: 'No long tasks blocking ad-related network requests',
  failureTitle: 'Avoid long tasks that block ad-related network requests',
  description: 'Tasks blocking the main thread can delay ad requests and cause ' +
  'a poor user experience. Consider removing long blocking tasks or moving ' +
  'them off of the main thread. These tasks can be especially detrimental to ' +
  'performance on less powerful devices. [Learn more](' +
  'https://developers.google.com/publisher-ads-audits/reference/audits/ad-blocking-tasks' +
  ').',
  failureDisplayValue: '{timeInMs, number, seconds} s blocked',
  columnScript: 'Attributable URL',
  columnStartTime: 'Start',
  columnDuration: 'Duration',
};

const str_ = i18n.createIcuMessageFn(import.meta.url, UIStrings);
/**
 * @typedef {Object} TaskDetails
 * @property {number} startTime
 * @property {number} endTime
 * @property {number} duration
 * @property {string} script
 * @property {string} rawUrl
 * @property {boolean} isTopLevel
 */

/**
 * Table headings for audits details sections.
 * @type {LH.Audit.Details.Table['headings']}
 */
const HEADINGS = [
  {
    key: 'script',
    itemType: 'url',
    text: str_(UIStrings.columnScript),
  },
  {
    key: 'startTime',
    itemType: 'ms',
    text: str_(UIStrings.columnStartTime),
    granularity: 1,
  },
  {
    key: 'duration',
    itemType: 'ms',
    text: str_(UIStrings.columnDuration),
    granularity: 1,
  },
];

/** @inheritDoc */
class AdBlockingTasks extends Audit {
  /**
   * @return {LH.Audit.Meta}
   */
  static get meta() {
    return {
      id: 'ad-blocking-tasks',
      title: str_(UIStrings.title),
      failureTitle: str_(UIStrings.failureTitle),
      description: str_(UIStrings.description),
      requiredArtifacts: ['traces', 'devtoolsLogs'],
    };
  }

  /**
   * @param {LH.Artifacts} artifacts
   * @param {LH.Audit.Context} context
   * @return {Promise<LH.Audit.Product>}
   * @override
   */
  static async audit(artifacts, context) {
  /**
   * Threshold to show long tasks in the report. We don't show shorter long
   * tasks since they each have a smaller impact on blocking ads.
   */
    const LONG_TASK_DUR_MS =
      context.settings.throttlingMethod == 'simulate' ? 200 : 100;
    const trace = artifacts.traces[Audit.DEFAULT_PASS];
    const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
    const metricData = {trace, devtoolsLog, settings: context.settings};
    let longTasks = [];
    try {
      longTasks = await LongTasks.request(metricData, context);
    } catch (e) {
      return auditNotApplicable.InvalidTiming;
    }

    if (!longTasks.length) {
      return auditNotApplicable.NoTasks;
    }

    const {timing: endTime} =
        await AdRequestTime.request(metricData, context);

    if (!(endTime > 0)) { // Handle NaN, etc.
      return auditNotApplicable.NoAdRelatedReq;
    }

    /** @type {TaskDetails[]} */ const blocking = [];
    for (const longTask of longTasks) {
      if (longTask.startTime > endTime ||
          longTask.duration < LONG_TASK_DUR_MS) {
        continue;
      }
      const scriptUrl = getAttributableUrl(longTask);
      if (scriptUrl && isAdScript(new URL(scriptUrl))) {
        continue;
      }

      const url = scriptUrl && new URL(scriptUrl);
      const displayUrl = url && (url.origin + url.pathname) || 'Other';

      blocking.push({
        // TODO(warrengm): Format the display URL so it fits on one line
        script: displayUrl,
        rawUrl: scriptUrl,
        startTime: longTask.startTime,
        endTime: longTask.endTime,
        duration: longTask.duration,
        isTopLevel: !longTask.parent,
      });
    }

    let filteredBlocking = Array.from(blocking);
    const taskLimit = 10;
    if (filteredBlocking.length > taskLimit) {
      // For the sake of brevity, we show at most 10 long tasks. If needed we
      // will filter tasks that are less actionable (child tasks or ones missing
      // attributable URLs).
      filteredBlocking = blocking
          .filter((b) => b.script !== 'Other' && b.isTopLevel)
      // Only show the longest tasks.
          .sort((a, b) => b.duration - a.duration)
          .splice(0, taskLimit)
          .sort((a, b) => a.startTime - b.startTime);
    }

    const blockedTime = filteredBlocking.reduce(
      (sum, t) => t.isTopLevel ? sum + t.duration : sum, 0);
    const failed = filteredBlocking.length > 0;
    return {
      score: failed ? 0 : 1,
      numericValue: blockedTime,
      numericUnit: 'millisecond',
      displayValue: failed ?
        str_(UIStrings.failureDisplayValue, {timeInMs: blockedTime}) :
        '',
      details: AdBlockingTasks.makeTableDetails(HEADINGS, filteredBlocking),
    };
  }
}

export default AdBlockingTasks;
export {UIStrings};


text:
module GroupedScope
  class SelfGroupping

    attr_reader :proxy_owner, :reflection

    delegate :quote_value, :columns_hash, :to => :proxy_class

    [].methods.each do |m|
      unless m =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/
        delegate m, :to => :grouped_proxy
      end
    end

    def initialize(proxy_owner)
      raise NoGroupIdError.new(proxy_owner) unless proxy_owner.class.column_names.include?('group_id')
      @proxy_owner = proxy_owner
    end

    def blank?
      proxy_owner.group_id.blank?
    end

    def present?
      !blank?
    end

    def ids
      grouped_scoped_ids.map(&primary_key.to_sym)
    end

    def ids_sql
      Arel.sql(grouped_scoped_ids.to_sql)
    end

    def quoted_ids
      ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
    end

    def with_reflection(reflection)
      @reflection = reflection
      yield
    ensure
      @reflection = nil
    end

    def respond_to?(method, include_private=false)
      super || proxy_class.grouped_reflections[method].present? || grouped_proxy.respond_to?(method, include_private)
    end

    protected

    def primary_key
      reflection ? reflection.association_primary_key : proxy_class.primary_key
    end

    def arel_group_id
      arel_table['group_id']
    end

    def arel_primary_key
      arel_table[primary_key]
    end

    def arel_table
      reflection ? Arel::Table.new(reflection.table_name) : proxy_class.arel_table
    end

    def grouped_proxy
      @grouped_proxy ||= grouped_scoped
    end

    def all_grouped?
      proxy_owner.all_grouped? rescue false
    end

    def grouped_scoped
      return proxy_class.scoped if all_grouped?
      proxy_class.where present? ? arel_group_id.eq(proxy_owner.group_id) : arel_primary_key.eq(proxy_owner.id)
    end

    def grouped_scoped_ids
      grouped_scoped.select(arel_primary_key)
    end

    def proxy_class
      proxy_owner.class
    end

    private

    def method_missing(method, *args)
      if proxy_class.grouped_reflections[method]
        if block_given?
          proxy_owner.send(:"grouped_scope_#{method}", *args)  { |*block_args| yield(*block_args) }
        else
          proxy_owner.send(:"grouped_scope_#{method}", *args)
        end
      elsif grouped_proxy.respond_to?(method)
        if block_given?
          grouped_proxy.send(method, *args)  { |*block_args| yield(*block_args) }
        else
          grouped_proxy.send(method, *args)
        end
      else
        super
      end
    end

  end
end


text:
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

/*
 * -- BASE STYLES --
 * Most of these are inherited from Base, but I want to change a few.
 */
body {
    line-height: 1.7em;
    color: #7f8c8d;
    font-size: 13px;
}

h1,
h2,
h3,
h4,
h5,
h6,
label {
    font-family: 'Lato', sans-serif;
    font-style: normal;
    font-variant: normal;
    font-weight: 300;
    color: #222222;
}

/* unvisited link */
a:link {
    color: #1f8dd6;
}

/* visited link */
a:visited {
    color: #1f8dd6;
}

/* mouse over link */
a:hover {
    color: #39B54A;
}

/* selected link */
a:active {
    color: #39B54A;
}

.pure-img-responsive {
    max-width: 100%;
    height: auto;
}

/*
 * -- LAYOUT STYLES --
 * These are some useful classes which I will need
 */
.l-box {
    padding: 1em;
}

.l-box-lrg {
    padding: 2em;
    border-bottom: 1px solid rgba(0,0,0,0.1);
}

.is-center {
    text-align: center;
}

/*
 * -- PURE FORM STYLES --
 * Style the form inputs and labels
 */
.pure-form label {
    margin: 1em 0 0;
    font-weight: bold;
    font-size: 100%;
}

.pure-form input[type] {
    border: 2px solid #ddd;
    box-shadow: none;
    font-size: 100%;
    width: 100%;
    margin-bottom: 1em;
}

/*
 * -- PURE BUTTON STYLES --
 * I want my pure-button elements to look a little different
 */
.pure-button {
    background-color: #1f8dd6;
    color: white;
    padding: 0.5em 2em;
    border-radius: 5px;
}

a.pure-button-primary {
    background: #1f8dd6;
    color: white;
    border-radius: 5px;
    font-size: 120%;
}

/*
 * -- MENU STYLES --
 * I want to customize how my .pure-menu looks at the top of the page
 */

.home-menu {
    padding: 0.5em;
    text-align: center;
    box-shadow: 0 1px 1px rgba(0,0,0, 0.10);

    font-family: 'Lato', sans-serif;
    font-style: normal;
    font-variant: normal;
    font-weight: 400;
    font-size: 80%;
}

.home-menu img{
    display: none;
}

.home-menu.pure-menu-open {
    background: #222222;
}
.pure-menu.pure-menu-open.pure-menu-fixed {
    /* Fixed menus normally have a border at the bottom. */
    border-bottom: none;
    /* I need a higher z-index here because of the scroll-over effect. */
    z-index: 4;
}

.home-menu .pure-menu-heading {
    color: #39B54A;
    font-family: 'Lato', sans-serif;
    font-style: normal;
    font-variant: normal;
    font-weight: 300;
    font-size: 120%;
}

.home-menu .pure-menu-selected a {
    color: white;
}

.home-menu a {
    color: #888888;
}

.home-menu li a:hover,
.home-menu li a:focus {
    background: none;
    border: none;
    color: #39B54A;
}

/*
 * -- SPLASH STYLES --
 * This is the blue top section that appears on the page.
 */

.splash-container {
    background: #222222;
    z-index: 1;
    overflow: hidden;
    /* The following styles are required for the "scroll-over" effect */
    width: 100%;
    height: 80%;
    top: 0;
    left: 0;
    position: fixed !important;
}

.splash {
    /* absolute center .splash within .splash-container */
    width: 80%;
    height: 50%;
    margin: auto;
    position: absolute;
    top: 20px; left: 0; bottom: 0; right: 0;
    text-align: center;
    text-transform: uppercase;
}

/* This is the main heading that appears on the blue section */
.splash-head {
    font-size: 20px;
    font-weight: bold;
    color: white;
    border: 6px solid white;
    padding: 1em 1.6em;
    font-weight: 100;
    border-radius: 5px;
    line-height: 1em;
}

/* This is the subheading that appears on the blue section */
.splash-subhead {
    font-family: 'Lato', sans-serif;
    font-style: normal;
    font-variant: normal;
    font-weight: 300;
    color: white;
    letter-spacing: 0.05em;
    opacity: 0.8;
    font-size: 120%;
}

/*
 * -- CONTENT STYLES --
 * This represents the content area (everything below the blue section)
 */
.content-wrapper {
    /* These styles are required for the "scroll-over" effect */
    position: absolute;
    top: 82%;
    width: 100%;
    min-height: 12%;
    z-index: 2;
    background: white;

}

/* This is the class used for the main content headers (<h2>) */
.content-head {
    font-weight: 400;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    margin: 2em 0 1em;
}

/* This is a modifier class used when the content-head is inside a ribbon */
.content-head-ribbon {
    color: white;
}

/* This is the class used for the content sub-headers (<h3>) */
.content-subhead {
    color: #1f8dd6;
}
    .content-subhead i {
        margin-right: 7px;
    }

/* This is the class used for the dark-background areas. */
.ribbon {
    background: #39B54A;
    color: #222222;
}

/* This is the class used for the footer */
.footer {
    font-family: 'Lato', sans-serif;
    font-style: normal;
    font-variant: normal;
    font-weight: 300;
    background: #222222;
}

/*
 * -- TABLET (AND UP) MEDIA QUERIES --
 * On tablets and other medium-sized devices, we want to customize some
 * of the mobile styles.
 */
@media (min-width: 48em) {

    /* We increase the body font size */
    body {
        font-size: 16px;
    }
    /* We want to give the content area some more padding */
    .content {
        padding: 1em;
    }

    /* We can align the menu header to the left, but float the
    menu items to the right. */
    .home-menu {
        text-align: left;
    }
        .home-menu ul {
            float: right;
        }

    /* We increase the height of the splash-container */
/*    .splash-container {
        height: 500px;
    }*/

    /* We decrease the width of the .splash, since we have more width
    to work with */
    .splash {
        width: 50%;
        height: 50%;
    }

    .splash-head {
        font-size: 250%;
    }

    /* We remove the border-separator assigned to .l-box-lrg */
    .l-box-lrg {
        border: none;
    }

    .home-menu img{
        display: inline;
    }

}

/*
 * -- DESKTOP (AND UP) MEDIA QUERIES --
 * On desktops and other large devices, we want to over-ride some
 * of the mobile and tablet styles.
 */
@media (min-width: 78em) {
    /* We increase the header font size even more */
    .splash-head {
        font-size: 300%;
    }

    .home-menu {
        font-weight: 400;
        font-size: 120%;
    }

    .home-menu img{
        display: inline;
    }
}


text:
import { util, platform } from "carbon-api";
let style = require("./scroller.optional.css") as any;

let isEnabled = platform.deviceType !== "mobile";
if (isEnabled) {
    style.use();
}

export type AntiscrollOptions = {
    initialDisplay: boolean;
    autoHide: boolean;
    autoHideTimeout: number;
    x: boolean;
    y: boolean;
    innerSelector: string | HTMLElement;
    debug: boolean;
}

const DefaultOptions: AntiscrollOptions = {
    autoHideTimeout: 1500,
    autoHide: true,
    initialDisplay: false,
    x: true,
    y: true,
    innerSelector: ".antiscroll-inner",
    debug: false
};

const MarginTop = 2;
const Padding = 2;

let index = 0;
const registry: {[key: string]: Antiscroll} = {};

export default class Antiscroll {
    private index: number;
    private horizontal: HorizontalScrollbar;
    private vertical: VerticalScrollbar;

    public inner: HTMLElement;
    public options: AntiscrollOptions;
    public windowScroll: boolean;
    public cache: {
        scrollPosition: number;
        diff: number;
    };

    constructor(public wrapperElement: HTMLElement, options: Partial<AntiscrollOptions>) {
        this.options = Object.assign({}, DefaultOptions, options);

        if (!isEnabled) {
            return;
        }

        if (wrapperElement.dataset["antiscroll"]) {
            let existing = registry[wrapperElement.dataset["antiscroll"]];
            existing.destroy();
        }

        this.cache = {
            scrollPosition: 0,
            diff: 0
        };

        this.windowScroll = wrapperElement === document.documentElement;

        // Reads "0" as an argument
        this.inner = this.windowScroll
            ? document.documentElement
            : typeof this.options.innerSelector === "string"
            ? this.wrapperElement.querySelectorAll(this.options.innerSelector)[0] as HTMLElement
            : this.options.innerSelector;

        if (options.debug) {
            console.group('Antiscroll');
            console.log('Inner element:', this.inner);
            console.log('Content width:', this.inner.clientWidth);
            console.log('Content height:', this.inner.clientHeight);
        }

        this.refresh();

        let newIndex = index++;
        registry[newIndex] = this;
        this.index = newIndex;
        this.wrapperElement.dataset["antiscroll"] = newIndex + "";
    }

    refresh() {
        if (!isEnabled) {
            return;
        }

        if (this.options.debug) {
            console.group('Antiscroll.refresh');
        }

        let rect = this.wrapperElement.getBoundingClientRect();
        var needHScroll = this.inner.scrollWidth > rect.width + (this.options.y ? scrollbarSize() : 0);
        var needVScroll = this.inner.scrollHeight > rect.height + (this.options.x ? scrollbarSize() : 0);

        if (this.options.debug) {
            console.log('Needs horizontal scroll:', needHScroll);
            console.log('Needs vertical scroll:', needVScroll);
        }

        if (this.options.x) {
            if (!this.horizontal && needHScroll) {
                this.horizontal = new HorizontalScrollbar(this);
            } else if (this.horizontal && !needHScroll) {
                this.horizontal.destroy();
                this.horizontal = null;
            } else if (this.horizontal) {
                this.horizontal.update();
            }
        }

        if (this.options.y) {
            if (!this.vertical && needVScroll) {
                this.vertical = new VerticalScrollbar(this);
            } else if (this.vertical && !needVScroll) {
                this.vertical.destroy();
                this.vertical = null;
            } else if (this.vertical) {
                this.vertical.update();
            }
        }

        if (this.options.debug) {
            console.groupEnd();
        }

        return 'Scrollbars have been refreshed.';
    }

    destroy() {
        if (!isEnabled) {
            return;
        }

        if (this.options.debug) {
            console.group('Antiscroll.destroy');
        }

        if (this.horizontal) {
            this.horizontal.destroy();
            this.horizontal = null;
        }

        if (this.vertical) {
            this.vertical.destroy();
            this.vertical = null;
        }

        if (this.options.debug) {
            console.groupEnd();
        }

        //if scroll container is re-rendered with other items and is smaller, it should resize
        if (this.inner && !this.windowScroll) {
            delete this.inner.style.height;
            delete this.inner.style.width;
        }

        delete registry[this.index];
        delete this.wrapperElement.dataset["antiscroll"];
    }
}

abstract class Scrollbar {
    hiding: any;
    startClientX: number;
    startClientY: number;
    startScrollTop: number;
    startScrollLeft: number;
    hideDebounced: () => any;
    //innerPaneMouseWheelListener: any;
    innerPaneScrollListener: any;
    mousedownListener: any;
    elementMousemoveListener: any;
    documentMousemoveListener: any;
    mouseleaveListener: any;
    mouseenterListener: any;
    shown: boolean;
    dragging: boolean;
    innerEl: Element;

    constructor(protected pane: Antiscroll, protected el: HTMLElement) {
        this.pane.wrapperElement.appendChild(this.el);
        this.innerEl = this.pane.inner;

        this.dragging = false;
        this.shown = false;

        this.documentMousemoveListener = this.documentMousemove.bind(this);
        this.elementMousemoveListener = this.elementMousemove.bind(this);

        // hovering
        this.mouseenterListener = this.mouseenter.bind(this);
        this.mouseleaveListener = this.mouseleave.bind(this);
        this.pane.wrapperElement.addEventListener("mouseenter", this.mouseenterListener);
        this.pane.wrapperElement.addEventListener("mouseleave", this.mouseleaveListener);

        // dragging
        this.mousedownListener = this.mousedown.bind(this);
        this.el.addEventListener("mousedown", this.mousedownListener);

        // scrolling
        this.innerPaneScrollListener = this.scroll.bind(this);
        if (this.pane.windowScroll) {
            window.addEventListener("scroll", this.innerPaneScrollListener);
            window.addEventListener("mousemove", this.elementMousemoveListener);
        }
        else {
            this.pane.inner.addEventListener("scroll", this.innerPaneScrollListener);
            this.el.addEventListener("mousemove", this.elementMousemoveListener);
        }

        // show
        this.hideDebounced = util.debounce(this.hide.bind(this), this.pane.options.autoHideTimeout);
    }

    destroy() {
        this.el.remove();
        if (this.pane.windowScroll) {
            window.removeEventListener("scroll", this.innerPaneScrollListener);
            window.removeEventListener("mousemove", this.elementMousemoveListener);
        }
        else {
            this.pane.inner.removeEventListener('scroll', this.innerPaneScrollListener);
            this.el.removeEventListener("mousemove", this.elementMousemoveListener);
        }

        //this.pane.inner.removeEventListener('mousewheel', this.innerPaneMouseWheelListener);

        this.pane.wrapperElement.removeEventListener("mouseenter", this.mouseenterListener);
        this.pane.wrapperElement.removeEventListener("mouseleave", this.mouseleaveListener);
        this.el.removeEventListener("mousedown", this.mousedownListener);
    }

    mouseenter() {
        this.show();
        this.hideDebounced();
    }

    mouseleave() {
        if (!this.dragging) {
            if (this.pane.options.autoHide) {
                this.hide();
            }
        }
    }

    scroll() {
        if (!this.shown) {
            this.show();
        }

        if (!this.dragging) {
            this.hideDebounced();
        }

        this.update();
    }

    abstract update();
    abstract elementMousemove(event: MouseEvent);
    abstract documentMousemove(event: MouseEvent);

    mousedown(event: MouseEvent) {
        event.preventDefault();

        this.dragging = true;

        this.startClientY = event.clientY;
        this.startClientX = event.clientX;

        this.startScrollTop = this.innerEl.scrollTop;
        this.startScrollLeft = this.innerEl.scrollLeft;

        // prevent crazy selections on IE
        this.el.ownerDocument.onselectstart = function () {
            return false;
        };

        // make scrollbar draggable
        var onMouseUp = () => {
            this.dragging = false;
            this.el.ownerDocument.onselectstart = null;

            this.el.ownerDocument.removeEventListener("mousemove", this.documentMousemoveListener);
            this.el.ownerDocument.removeEventListener("mouseup", onMouseUp);
            this.hideDebounced();
        };

        this.el.ownerDocument.addEventListener("mousemove", this.documentMousemoveListener);
        this.el.ownerDocument.addEventListener("mouseup", onMouseUp);
    }

    show() {
        if (!this.shown && this.update()) {
            this.el.classList.add('antiscroll-scrollbar-shown');
            if (this.hiding) {
                clearTimeout(this.hiding);
                this.hiding = 0;
            }
            this.shown = true;
        }
    }

    hide() {
        if (this.shown) {
            // check for dragging
            this.el.classList.remove('antiscroll-scrollbar-shown');
            this.shown = false;
            if (this.hiding) {
                clearTimeout(this.hiding);
                this.hiding = 0;
            }
        }
    }
}

class HorizontalScrollbar extends Scrollbar {
    constructor(pane: Antiscroll) {
        let div = document.createElement("div");
        div.classList.add("antiscroll-scrollbar");
        div.classList.add("antiscroll-scrollbar-horizontal");
        pane.wrapperElement.appendChild(div);

        super(pane, div);
    }

    update() {
        var paneWidth = this.pane.wrapperElement.getBoundingClientRect().width;
        var trackWidth = paneWidth - Padding * 2;
        var innerEl = this.pane.inner;

        this.el.style.width = trackWidth * paneWidth / innerEl.scrollWidth + "px";
        this.el.style.left = trackWidth * innerEl.scrollLeft / innerEl.scrollWidth + "px";

        return paneWidth < innerEl.scrollWidth;
    }
    documentMousemove(event: MouseEvent) {
        var paneWidth = this.pane.wrapperElement.getBoundingClientRect().width;
        let scrollDelta = event.clientX - this.startClientX;
        let realDelta = this.innerEl.scrollWidth/paneWidth * scrollDelta;

        this.innerEl.scrollLeft = Math.round(this.startScrollLeft + realDelta);
    }
    elementMousemove(event: MouseEvent) {
        let rect = this.pane.wrapperElement.getBoundingClientRect();
        if (event.clientY > rect.bottom - size) {
            this.show();
        }
        else if (this.shown) {
            this.hideDebounced();
        }
    }
}

class VerticalScrollbar extends Scrollbar {
    constructor(pane: Antiscroll) {
        let div = document.createElement("div");
        div.classList.add("antiscroll-scrollbar");
        div.classList.add("antiscroll-scrollbar-vertical");
        div.style.marginTop = MarginTop + "px";
        pane.wrapperElement.appendChild(div);

        super(pane, div);
    }

    update() {
        if (this.pane.options.debug) {
            console.group('Scrollbar.Vertical.update');
        }

        var paneHeight = this.pane.wrapperElement.getBoundingClientRect().height;
        var trackHeight = paneHeight - Padding * 2;
        var innerEl = this.innerEl;

        var barHeight = trackHeight * paneHeight / innerEl.scrollHeight;
        barHeight = barHeight < 20 ? 20 : barHeight;

        if (this.pane.options.debug) {
            console.groupCollapsed('Measurements');
            console.log('Content height: ', innerEl.scrollHeight);
            console.log('Container height:', paneHeight);
            console.log('Track height:', trackHeight);
            console.log('Scrollbar height:', barHeight);
            console.log('Scrollable track:', trackHeight - barHeight);
            console.groupEnd();
        }

        var topPos = trackHeight * innerEl.scrollTop / innerEl.scrollHeight;
        // If scrollbar would go beyond boundaries
        if ((topPos + barHeight) > trackHeight) {
            if (this.pane.options.debug) {
                console.warn('Scrollbar goes beyond boundaries. Offset will be adjusted.');
            }
            var overlap = (topPos + barHeight) - trackHeight;
            topPos = topPos - overlap;
        }

        if (this.pane.windowScroll) {
            topPos += innerEl.scrollTop;
        }

        topPos = Math.round(topPos);

        if (this.pane.options.debug) {
            console.log('Scrolled track: ' + topPos + ' / ' + trackHeight);
            console.log('Scrolled content: ' + innerEl.scrollTop + ' / ' + innerEl.scrollHeight);
            this.pane.cache.diff = topPos - this.pane.cache.scrollPosition;
            console.groupEnd();
        }

        this.el.style.height = barHeight + "px";
        this.el.style.top = topPos + "px";

        this.pane.cache.scrollPosition = topPos;

        return paneHeight < innerEl.scrollHeight;
    }
    documentMousemove(event: MouseEvent) {
        if (this.pane.options.debug) {
            console.group('Scrollbar.Vertical.mousemove');
        }

        var paneHeight = this.pane.wrapperElement.getBoundingClientRect().height;
        let scrollDelta = event.clientY - this.startClientY;
        let realDelta = this.innerEl.scrollHeight/paneHeight * scrollDelta;

        this.innerEl.scrollTop = Math.round(this.startScrollTop + realDelta);

        if (this.pane.options.debug) {
            console.groupEnd();
        }
    }
    elementMousemove(event: MouseEvent) {
        let rect = this.pane.wrapperElement.getBoundingClientRect();
        if (event.clientX > rect.right - size) {
            this.show();
        }
        else if (this.shown) {
            this.hideDebounced();
        }
    }
}

var size: number = undefined;

function scrollbarSize() {
    if (size === undefined) {
        var div = document.createElement("div");
        div.classList.add("antiscroll-inner");
        div.style.width = "50px";
        div.style.height = "50px";
        div.style.overflowY = "scroll";
        div.style.position = "absolute";
        div.style.top = "-200px";
        div.style.left = "-200px";

        let inner = document.createElement("div");
        inner.style.height = "100px";
        inner.style.width = "100%";
        div.appendChild(inner);

        document.body.appendChild(div);
        var w1 = div.offsetWidth;
        var w2 = inner.offsetWidth;
        div.remove();

        size = w1 - w2;
    }

    return size;
}


text:
"""
Regularized Unbalanced OT
"""

# Author: Hicham Janati <hicham.janati@inria.fr>
# License: MIT License

from __future__ import division
import warnings
import numpy as np
from scipy.special import logsumexp

# from .utils import unif, dist

def sinkhorn_unbalanced(a, b, M, reg, reg_m, method='sinkhorn', numItermax=1000,
                        stopThr=1e-6, verbose=False, log=False, **kwargs):
    r"""
    Solve the unbalanced entropic regularization optimal transport problem
    and return the OT plan

    The function solves the following optimization problem:

    .. math::
        W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)

        s.t.
             \gamma\geq 0
    where :

    - M is the (dim_a, dim_b) metric cost matrix
    - :math:`\Omega` is the entropic regularization
        term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
    - a and b are source and target unbalanced distributions
    - KL is the Kullback-Leibler divergence

    The algorithm used for solving the problem is the generalized
        Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

    Parameters
    ----------
    a : np.ndarray (dim_a,)
        Unnormalized histogram of dimension dim_a
    b : np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)
        One or multiple unnormalized histograms of dimension dim_b
        If many, compute all the OT distances (a, b_i)
    M : np.ndarray (dim_a, dim_b)
        loss matrix
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    method : str
        method used for the solver either 'sinkhorn',  'sinkhorn_stabilized' or
        'sinkhorn_reg_scaling', see those function for specific parameters
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (>0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    if n_hists == 1:
        gamma : (dim_a x dim_b) ndarray
            Optimal transportation matrix for the given parameters
        log : dict
            log dictionary returned only if `log` is `True`
    else:
        ot_distance : (n_hists,) ndarray
            the OT distance between `a` and each of the histograms `b_i`
        log : dict
            log dictionary returned only if `log` is `True`

    Examples
    --------

    >>> import ot
    >>> a=[.5, .5]
    >>> b=[.5, .5]
    >>> M=[[0., 1.], [1., 0.]]
    >>> ot.sinkhorn_unbalanced(a, b, M, 1, 1)
    array([[0.51122823, 0.18807035],
           [0.18807035, 0.51122823]])

    References
    ----------

    .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
        Transport, Advances in Neural Information Processing Systems
        (NIPS) 26, 2013

    .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for
        Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.

    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprint
        arXiv:1607.05816.

    .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
        Learning with a Wasserstein Loss,  Advances in Neural Information
        Processing Systems (NIPS) 2015

    See Also
    --------
    ot.unbalanced.sinkhorn_knopp_unbalanced : Unbalanced Classic Sinkhorn [10]
    ot.unbalanced.sinkhorn_stabilized_unbalanced:
        Unbalanced Stabilized sinkhorn [9][10]
    ot.unbalanced.sinkhorn_reg_scaling_unbalanced:
        Unbalanced Sinkhorn with epslilon scaling [9][10]

    """

    if method.lower() == 'sinkhorn':
        return sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m,
                                         numItermax=numItermax,
                                         stopThr=stopThr, verbose=verbose,
                                         log=log, **kwargs)

    elif method.lower() == 'sinkhorn_stabilized':
        return sinkhorn_stabilized_unbalanced(a, b, M, reg, reg_m,
                                              numItermax=numItermax,
                                              stopThr=stopThr,
                                              verbose=verbose,
                                              log=log, **kwargs)
    elif method.lower() in ['sinkhorn_reg_scaling']:
        warnings.warn('Method not implemented yet. Using classic Sinkhorn Knopp')
        return sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m,
                                         numItermax=numItermax,
                                         stopThr=stopThr, verbose=verbose,
                                         log=log, **kwargs)
    else:
        raise ValueError("Unknown method '%s'." % method)

def sinkhorn_unbalanced2(a, b, M, reg, reg_m, method='sinkhorn',
                         numItermax=1000, stopThr=1e-6, verbose=False,
                         log=False, **kwargs):
    r"""
    Solve the entropic regularization unbalanced optimal transport problem and
    return the loss

    The function solves the following optimization problem:

    .. math::
        W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)

        s.t.
             \gamma\geq 0
    where :

    - M is the (dim_a, dim_b) metric cost matrix
    - :math:`\Omega` is the entropic regularization term
        :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
    - a and b are source and target unbalanced distributions
    - KL is the Kullback-Leibler divergence

    The algorithm used for solving the problem is the generalized
    Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

    Parameters
    ----------
    a : np.ndarray (dim_a,)
        Unnormalized histogram of dimension dim_a
    b : np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)
        One or multiple unnormalized histograms of dimension dim_b
        If many, compute all the OT distances (a, b_i)
    M : np.ndarray (dim_a, dim_b)
        loss matrix
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    method : str
        method used for the solver either 'sinkhorn',  'sinkhorn_stabilized' or
        'sinkhorn_reg_scaling', see those function for specific parameters
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (>0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    ot_distance : (n_hists,) ndarray
        the OT distance between `a` and each of the histograms `b_i`
    log : dict
        log dictionary returned only if `log` is `True`

    Examples
    --------

    >>> import ot
    >>> a=[.5, .10]
    >>> b=[.5, .5]
    >>> M=[[0., 1.],[1., 0.]]
    >>> ot.unbalanced.sinkhorn_unbalanced2(a, b, M, 1., 1.)
    array([0.31912866])

    References
    ----------

    .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
        Transport, Advances in Neural Information Processing Systems
        (NIPS) 26, 2013

    .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for
        Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.

    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprint
        arXiv:1607.05816.

    .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
        Learning with a Wasserstein Loss,  Advances in Neural Information
        Processing Systems (NIPS) 2015

    See Also
    --------
    ot.unbalanced.sinkhorn_knopp : Unbalanced Classic Sinkhorn [10]
    ot.unbalanced.sinkhorn_stabilized: Unbalanced Stabilized sinkhorn [9][10]
    ot.unbalanced.sinkhorn_reg_scaling: Unbalanced Sinkhorn with epslilon scaling [9][10]

    """
    b = np.asarray(b, dtype=np.float64)
    if len(b.shape) < 2:
        b = b[:, None]
    if method.lower() == 'sinkhorn':
        return sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m,
                                         numItermax=numItermax,
                                         stopThr=stopThr, verbose=verbose,
                                         log=log, **kwargs)

    elif method.lower() == 'sinkhorn_stabilized':
        return sinkhorn_stabilized_unbalanced(a, b, M, reg, reg_m,
                                              numItermax=numItermax,
                                              stopThr=stopThr,
                                              verbose=verbose,
                                              log=log, **kwargs)
    elif method.lower() in ['sinkhorn_reg_scaling']:
        warnings.warn('Method not implemented yet. Using classic Sinkhorn Knopp')
        return sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m,
                                         numItermax=numItermax,
                                         stopThr=stopThr, verbose=verbose,
                                         log=log, **kwargs)
    else:
        raise ValueError('Unknown method %s.' % method)

def sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m, numItermax=1000,
                              stopThr=1e-6, verbose=False, log=False, **kwargs):
    r"""
    Solve the entropic regularization unbalanced optimal transport problem and return the loss

    The function solves the following optimization problem:

    .. math::
        W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + \reg_m KL(\gamma 1, a) + \reg_m KL(\gamma^T 1, b)

        s.t.
             \gamma\geq 0
    where :

    - M is the (dim_a, dim_b) metric cost matrix
    - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
    - a and b are source and target unbalanced distributions
    - KL is the Kullback-Leibler divergence

    The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

    Parameters
    ----------
    a : np.ndarray (dim_a,)
        Unnormalized histogram of dimension dim_a
    b : np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)
        One or multiple unnormalized histograms of dimension dim_b
        If many, compute all the OT distances (a, b_i)
    M : np.ndarray (dim_a, dim_b)
        loss matrix
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (> 0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    if n_hists == 1:
        gamma : (dim_a x dim_b) ndarray
            Optimal transportation matrix for the given parameters
        log : dict
            log dictionary returned only if `log` is `True`
    else:
        ot_distance : (n_hists,) ndarray
            the OT distance between `a` and each of the histograms `b_i`
        log : dict
            log dictionary returned only if `log` is `True`
    Examples
    --------

    >>> import ot
    >>> a=[.5, .5]
    >>> b=[.5, .5]
    >>> M=[[0., 1.],[1., 0.]]
    >>> ot.unbalanced.sinkhorn_knopp_unbalanced(a, b, M, 1., 1.)
    array([[0.51122823, 0.18807035],
           [0.18807035, 0.51122823]])

    References
    ----------

    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprint
        arXiv:1607.05816.

    .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
        Learning with a Wasserstein Loss,  Advances in Neural Information
        Processing Systems (NIPS) 2015

    See Also
    --------
    ot.lp.emd : Unregularized OT
    ot.optim.cg : General regularized OT

    """

    a = np.asarray(a, dtype=np.float64)
    b = np.asarray(b, dtype=np.float64)
    M = np.asarray(M, dtype=np.float64)

    dim_a, dim_b = M.shape

    if len(a) == 0:
        a = np.ones(dim_a, dtype=np.float64) / dim_a
    if len(b) == 0:
        b = np.ones(dim_b, dtype=np.float64) / dim_b

    if len(b.shape) > 1:
        n_hists = b.shape[1]
    else:
        n_hists = 0

    if log:
        log = {'err': []}

    # we assume that no distances are null except those of the diagonal of
    # distances
    if n_hists:
        u = np.ones((dim_a, 1)) / dim_a
        v = np.ones((dim_b, n_hists)) / dim_b
        a = a.reshape(dim_a, 1)
    else:
        u = np.ones(dim_a) / dim_a
        v = np.ones(dim_b) / dim_b

    # Next 3 lines equivalent to K= np.exp(-M/reg), but faster to compute
    K = np.empty(M.shape, dtype=M.dtype)
    np.divide(M, -reg, out=K)
    np.exp(K, out=K)

    fi = reg_m / (reg_m + reg)

    err = 1.

    for i in range(numItermax):
        uprev = u
        vprev = v

        Kv = K.dot(v)
        u = (a / Kv) ** fi
        Ktu = K.T.dot(u)
        v = (b / Ktu) ** fi

        if (np.any(Ktu == 0.)
                or np.any(np.isnan(u)) or np.any(np.isnan(v))
                or np.any(np.isinf(u)) or np.any(np.isinf(v))):
            # we have reached the machine precision
            # come back to previous solution and quit loop
            warnings.warn('Numerical errors at iteration %s' % i)
            u = uprev
            v = vprev
            break

        err_u = abs(u - uprev).max() / max(abs(u).max(), abs(uprev).max(), 1.)
        err_v = abs(v - vprev).max() / max(abs(v).max(), abs(vprev).max(), 1.)
        err = 0.5 * (err_u + err_v)
        if log:
            log['err'].append(err)
            if verbose:
                if i % 50 == 0:
                    print(
                        '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
                print('{:5d}|{:8e}|'.format(i, err))
        if err < stopThr:
            break

    if log:
        log['logu'] = np.log(u + 1e-300)
        log['logv'] = np.log(v + 1e-300)

    if n_hists:  # return only loss
        res = np.einsum('ik,ij,jk,ij->k', u, K, v, M)
        if log:
            return res, log
        else:
            return res

    else:  # return OT matrix

        if log:
            return u[:, None] * K * v[None, :], log
        else:
            return u[:, None] * K * v[None, :]

def sinkhorn_stabilized_unbalanced(a, b, M, reg, reg_m, tau=1e5, numItermax=1000,
                                   stopThr=1e-6, verbose=False, log=False,
                                   **kwargs):
    r"""
    Solve the entropic regularization unbalanced optimal transport
    problem and return the loss

    The function solves the following optimization problem using log-domain
    stabilization as proposed in [10]:

    .. math::
        W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)

        s.t.
             \gamma\geq 0
    where :

    - M is the (dim_a, dim_b) metric cost matrix
    - :math:`\Omega` is the entropic regularization
        term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
    - a and b are source and target unbalanced distributions
    - KL is the Kullback-Leibler divergence

    The algorithm used for solving the problem is the generalized
    Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

    Parameters
    ----------
    a : np.ndarray (dim_a,)
        Unnormalized histogram of dimension dim_a
    b : np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)
        One or multiple unnormalized histograms of dimension dim_b
        If many, compute all the OT distances (a, b_i)
    M : np.ndarray (dim_a, dim_b)
        loss matrix
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    tau : float
        thershold for max value in u or v for log scaling
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (>0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    if n_hists == 1:
        gamma : (dim_a x dim_b) ndarray
            Optimal transportation matrix for the given parameters
        log : dict
            log dictionary returned only if `log` is `True`
    else:
        ot_distance : (n_hists,) ndarray
            the OT distance between `a` and each of the histograms `b_i`
        log : dict
            log dictionary returned only if `log` is `True`
    Examples
    --------

    >>> import ot
    >>> a=[.5, .5]
    >>> b=[.5, .5]
    >>> M=[[0., 1.],[1., 0.]]
    >>> ot.unbalanced.sinkhorn_stabilized_unbalanced(a, b, M, 1., 1.)
    array([[0.51122823, 0.18807035],
           [0.18807035, 0.51122823]])

    References
    ----------

    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

    .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
        Learning with a Wasserstein Loss,  Advances in Neural Information
        Processing Systems (NIPS) 2015

    See Also
    --------
    ot.lp.emd : Unregularized OT
    ot.optim.cg : General regularized OT

    """

    a = np.asarray(a, dtype=np.float64)
    b = np.asarray(b, dtype=np.float64)
    M = np.asarray(M, dtype=np.float64)

    dim_a, dim_b = M.shape

    if len(a) == 0:
        a = np.ones(dim_a, dtype=np.float64) / dim_a
    if len(b) == 0:
        b = np.ones(dim_b, dtype=np.float64) / dim_b

    if len(b.shape) > 1:
        n_hists = b.shape[1]
    else:
        n_hists = 0

    if log:
        log = {'err': []}

    # we assume that no distances are null except those of the diagonal of
    # distances
    if n_hists:
        u = np.ones((dim_a, n_hists)) / dim_a
        v = np.ones((dim_b, n_hists)) / dim_b
        a = a.reshape(dim_a, 1)
    else:
        u = np.ones(dim_a) / dim_a
        v = np.ones(dim_b) / dim_b

    # print(reg)
    # Next 3 lines equivalent to K= np.exp(-M/reg), but faster to compute
    K = np.empty(M.shape, dtype=M.dtype)
    np.divide(M, -reg, out=K)
    np.exp(K, out=K)

    fi = reg_m / (reg_m + reg)

    cpt = 0
    err = 1.
    alpha = np.zeros(dim_a)
    beta = np.zeros(dim_b)
    while (err > stopThr and cpt < numItermax):
        uprev = u
        vprev = v

        Kv = K.dot(v)
        f_alpha = np.exp(- alpha / (reg + reg_m))
        f_beta = np.exp(- beta / (reg + reg_m))

        if n_hists:
            f_alpha = f_alpha[:, None]
            f_beta = f_beta[:, None]
        u = ((a / (Kv + 1e-16)) ** fi) * f_alpha
        Ktu = K.T.dot(u)
        v = ((b / (Ktu + 1e-16)) ** fi) * f_beta
        absorbing = False
        if (u > tau).any() or (v > tau).any():
            absorbing = True
            if n_hists:
                alpha = alpha + reg * np.log(np.max(u, 1))
                beta = beta + reg * np.log(np.max(v, 1))
            else:
                alpha = alpha + reg * np.log(np.max(u))
                beta = beta + reg * np.log(np.max(v))
            K = np.exp((alpha[:, None] + beta[None, :] -
                        M) / reg)
            v = np.ones_like(v)
        Kv = K.dot(v)

        if (np.any(Ktu == 0.)
                or np.any(np.isnan(u)) or np.any(np.isnan(v))
                or np.any(np.isinf(u)) or np.any(np.isinf(v))):
            # we have reached the machine precision
            # come back to previous solution and quit loop
            warnings.warn('Numerical errors at iteration %s' % cpt)
            u = uprev
            v = vprev
            break
        if (cpt % 10 == 0 and not absorbing) or cpt == 0:
            # we can speed up the process by checking for the error only all
            # the 10th iterations
            err = abs(u - uprev).max() / max(abs(u).max(), abs(uprev).max(),
                                             1.)
            if log:
                log['err'].append(err)
            if verbose:
                if cpt % 200 == 0:
                    print(
                        '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
                print('{:5d}|{:8e}|'.format(cpt, err))
        cpt = cpt + 1

    if err > stopThr:
        warnings.warn("Stabilized Unbalanced Sinkhorn did not converge." +
                      "Try a larger entropy `reg` or a lower mass `reg_m`." +
                      "Or a larger absorption threshold `tau`.")
    if n_hists:
        logu = alpha[:, None] / reg + np.log(u)
        logv = beta[:, None] / reg + np.log(v)
    else:
        logu = alpha / reg + np.log(u)
        logv = beta / reg + np.log(v)
    if log:
        log['logu'] = logu
        log['logv'] = logv
    if n_hists:  # return only loss
        res = logsumexp(np.log(M + 1e-100)[:, :, None] + logu[:, None, :] +
                        logv[None, :, :] - M[:, :, None] / reg, axis=(0, 1))
        res = np.exp(res)
        if log:
            return res, log
        else:
            return res

    else:  # return OT matrix
        ot_matrix = np.exp(logu[:, None] + logv[None, :] - M / reg)
        if log:
            return ot_matrix, log
        else:
            return ot_matrix

def barycenter_unbalanced_stabilized(A, M, reg, reg_m, weights=None, tau=1e3,
                                     numItermax=1000, stopThr=1e-6,
                                     verbose=False, log=False):
    r"""Compute the entropic unbalanced wasserstein barycenter of A with stabilization.

     The function solves the following optimization problem:

    .. math::
       \mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)

    where :

    - :math:`Wu_{reg}(\cdot,\cdot)` is the unbalanced entropic regularized
        Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced)
    - :math:`\mathbf{a}_i` are training distributions in the columns of
        matrix :math:`\mathbf{A}`
    - reg and :math:`\mathbf{M}` are respectively the regularization term and
        the cost matrix for OT
    - reg_mis the marginal relaxation hyperparameter
        The algorithm used for solving the problem is the generalized
        Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

    Parameters
    ----------
    A : np.ndarray (dim, n_hists)
        `n_hists` training distributions a_i of dimension dim
    M : np.ndarray (dim, dim)
        ground metric matrix for OT.
    reg : float
        Entropy regularization term > 0
    reg_m : float
        Marginal relaxation term > 0
    tau : float
        Stabilization threshold for log domain absorption.
    weights : np.ndarray (n_hists,) optional
        Weight of each distribution (barycentric coodinates)
        If None, uniform weights are used.
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (> 0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    a : (dim,) ndarray
        Unbalanced Wasserstein barycenter
    log : dict
        log dictionary return only if log==True in parameters

    References
    ----------

    .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré,
        G. (2015). Iterative Bregman projections for regularized transportation
        problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprint
        arXiv:1607.05816.

    """
    dim, n_hists = A.shape
    if weights is None:
        weights = np.ones(n_hists) / n_hists
    else:
        assert(len(weights) == A.shape[1])

    if log:
        log = {'err': []}

    fi = reg_m / (reg_m + reg)

    u = np.ones((dim, n_hists)) / dim
    v = np.ones((dim, n_hists)) / dim

    # print(reg)
    # Next 3 lines equivalent to K= np.exp(-M/reg), but faster to compute
    K = np.empty(M.shape, dtype=M.dtype)
    np.divide(M, -reg, out=K)
    np.exp(K, out=K)

    fi = reg_m / (reg_m + reg)

    cpt = 0
    err = 1.
    alpha = np.zeros(dim)
    beta = np.zeros(dim)
    q = np.ones(dim) / dim
    for i in range(numItermax):
        qprev = q.copy()
        Kv = K.dot(v)
        f_alpha = np.exp(- alpha / (reg + reg_m))
        f_beta = np.exp(- beta / (reg + reg_m))
        f_alpha = f_alpha[:, None]
        f_beta = f_beta[:, None]
        u = ((A / (Kv + 1e-16)) ** fi) * f_alpha
        Ktu = K.T.dot(u)
        q = (Ktu ** (1 - fi)) * f_beta
        q = q.dot(weights) ** (1 / (1 - fi))
        Q = q[:, None]
        v = ((Q / (Ktu + 1e-16)) ** fi) * f_beta
        absorbing = False
        if (u > tau).any() or (v > tau).any():
            absorbing = True
            alpha = alpha + reg * np.log(np.max(u, 1))
            beta = beta + reg * np.log(np.max(v, 1))
            K = np.exp((alpha[:, None] + beta[None, :] -
                        M) / reg)
            v = np.ones_like(v)
        Kv = K.dot(v)
        if (np.any(Ktu == 0.)
                or np.any(np.isnan(u)) or np.any(np.isnan(v))
                or np.any(np.isinf(u)) or np.any(np.isinf(v))):
            # we have reached the machine precision
            # come back to previous solution and quit loop
            warnings.warn('Numerical errors at iteration %s' % cpt)
            q = qprev
            break
        if (i % 10 == 0 and not absorbing) or i == 0:
            # we can speed up the process by checking for the error only all
            # the 10th iterations
            err = abs(q - qprev).max() / max(abs(q).max(),
                                             abs(qprev).max(), 1.)
            if log:
                log['err'].append(err)
            if verbose:
                if i % 50 == 0:
                    print(
                        '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
                print('{:5d}|{:8e}|'.format(i, err))
            if err < stopThr:
                break

    if err > stopThr:
        warnings.warn("Stabilized Unbalanced Sinkhorn did not converge." +
                      "Try a larger entropy `reg` or a lower mass `reg_m`." +
                      "Or a larger absorption threshold `tau`.")
    if log:
        log['niter'] = i
        log['logu'] = np.log(u + 1e-300)
        log['logv'] = np.log(v + 1e-300)
        return q, log
    else:
        return q

def barycenter_unbalanced_sinkhorn(A, M, reg, reg_m, weights=None,
                                   numItermax=1000, stopThr=1e-6,
                                   verbose=False, log=False):
    r"""Compute the entropic unbalanced wasserstein barycenter of A.

     The function solves the following optimization problem with a

    .. math::
       \mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)

    where :

    - :math:`Wu_{reg}(\cdot,\cdot)` is the unbalanced entropic regularized
    Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced)
    - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
    :math:`\mathbf{A}`
    - reg and :math:`\mathbf{M}` are respectively the regularization term and
    the cost matrix for OT
    - reg_mis the marginal relaxation hyperparameter
    The algorithm used for solving the problem is the generalized
    Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

    Parameters
    ----------
    A : np.ndarray (dim, n_hists)
        `n_hists` training distributions a_i of dimension dim
    M : np.ndarray (dim, dim)
        ground metric matrix for OT.
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    weights : np.ndarray (n_hists,) optional
        Weight of each distribution (barycentric coodinates)
        If None, uniform weights are used.
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (> 0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    a : (dim,) ndarray
        Unbalanced Wasserstein barycenter
    log : dict
        log dictionary return only if log==True in parameters

    References
    ----------

    .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G.
        (2015). Iterative Bregman projections for regularized transportation
        problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprin
        arXiv:1607.05816.

    """
    dim, n_hists = A.shape
    if weights is None:
        weights = np.ones(n_hists) / n_hists
    else:
        assert(len(weights) == A.shape[1])

    if log:
        log = {'err': []}

    K = np.exp(- M / reg)

    fi = reg_m / (reg_m + reg)

    v = np.ones((dim, n_hists))
    u = np.ones((dim, 1))
    q = np.ones(dim)
    err = 1.

    for i in range(numItermax):
        uprev = u.copy()
        vprev = v.copy()
        qprev = q.copy()

        Kv = K.dot(v)
        u = (A / Kv) ** fi
        Ktu = K.T.dot(u)
        q = ((Ktu ** (1 - fi)).dot(weights))
        q = q ** (1 / (1 - fi))
        Q = q[:, None]
        v = (Q / Ktu) ** fi

        if (np.any(Ktu == 0.)
                or np.any(np.isnan(u)) or np.any(np.isnan(v))
                or np.any(np.isinf(u)) or np.any(np.isinf(v))):
            # we have reached the machine precision
            # come back to previous solution and quit loop
            warnings.warn('Numerical errors at iteration %s' % i)
            u = uprev
            v = vprev
            q = qprev
            break
            # compute change in barycenter
        err = abs(q - qprev).max()
        err /= max(abs(q).max(), abs(qprev).max(), 1.)
        if log:
            log['err'].append(err)
        # if barycenter did not change + at least 10 iterations - stop
        if err < stopThr and i > 10:
            break

        if verbose:
            if i % 10 == 0:
                print(
                    '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
            print('{:5d}|{:8e}|'.format(i, err))

    if log:
        log['niter'] = i
        log['logu'] = np.log(u + 1e-300)
        log['logv'] = np.log(v + 1e-300)
        return q, log
    else:
        return q

def barycenter_unbalanced(A, M, reg, reg_m, method="sinkhorn", weights=None,
                          numItermax=1000, stopThr=1e-6,
                          verbose=False, log=False, **kwargs):
    r"""Compute the entropic unbalanced wasserstein barycenter of A.

     The function solves the following optimization problem with a

    .. math::
       \mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)

    where :

    - :math:`Wu_{reg}(\cdot,\cdot)` is the unbalanced entropic regularized
    Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced)
    - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
    :math:`\mathbf{A}`
    - reg and :math:`\mathbf{M}` are respectively the regularization term and
    the cost matrix for OT
    - reg_mis the marginal relaxation hyperparameter
    The algorithm used for solving the problem is the generalized
    Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

    Parameters
    ----------
    A : np.ndarray (dim, n_hists)
        `n_hists` training distributions a_i of dimension dim
    M : np.ndarray (dim, dim)
        ground metric matrix for OT.
    reg : float
        Entropy regularization term > 0
    reg_m: float
        Marginal relaxation term > 0
    weights : np.ndarray (n_hists,) optional
        Weight of each distribution (barycentric coodinates)
        If None, uniform weights are used.
    numItermax : int, optional
        Max number of iterations
    stopThr : float, optional
        Stop threshol on error (> 0)
    verbose : bool, optional
        Print information along iterations
    log : bool, optional
        record log if True

    Returns
    -------
    a : (dim,) ndarray
        Unbalanced Wasserstein barycenter
    log : dict
        log dictionary return only if log==True in parameters

    References
    ----------

    .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G.
        (2015). Iterative Bregman projections for regularized transportation
        problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
    .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
        Scaling algorithms for unbalanced transport problems. arXiv preprin
        arXiv:1607.05816.

    """

    if method.lower() == 'sinkhorn':
        return barycenter_unbalanced_sinkhorn(A, M, reg, reg_m,
                                              weights=weights,
                                              numItermax=numItermax,
                                              stopThr=stopThr, verbose=verbose,
                                              log=log, **kwargs)

    elif method.lower() == 'sinkhorn_stabilized':
        return barycenter_unbalanced_stabilized(A, M, reg, reg_m,
                                                weights=weights,
                                                numItermax=numItermax,
                                                stopThr=stopThr,
                                                verbose=verbose,
                                                log=log, **kwargs)
    elif method.lower() in ['sinkhorn_reg_scaling']:
        warnings.warn('Method not implemented yet. Using classic Sinkhorn Knopp')
        return barycenter_unbalanced(A, M, reg, reg_m,
                                     weights=weights,
                                     numItermax=numItermax,
                                     stopThr=stopThr, verbose=verbose,
                                     log=log, **kwargs)
    else:
        raise ValueError("Unknown method '%s'." % method)


text:
angular.module('ionic.service.bind', [])
/**
 * @private
 */
.factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {
  var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  return function(scope, attrs, bindDefinition) {
    angular.forEach(bindDefinition || {}, function (definition, scopeName) {
      //Adapted from angular.js $compile
      var match = definition.match(LOCAL_REGEXP) || [],
        attrName = match[3] || scopeName,
        mode = match[1], // @, =, or &
        parentGet,
        unwatch;

      switch(mode) {
        case '@':
          if (!attrs[attrName]) {
            return;
          }
          attrs.$observe(attrName, function(value) {
            scope[scopeName] = value;
          });
          // we trigger an interpolation to ensure
          // the value is there for use immediately
          if (attrs[attrName]) {
            scope[scopeName] = $interpolate(attrs[attrName])(scope);
          }
          break;

        case '=':
          if (!attrs[attrName]) {
            return;
          }
          unwatch = scope.$watch(attrs[attrName], function(value) {
            scope[scopeName] = value;
          });
          //Destroy parent scope watcher when this scope is destroyed
          scope.$on('$destroy', unwatch);
          break;

        case '&':
          /* jshint -W044 */
          if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\(.*?\)'))) {
            throw new Error('& expression binding "' + scopeName + '" looks like it will recursively call "' +
                          attrs[attrName] + '" and cause a stack overflow! Please choose a different scopeName.');
          }
          parentGet = $parse(attrs[attrName]);
          scope[scopeName] = function(locals) {
            return parentGet(scope, locals);
          };
          break;
      }
    });
  };
}]);


text:
<?php

abstract class PhluxController extends PhabricatorController {

  protected function buildApplicationCrumbs() {
    $crumbs = parent::buildApplicationCrumbs();
    $crumbs->addAction(
      id(new PHUIListItemView())
        ->setName(pht('Create Variable'))
        ->setHref($this->getApplicationURI('/edit/'))
        ->setIcon('create'));

    return $crumbs;
  }

}


text:
//-----------------------------------------------------------------------
// <copyright file="ChangedWatcherCallbackCommand.cs">
//     Copyright © 2010. All rights reserved.
// </copyright>
// <author>Matt Lacey</author>
//-----------------------------------------------------------------------

namespace PhoneGap.Plugins.Orientation
{
    public class ChangedWatcherCallbackCommand : PhoneGapCommand
    {
        public ChangedWatcherCallbackCommand()
        {
            this.HasCallback = true;
        }

        public override void Execute(params string[] args)
        {
            // NOOP
        }
    }
}


text:
<!doctype html>

    <title>Code coverage report for lib\Template.js</title>
    <meta charset="utf-8">

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

Code coverage report for lib\Template.js

        Statements: 93.33% (70 / 75)

        Branches: 80.56% (29 / 36)

        Functions: 100% (10 / 10)

        Lines: 97.06% (66 / 68)

        Ignored: none

All files » lib\ » Template.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

1
1

1
1984
1984

1

1
1
1
1
1
1
1

1

1
6439
752

5687
5687
5673

1
502
502

502
502
502

1
3963
2959

1004

1
734
734
734

734
734
734
730

734
2999
2999
734
734

646
646
646
646
2876

646
3288
3288
3288
3288
2876
2876

646
646

88
88
123
123
123

88

734

1
93

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var Tapable = require("tapable");
var ConcatSource = require("webpack-core/lib/ConcatSource");

function Template(outputOptions) {
	Tapable.call(this);
	this.outputOptions = outputOptions || {};
}
module.exports = Template;

Template.REGEXP_HASH = /\[hash\]/gi;
Template.REGEXP_CHUNKHASH = /\[chunkhash\]/gi;
Template.REGEXP_NAME = /\[name\]/gi;
Template.REGEXP_ID = /\[id\]/gi;
Template.REGEXP_FILE = /\[file\]/gi;
Template.REGEXP_QUERY = /\[query\]/gi;
Template.REGEXP_FILEBASE = /\[filebase\]/gi;

Template.prototype = Object.create(Tapable.prototype);

Template.prototype.indent = function indent(str) {
	if(Array.isArray(str)) {
		return str.map(indent).join("\n");
	} else {
		str = str.trimRight();
		if(!str) return "";
		return (str[0] === "\n" ? "" : "\t") + str.replace(/\n([^\n])/g, "\n\t$1");
	}
};

Template.prototype.prefix = function(str, prefix) {
	Eif(Array.isArray(str)) {
		str = str.join("\n");
	}
	str = str.trim();
	Iif(!str) return "";
	return (str[0] === "\n" ? "" : prefix) + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
};

Template.prototype.asString = function(str) {
	if(Array.isArray(str)) {
		return str.join("\n");
	}
	return str;
};

Template.prototype.renderChunkModules = function(chunk, moduleTemplate, dependencyTemplates, prefix) {
	if(!prefix) prefix = "";
	var source = new ConcatSource();
	Iif(chunk.modules.length === 0) {
		source.add("[]");
		return source;
	}
	var maxId = chunk.modules[chunk.modules.length-1].id;
	var minId = chunk.modules[0].id;
	if(minId < 16 + (""+minId).length) {
		minId = 0;
	}
	var objectOverhead = chunk.modules.map(function(module) {
		return (module.id + "").length + 2;
	}).reduce(function(a, b) { return a + b }, -1);
	var arrayOverhead = minId === 0 ? maxId : 16 + (""+minId).length + maxId;
	if(arrayOverhead < objectOverhead) {
		// Render a sparse array
		Iif(minId !== 0) source.add("Array(" + minId + ").concat(");
		source.add("[\n");
		var modules = {};
		chunk.modules.forEach(function(module) {
			modules[module.id] = module;
		});
		for(var idx = minId; idx <= maxId; idx++) {
			var module = modules[idx];
			if(idx !== minId) source.add(",\n");
			source.add("/* " + idx + " */");
			if(module) {
				source.add("\n");
				source.add(moduleTemplate.render(module, dependencyTemplates, chunk));
			}
		}
		source.add("\n" + prefix + "]");
		Iif(minId !== 0) source.add(")");
	} else {
		// Render an object
		source.add("{\n");
		chunk.modules.forEach(function(module, idx) {
			if(idx !== 0) source.add(",\n");
			source.add("\n/***/ " + module.id + ":\n");
			source.add(moduleTemplate.render(module, dependencyTemplates, chunk));
		});
		source.add("\n\n" + prefix + "}");
	}
	return source;
};

Template.getFunctionContent = function(fn) {
	return fn.toString().replace(/^function\s?\(\)\s?\{\n?|\n?\}$/g, "").replace(/^\t/mg, "");
};

Generated by istanbul at Tue Aug 05 2014 08:06:14 GMT+0200 (Mitteleuropäische Sommerzeit)


text:
$slideshow = {
	context: false,
	tabs: false,
	timeout: 1000,
	slideSpeed: 1000,
	tabSpeed: 300,
	fx: 'scrollLeft',

	init: function() {
		// cache the context to help speed up selectors/improve performance
		this.context = $('#slideshow');

		// set tabs to current hard coded nav items
		this.tabs = $('ul.slides-nav li', this.context);

		//remove hard coded nav from DOM b/c they're not hooked into jQuery cycle
		this.tabs.remove();

		//prepare slideshow and jQuery cycle tabs
		this.prepareSlideshow();
	},

	prepareSlideshow: function() {
		//initialize the jquery cycle plugin -
		// for info: http://malsup.com/jquery/cycle/options.html
		$("div.slides > ul", $slideshow.context).cycle({
			fx: $slideshow.fx,
			timeout: $slideshow.timeout,
			speed: $slideshow.slideSpeed,
			fastOnEvent: $slideshow.tabSpeed,
			pager: $("ul.slides-nav", $slideshow.context),
			pagerAnchorBuilder: $slideshow.prepareTabs,
			before: $slideshow.activateTab,
			pauseOnPagerHover: true,
			pause: true
		});
	},

	prepareTabs: function(i, slide) {
		//return markup from hardcoded tabs for use as jQuery cycle tabs
		// (attaches necessary jQuery cycle events to tabs)
		return $slideshow.tabs.eq(i);
	},

	activateTab: function(currentSlide, nextSlide) {
		// get the active tab
		var activeTab = $('a[href="#' + nextSlide.id + '"]', $slideshow.context);

		// if there is an active tab
		if(activeTab.length) {
			// remove active styling from all other tabs
			$slideshow.tabs.removeClass('on');

			// add active styling to active button
			activeTab.parent().addClass('on');
		}
	}
};

$(function() {
	//initialize the slidewho when the DOM is ready
	$slideshow.init();
});


text:
/*
 *  btstack.h
 *
 *  Created by Matthias Ringwald on 7/1/09.
 *
 *  BTstack client API
 *
 */

#pragma once

#include <btstack/hci_cmds.h>
#include <btstack/run_loop.h>
#include <btstack/utils.h>

#include <stdint.h>

#if defined __cplusplus
extern "C" {
#endif

// Default TCP port for BTstack daemon
#define BTSTACK_PORT            13333

// UNIX domain socket for BTstack */
#define BTSTACK_UNIX            "/tmp/BTstack"

// packet handler
typedef void (*btstack_packet_handler_t) (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);

// optional: if called before bt_open, TCP socket is used instead of local unix socket
//           note: address is not copied and must be valid during bt_open
void bt_use_tcp(const char * address, uint16_t port);

// init BTstack library
int bt_open(void);

// stop using BTstack library
int bt_close(void);

// send hci cmd packet
int bt_send_cmd(const hci_cmd_t *cmd, ...);

// register packet handler -- channel only valid for l2cap and rfcomm packets
// @returns old packet handler
btstack_packet_handler_t bt_register_packet_handler(btstack_packet_handler_t handler);

void bt_send_acl(uint8_t * data, uint16_t len);

void bt_send_l2cap(uint16_t local_cid, uint8_t *data, uint16_t len);
void bt_send_rfcomm(uint16_t rfcom_cid, uint8_t *data, uint16_t len);

#if defined __cplusplus
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<!-- ===================================================================== -->
<!--                                                                       -->
<!--  Log4j Configuration                                                  -->
<!--                                                                       -->
<!-- ===================================================================== -->

<!--
   | For more configuration information and examples see the Jakarta Log4j
   | website: http://jakarta.apache.org/log4j
 -->

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

  <!-- ============================== -->
  <!-- Append messages to the console -->
  <!-- ============================== -->

  <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <param name="Threshold" value="DEBUG"/>
    <param name="Target" value="System.err"/>

    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%-5p | %c | %d{ISO8601}%n   > %m%n%n"/>
    </layout>
  </appender>

  <!-- ======================= -->
  <!-- Setup the Root category -->
  <!-- ======================= -->

  <logger name="org.apache.tapestry5.cdi.CDIInjectionProvider">
    <level value="DEBUG" />
  </logger>

  <logger name="org.apache.tapestry5.cdi.CDIObjectProvider">
    <level value="DEBUG" />
  </logger>

  <logger name="org.apache.tapestry5.cdi.internal.InternalUtils">
    <level value="DEBUG" />
  </logger>

  <logger name="org.apache.tapestry5.cdi.BeanHelper">
      <level value="DEBUG" />
  </logger>

  <logger name="org.apache.tapestry5.cdi.extension.TapestryExtension">
      <level value="DEBUG" />
  </logger>

  <root>
    <priority value ="DEBUG" />
    <appender-ref ref="CONSOLE"/>
  </root>

</log4j:configuration>


text:
layout: post
title:  "AngularJS v2.0 and the Impending Schism"
date:   2015-08-05
modified:   2015-09-18
categories: angularjs
tags: [programming, angularjs, javascript, python, opinion]
image:
  feature: abstract-11.jpg
  credit:
---

I think we are witnessing the Python 2->3 'Conversion' all over again.
AngularJS v2.0 introduces too many changes. **Not least of which is TypeScript**, which is a big ask amidst the finalization of JS's latest version: ES6.

> Let me say clearly: I love TypeScript. I seccretly wish the TC-39 meetings had produced it... They didn't.
> However, They came up with another (totally different), also-awesome spec...

While TypeScript compiles to JavaScript, it doesn't mean you blindly copy & paste 'compiled' TypeScript. It effectively becomes required learning, as to understand annotated AngularJS 2.0 TypeScript.

Now, newbies must climb 'Mount TypeScript' before they can even start assembling an Angular app (with some level of understanding).

I have a feeling how this might go...

Oh well, I'll add it to the Newbie training list: somewhere between `Basic Shell Usage` and `Gulp or Grunt? Godsend+Misery!`

> Anyway, I hope this works out...

[schema_refactor]: https://res.cloudinary.com/ddd/image/upload/bldg-collapse__wsZKhIc_kafcha.gif
[not_a_fan]: https://res.cloudinary.com/ddd/image/upload/timeout-expired.gif
[teamwork]: https://res.cloudinary.com/ddd/image/upload/teamwork__tumblr_n2df80cPZa1s373hwo1_400_ghv4xn.gif
[fuck_this]: https://res.cloudinary.com/ddd/image/upload/panda-rampage__tumblr_nq7srwTXqr1stn6klo1_500_gm2som.gif
[new_feature]: https://res.cloudinary.com/ddd/image/upload/simba-toss-error.gif
[drinking]: http://res.cloudinary.com/ddd/image/upload/v1442175801/system-maint-anon.gif
[cat_outfit]: http://res.cloudinary.com/ddd/image/upload/v1441143858/cat-bee-fail.gif
[cat_loops]: http://res.cloudinary.com/ddd/image/upload/v1441143869/cat-loops.gif
[cat_bowl]: http://res.cloudinary.com/ddd/image/upload/v1441143883/kitten_bowl.gif
[cat_wtf]: http://res.cloudinary.com/ddd/image/upload/v1441143878/cat-wtf.gif
[endless_loop]: http://res.cloudinary.com/ddd/image/upload/v1441143881/endless-loop.gif


text:
exports.init = function(genericAWSClient) {
  // Creates an EC2 API client
  var createEC2Client = function (accessKeyId, secretAccessKey, options) {
    options = options || {}
    var aws = genericAWSClient({
      host: options.host || "ec2.amazonaws.com",
      path: options.path || "/",
      accessKeyId: accessKeyId,
      secretAccessKey: secretAccessKey,
      secure: options.secure,
      token: options.token
    });
    var callFn = function(action, opts, callback) {
	  var query = {};
      query["Action"] = action
      query["Version"] = options.version || "2012-12-01"
      query["SignatureMethod"] = "HmacSHA256"
      query["SignatureVersion"] = "2"
      //add options to the end of the query
	  for(var key in opts){
		   query[key] = opts[key];
	   }

      return aws.call(action, query, callback);
    }
    return {
        client: aws,
        call: callFn
    };
  }
  return createEC2Client;
}


text:
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output

@click.command('get_libraries')
@click.option(
    "--library_id",
    help="filter for library by library id",
    type=str
)
@click.option(
    "--name",
    help="Library name to filter on.",
    type=str
)
@click.option(
    "--deleted",
    help="If ``False`` (the default), return only non-deleted libraries. If ``True``, return only deleted libraries. If ``None``, return both deleted and non-deleted libraries.",
    is_flag=True
)
@pass_context
@custom_exception
@json_output
def cli(ctx, library_id="", name="", deleted=False):
    """Get all libraries, or select a subset by specifying optional arguments for filtering (e.g. a library name).

Output:

    list of dicts each containing basic information about a library
    """
    return ctx.gi.libraries.get_libraries(library_id=library_id, name=name, deleted=deleted)


text:
<!doctype html>
<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<html>
<head>
  <title>app-route 0bserver Test</title>

  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>

  <link rel="import" href="../../polymer/polymer.html">
  <link rel="import" href="./observer-tester.html">

</head>
<body>

  <test-fixture id="observer_app">
    <template>
      <observer-tester id="testel"></observer-tester>
    </template>
  </test-fixture>
  <script>
    'use strict';
    function setLocation(url) {
      window.history.pushState({}, '', url);
      Polymer.Base.fire('location-changed', {}, {node: window});
    }

    suite('observe app-route active changes', function() {
      var originalLocation;
      var sandbox, el;
      setup(function() {
        originalLocation = window.location.href;
        sandbox = sinon.sandbox.create();
        el = fixture('observer_app');
      });
      teardown(function() {
        sandbox.restore();
        window.history.replaceState({}, '', originalLocation);
      });

      test('observer should fire when route selected', function() {
        sandbox.spy(el, 'checkActive');
        setLocation('/report/1000');
        expect(el.checkActive).to.have.been.called.once;
        expect(el.checkActive).to.have.been.calledWith(true);
      });
      test('observer should fire when route deselected', function() {
        setLocation('/report/1000');
        sandbox.spy(el, 'checkActive');
        setLocation('/menu');
        expect(el.checkActive).to.have.been.called.once;
        expect(el.checkActive).to.have.been.calledWith(false);
      });
    });
  </script>
</body>


text:
require 'pact/logging'
require 'rack/test'
require 'pact/consumer_contract/interaction'
require 'pact/provider/state/provider_state'
require 'pact/provider/state/provider_state_proxy'
require 'pact/provider/request'
require 'pact/provider/world'
require 'pact/provider/state/provider_state_manager'

module Pact
  module Provider
    module TestMethods

      include Pact::Logging
      include Rack::Test::Methods

      def replay_interaction interaction
        request = Request::Replayable.new(interaction.request)
        args = [request.path, request.body, request.headers]

        logger.info "Sending #{request.method.upcase} request to path: \"#{request.path}\" with headers: #{request.headers}, see debug logs for body"
        logger.debug "body :#{request.body}"
        response = self.send(request.method.downcase, *args)
        logger.info "Received response with status: #{response.status}, headers: #{response.headers}, see debug logs for body"
        logger.debug "body: #{response.body}"
      end

      def parse_body_from_response rack_response
        case rack_response.headers['Content-Type']
        when /json/
          JSON.load(rack_response.body)
        else
          rack_response.body
        end
      end

      def set_up_provider_state provider_state_name, consumer
        State::ProviderStateManager.new(provider_state_name, consumer).set_up_provider_state
      end

      def tear_down_provider_state provider_state_name, consumer
        State::ProviderStateManager.new(provider_state_name, consumer).tear_down_provider_state
      end

    end
  end
end


text:
using namespace std;
using namespace MuddledManaged;

Protocol::MessageFieldParser::MessageFieldParser ()
{ }

bool Protocol::MessageFieldParser::parse (TokenReader::iterator current, TokenReader::iterator end, bool firstChance, std::shared_ptr<ProtoModel> model)
{
    if (current != end)
    {
        Protocol::MessageFieldModel::Requiredness requiredness = Protocol::MessageFieldModel::Requiredness::required;
        if (*current == "required")
        {
            requiredness = Protocol::MessageFieldModel::Requiredness::required;
        }
        else if (*current == "optional")
        {
            requiredness = Protocol::MessageFieldModel::Requiredness::optional;
        }
        else if (*current == "repeated")
        {
            requiredness = Protocol::MessageFieldModel::Requiredness::repeated;
        }
        else
        {
            return false;
        }

        // Move to the field type.
        ++current;
        if (current == end || current->empty())
        {
            throw InvalidProtoException(current.line(), current.column(), "Expected field type.");
        }
        string fieldType = *current;
        // Either move to the name or keep adding to the type if we find a dot.
        ++current;
        while (current != end && *current == ".")
        {
            fieldType += ".";
            ++current;
            if (current == end || current->empty())
            {
                throw InvalidProtoException(current.line(), current.column(), "Expected additional field type.");
            }
            fieldType += *current;
            ++current;
        }

        // Get the field name.
        if (current == end || current->empty())
        {
            throw InvalidProtoException(current.line(), current.column(), "Expected field name.");
        }
        string name = *current;

        // Move to the equal.
        ++current;
        if (current == end || *current != "=")
        {
            throw InvalidProtoException(current.line(), current.column(), "Expected = character.");
        }

        // Move to the field index.
        ++current;
        if (current == end || current->empty())
        {
            throw InvalidProtoException(current.line(), current.column(), "Expected field index.");
        }
        unsigned int index = stoi(*current);

        shared_ptr<MessageFieldModel> field(new MessageFieldModel(requiredness, fieldType, name, index));
        model->addField(current, field);

        // Move to the semicolon or inline options.
        ParserManager * parserMgr = ParserManager::instance();
        ++current;
        if (current == end)
        {
            throw InvalidProtoException(current.line(), current.column(), "Expected ; or [ character.");
        }
        if (*current != ";")
        {
            bool parserFound = false;
            for (auto & parser: *parserMgr->parsers("messageField"))
            {
                if (parser->parse(current, end, true, model))
                {
                    parserFound = true;
                    break;
                }
            }
            if (!parserFound)
            {
                // Try again for the second chance parsers.
                for (auto & parser: *parserMgr->parsers("messageField"))
                {
                    if (parser->parse(current, end, false, model))
                    {
                        parserFound = true;
                        break;
                    }
                }
                if (!parserFound)
                {
                    throw InvalidProtoException(current.line(), current.column(), "Unexpected option content found.");
                }
            }

            // Move to the semicolon.
            ++current;
            if (current == end || *current != ";")
            {
                throw InvalidProtoException(current.line(), current.column(), "Expected ; character.");
            }
        }
        model->completeField();

        return true;
    }
    return false;
}


text:
package it.hysen.springmvc.security.oauth2;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

//@Configuration
//@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private static final String RESOURCE_ID = "rest_api";

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.anonymous().disable().requestMatchers().antMatchers("/api/**").and().authorizeRequests()
		        .antMatchers("/api/**").access("hasRole('ADMIN')").and().exceptionHandling()
		        .accessDeniedHandler(new OAuth2AccessDeniedHandler());
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.resourceId(ResourceServerConfiguration.RESOURCE_ID).stateless(false);
	}

}


text:
<?php

/** Zend_Filter_Interface */
require_once "Zend/Filter/Interface.php";

/**
 * Boolean filter
 *
 * Filters a value to a boolean.
 *
 * @category Rend
 * @package Filter
 */
class Rend_Filter_Boolean implements Zend_Filter_Interface
{

    /**
     * Filter a value
     *
     * @param mixed $value
     * @return boolean
     */
    public function filter($value)
    {
        return (boolean) $value;
    }

}


text:
categories:
  - photo
comments: true
layout: post
published: true
status: publish
tags: []
title: "picking it up. Group 1 is the best."
type: post
---


text:
package org.openfs.component.truevfs;

import java.io.File;

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.util.FileUtil;
import org.junit.Test;

public class DuplicateTest extends CamelTestSupport {

	@EndpointInject(uri = "mock:result")
	MockEndpoint resultEndpoint;

	@Test
	public void testDirFilesZipArchiver() throws Exception {
		cleanupDir("target/test");
		cleanupDir("target/archiver");
		resultEndpoint.expectedMessageCount(1);
		resultEndpoint.expectedFileExists("target/archiver/testDir.zip");
		template.sendBodyAndHeader("file://target/test", "1", Exchange.FILE_NAME, "3.dat");
		template.sendBodyAndHeader("file://target/test", "2", Exchange.FILE_NAME, "4.dat");
		resultEndpoint.assertIsSatisfied();
	}

	@Test
	public void testDirFilesZipArchiverDup() throws Exception {
		resultEndpoint.expectedMessageCount(1);
		resultEndpoint.expectedFileExists("target/archiver/testDir.zip");
		template.sendBodyAndHeader("file://target/test", "1", Exchange.FILE_NAME, "3.dat");
		template.sendBodyAndHeader("file://target/test", "2", Exchange.FILE_NAME, "4.dat");
		template.sendBodyAndHeader("file://target/test", "2", Exchange.FILE_NAME, "5.dat");
		resultEndpoint.assertIsSatisfied();
	}

	protected RouteBuilder createRouteBuilder() {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("timer://test?repeatCount=1")
						.to("truevfs://target/archiver?fileName=testDir.zip&srcDir=target/test")
						.to("mock:result");
			}
		};
	}

	protected void cleanupDir (String dirname) {
		File d = new File(dirname);
		if (d.exists() && d.isDirectory())
			FileUtil.removeDir(d);
	}
}