text:
"""Provides stubs for os, sys and subprocess for testing

This test allows one to test code that itself uses os, sys, and subprocess.
"""

import os
import re
import shlex
import sys

class Override(object):
  def __init__(self, base_module, module_list):
    stubs = {'adb_commands': AdbCommandsModuleStub,
             'cloud_storage': CloudStorageModuleStub,
             'open': OpenFunctionStub,
             'os': OsModuleStub,
             'perf_control': PerfControlModuleStub,
             'raw_input': RawInputFunctionStub,
             'subprocess': SubprocessModuleStub,
             'sys': SysModuleStub,
             'thermal_throttle': ThermalThrottleModuleStub,
    }
    self.adb_commands = None
    self.os = None
    self.subprocess = None
    self.sys = None

    self._base_module = base_module
    self._overrides = {}

    for module_name in module_list:
      self._overrides[module_name] = getattr(base_module, module_name, None)
      setattr(self, module_name, stubs[module_name]())
      setattr(base_module, module_name, getattr(self, module_name))

    if self.os and self.sys:
      self.os.path.sys = self.sys

  def __del__(self):
    assert not len(self._overrides)

  def Restore(self):
    for module_name, original_module in self._overrides.iteritems():
      setattr(self._base_module, module_name, original_module)
    self._overrides = {}

class AdbCommandsModuleStub(object):
  class AdbCommandsStub(object):
    def __init__(self, module, device):
      self._module = module
      self._device = device
      self.is_root_enabled = True

    def RunShellCommand(self, args):
      if isinstance(args, basestring):
        args = shlex.split(args)
      handler = self._module.shell_command_handlers[args[0]]
      return handler(args)

    def IsRootEnabled(self):
      return self.is_root_enabled

    def RestartAdbdOnDevice(self):
      pass

    def IsUserBuild(self):
      return False

    def WaitForDevicePm(self):
      pass

  def __init__(self):
    self.attached_devices = []
    self.shell_command_handlers = {}

    def AdbCommandsStubConstructor(device=None):
      return AdbCommandsModuleStub.AdbCommandsStub(self, device)
    self.AdbCommands = AdbCommandsStubConstructor

  @staticmethod
  def IsAndroidSupported():
    return True

  def GetAttachedDevices(self):
    return self.attached_devices

  def SetupPrebuiltTools(self, _):
    return True

  def CleanupLeftoverProcesses(self):
    pass

class CloudStorageModuleStub(object):
  INTERNAL_BUCKET = None
  PUBLIC_BUCKET = None

  class CloudStorageError(Exception):
    pass

  def __init__(self):
    self.remote_paths = []
    self.local_file_hashes = {}
    self.local_hash_files = {}

  def List(self, _):
    return self.remote_paths

  def Insert(self, bucket, remote_path, local_path):
    pass

  def CalculateHash(self, file_path):
    return self.local_file_hashes[file_path]

  def ReadHash(self, hash_path):
    return self.local_hash_files[hash_path]

class OpenFunctionStub(object):
  class FileStub(object):
    def __init__(self, data):
      self._data = data

    def __enter__(self):
      return self

    def __exit__(self, *args):
      pass

    def read(self, size=None):
      if size:
        return self._data[:size]
      else:
        return self._data

    def write(self, data):
      self._data.write(data)

    def close(self):
      pass

  def __init__(self):
    self.files = {}

  def __call__(self, name, *args, **kwargs):
    return OpenFunctionStub.FileStub(self.files[name])

class OsModuleStub(object):
  class OsEnvironModuleStub(object):
    def get(self, _):
      return None

  class OsPathModuleStub(object):
    def __init__(self, sys_module):
      self.sys = sys_module
      self.files = []

    def exists(self, path):
      return path in self.files

    def isfile(self, path):
      return path in self.files

    def join(self, *paths):
      def IsAbsolutePath(path):
        if self.sys.platform.startswith('win'):
          return re.match('[a-zA-Z]:\\\\', path)
        else:
          return path.startswith('/')

      # Per Python specification, if any component is an absolute path,
      # discard previous components.
      for index, path in reversed(list(enumerate(paths))):
        if IsAbsolutePath(path):
          paths = paths[index:]
          break

      if self.sys.platform.startswith('win'):
        tmp = os.path.join(*paths)
        return tmp.replace('/', '\\')
      else:
        tmp = os.path.join(*paths)
        return tmp.replace('\\', '/')

    @staticmethod
    def expanduser(path):
      return os.path.expanduser(path)

    @staticmethod
    def dirname(path):
      return os.path.dirname(path)

    @staticmethod
    def splitext(path):
      return os.path.splitext(path)

  X_OK = os.X_OK

  pathsep = os.pathsep

  def __init__(self, sys_module=sys):
    self.path = OsModuleStub.OsPathModuleStub(sys_module)
    self.environ = OsModuleStub.OsEnvironModuleStub()
    self.display = ':0'
    self.local_app_data = None
    self.sys_path = None
    self.program_files = None
    self.program_files_x86 = None
    self.devnull = os.devnull

  def access(self, path, _):
    return path in self.path.files

  def getenv(self, name, value=None):
    if name == 'DISPLAY':
      env = self.display
    elif name == 'LOCALAPPDATA':
      env = self.local_app_data
    elif name == 'PATH':
      env = self.sys_path
    elif name == 'PROGRAMFILES':
      env = self.program_files
    elif name == 'PROGRAMFILES(X86)':
      env = self.program_files_x86
    else:
      raise NotImplementedError('Unsupported getenv')
    return env if env else value

class PerfControlModuleStub(object):
  class PerfControlStub(object):
    def __init__(self, adb):
      pass

  def __init__(self):
    self.PerfControl = PerfControlModuleStub.PerfControlStub

class RawInputFunctionStub(object):
  def __init__(self):
    self.input = ''

  def __call__(self, name, *args, **kwargs):
    return self.input

class SubprocessModuleStub(object):
  class PopenStub(object):
    def __init__(self):
      self.communicate_result = ('', '')

    def __call__(self, args, **kwargs):
      return self

    def communicate(self):
      return self.communicate_result

  def __init__(self):
    self.Popen = SubprocessModuleStub.PopenStub()
    self.PIPE = None

  def call(self, *args, **kwargs):
    pass

class SysModuleStub(object):
  def __init__(self):
    self.platform = ''

class ThermalThrottleModuleStub(object):
  class ThermalThrottleStub(object):
    def __init__(self, adb):
      pass

  def __init__(self):
    self.ThermalThrottle = ThermalThrottleModuleStub.ThermalThrottleStub


text:
define(['../internal/baseIndexOf', '../internal/binaryIndex'], function(baseIndexOf, binaryIndex) {

  /* Native method references for those with the same name as other `lodash` methods. */
  var nativeMax = Math.max;

  /**
   * Gets the index at which the first occurrence of `value` is found in `array`
   * using `SameValueZero` for equality comparisons. If `fromIndex` is negative,
   * it is used as the offset from the end of `array`. If `array` is sorted
   * providing `true` for `fromIndex` performs a faster binary search.
   *
   * **Note:** `SameValueZero` comparisons are like strict equality comparisons,
   * e.g. `===`, except that `NaN` matches `NaN`. See the
   * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
   * for more details.
   *
   * @static
   * @memberOf _
   * @category Array
   * @param {Array} array The array to search.
   * @param {*} value The value to search for.
   * @param {boolean|number} [fromIndex=0] The index to search from or `true`
   *  to perform a binary search on a sorted array.
   * @returns {number} Returns the index of the matched value, else `-1`.
   * @example
   *
   * _.indexOf([1, 2, 3, 1, 2, 3], 2);
   * // => 1
   *
   * // using `fromIndex`
   * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
   * // => 4
   *
   * // performing a binary search
   * _.indexOf([4, 4, 5, 5, 6, 6], 5, true);
   * // => 2
   */
  function indexOf(array, value, fromIndex) {
    var length = array ? array.length : 0;
    if (!length) {
      return -1;
    }
    if (typeof fromIndex == 'number') {
      fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
    } else if (fromIndex) {
      var index = binaryIndex(array, value),
          other = array[index];

      return (value === value ? value === other : other !== other) ? index : -1;
    }
    return baseIndexOf(array, value, fromIndex);
  }

  return indexOf;
});

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.insightfullogic</groupId>
	<artifactId>multi-inherit</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>multi-inherit</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>clean</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<reporting>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</reporting>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>3.0</version>
		</dependency>
		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm-commons</artifactId>
			<version>3.3.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>r09</version>
		</dependency>
		<dependency>
			<groupId>nl.jqno.equalsverifier</groupId>
			<artifactId>equalsverifier</artifactId>
			<version>1.0.2</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
package org.italiangrid.voms.clients.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.italiangrid.voms.clients.strategies.VOMSCommandsParsingStrategy;

public class DefaultVOMSCommandsParser implements VOMSCommandsParsingStrategy {

  public static final String COMMAND_SEPARATOR = ":";
  public static final String ALL_COMMAND_STRING = "all";

  public Map<String, List<String>> parseCommands(List<String> commands) {

    if (commands == null)
      return null;

    if (commands.isEmpty())
      return Collections.emptyMap();

    Map<String, List<String>> commandsMap = new LinkedHashMap<String, List<String>>();

    for (String cmd : commands) {

      String[] cmdTokens = cmd.split(COMMAND_SEPARATOR);
      String vo = cmdTokens[0];

      if (commandsMap.containsKey(vo)) {

        if (cmdTokens.length > 1 && !cmdTokens[1].equals(ALL_COMMAND_STRING))
          commandsMap.get(vo).add(cmdTokens[1]);
      } else {

        List<String> requestedFQANs = new ArrayList<String>();

        if (cmdTokens.length > 1 && !cmdTokens[1].equals("all"))
          requestedFQANs.add(cmdTokens[1]);

        commandsMap.put(vo, requestedFQANs);
      }
    }

    return commandsMap;
  }

}


text:
from msrest.serialization import Model

class PagedSubNameInfoList(Model):
    """A paged list of Service Fabric names. The list is paged when all of the
    results cannot fit in a single message. The next set of results can be
    obtained by executing the same query with the continuation token provided
    in this list.

    :param continuation_token: The continuation token parameter is used to
     obtain next set of results. The continuation token is included in the
     response of the API when the results from the system do not fit in a
     single response. When this value is passed to the next API call, the API
     returns next set of results. If there are no further results then the
     continuation token is not included in the response.
    :type continuation_token: str
    :param is_consistent: Indicates whether any name under the given name has
     been modified during the enumeration. If there was a modification, this
     property value is false.
    :type is_consistent: bool
    :param sub_names: List of the child names.
    :type sub_names: list[str]
    """

    _attribute_map = {
        'continuation_token': {'key': 'ContinuationToken', 'type': 'str'},
        'is_consistent': {'key': 'IsConsistent', 'type': 'bool'},
        'sub_names': {'key': 'SubNames', 'type': '[str]'},
    }

    def __init__(self, continuation_token=None, is_consistent=None, sub_names=None):
        super(PagedSubNameInfoList, self).__init__()
        self.continuation_token = continuation_token
        self.is_consistent = is_consistent
        self.sub_names = sub_names


text:
namespace Beaker.Specs
{
	/// <summary>
	/// A builder
	/// </summary>
	public interface IBuilder
	{
		/// <summary>
		/// Build the subject.
		/// </summary>
		/// <returns>The build subject.</returns>
		object Build();
	}

	/// <summary>
	/// A builder that builds the given type
	/// </summary>
	/// <typeparam name="TSubject">The type to build</typeparam>
	public interface IBuilder<out TSubject>
		: IBuilder
	{
		/// <summary>
		/// Build the subject.
		/// </summary>
		/// <returns>The build subject.</returns>
		new TSubject Build();
	}
}


text:
using boost::icl::interval;

namespace grt {

class Grid
{
 public:
  Grid() = default;
  ~Grid() = default;

  void init(const odb::Rect& die_area,
            const int tile_size,
            const int x_grids,
            const int y_grids,
            const bool perfect_regular_x,
            const bool perfectR_rgular_y,
            const int num_layers);

  void clear();

  int getXMin() const { return die_area_.xMin(); }
  int getYMin() const { return die_area_.yMin(); }

  void setXMin(int x) { die_area_.set_xlo(x); }
  void setYMin(int y) { die_area_.set_ylo(y); }

  int getXMax() const { return die_area_.xMax(); }
  int getYMax() const { return die_area_.yMax(); }

  int getTileSize() const { return tile_size_; }

  int getXGrids() const { return x_grids_; }
  int getYGrids() const { return y_grids_; }

  bool isPerfectRegularX() const { return perfect_regular_x_; }
  bool isPerfectRegularY() const { return perfect_regular_y_; }

  int getNumLayers() const { return num_layers_; }

  void setPitchesInTile(const int pitches_in_tile)
  {
    pitches_in_tile_ = pitches_in_tile;
  }
  int getPitchesInTile() const { return pitches_in_tile_; }

  const std::vector<int>& getSpacings() const { return spacings_; }
  const std::vector<int>& getMinWidths() const { return min_widths_; }

  void addSpacing(int value, int layer) { spacings_[layer] = value; }
  void addMinWidth(int value, int layer) { min_widths_[layer] = value; }

  const std::vector<int>& getHorizontalEdgesCapacities()
  {
    return horizontal_edges_capacities_;
  };
  const std::vector<int>& getVerticalEdgesCapacities()
  {
    return vertical_edges_capacities_;
  };

  void addHorizontalCapacity(int value, int layer)
  {
    horizontal_edges_capacities_[layer] = value;
  }
  void addVerticalCapacity(int value, int layer)
  {
    vertical_edges_capacities_[layer] = value;
  }

  void updateHorizontalEdgesCapacities(int layer, int reduction)
  {
    horizontal_edges_capacities_[layer] = reduction;
  };
  void updateVerticalEdgesCapacities(int layer, int reduction)
  {
    vertical_edges_capacities_[layer] = reduction;
  };

  odb::Point getPositionOnGrid(const odb::Point& position);

  void getBlockedTiles(const odb::Rect& obstruction,
                       odb::Rect& first_tile_bds,
                       odb::Rect& last_tile_bds,
                       odb::Point& first_tile,
                       odb::Point& last_tile);

  int computeTileReduce(const odb::Rect& obs,
                        const odb::Rect& tile,
                        int track_space,
                        bool first,
                        odb::dbTechLayerDir direction);

  interval<int>::type computeTileReduceInterval(const odb::Rect& obs,
                                                const odb::Rect& tile,
                                                int track_space,
                                                bool first,
                                                odb::dbTechLayerDir direction);

  odb::Point getMiddle();
  const odb::Rect& getGridArea() const;

 private:
  odb::Rect die_area_;
  int tile_size_;
  int x_grids_;
  int y_grids_;
  bool perfect_regular_x_;
  bool perfect_regular_y_;
  int num_layers_;
  int pitches_in_tile_ = 15;
  std::vector<int> spacings_;
  std::vector<int> min_widths_;
  std::vector<int> horizontal_edges_capacities_;
  std::vector<int> vertical_edges_capacities_;
};

}  // namespace grt


text:
<?php

namespace spec\Pkracer\JsonApiDocuments\Formatters;

use PhpSpec\ObjectBehavior;
use Pkracer\JsonApiDocuments\Interfaces\FormatterInterface;
use Prophecy\Argument;

class LaravelFormatterSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(FormatterInterface::class);
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
  <link rel="stylesheet" href="css/app.css">

    <title ng-bind-template="Google Phone Gallery: {{query}}">Google Phone Gallery</title>

Billy Bob's Phone Shop


text:
<?php

namespace Drupal\password_policy\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\ConfirmFormHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user\SharedTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Deleting a constraint from a policy within the wizard.
 */
class ConstraintDelete extends ConfirmFormBase {

  /**
   * Temp store to maintain state between steps of the wizard.
   *
   * @var \Drupal\user\SharedTempStoreFactory
   */
  protected $tempstore;

  /**
   * ID of the tempstore to maintain state for the form wizard.
   *
   * @var string
   */
  protected $tempstoreId = 'password_policy.password_policy';

  /**
   * The machine name of the form step.
   *
   * @var string
   */
  protected $machineName;

  /**
   * ID of the constraint.
   *
   * @var int
   */
  protected $id;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('user.shared_tempstore'));
  }

  /**
   * Constructor that adds the tempstore from the container for wizard.
   *
   * @param \Drupal\user\SharedTempStoreFactory $tempstore
   *   The tempstore of the wizard form.
   */
  public function __construct(SharedTempStoreFactory $tempstore) {
    $this->tempstore = $tempstore;
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'password_policy_constraint_delete_form';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param string $machine_name
   *   The machine name of the policy.
   * @param int $id
   *   The ID value of the constraint.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $machine_name = NULL, $id = NULL) {
    $this->machineName = $machine_name;
    $this->id = $id;

    $cached_values = $this->tempstore->get($this->tempstoreId)->get($this->machineName);
    $form['#title'] = $this->getQuestion($id, $cached_values);

    $form['#attributes']['class'][] = 'confirmation';
    $form['description'] = ['#markup' => $this->getDescription()];
    $form[$this->getFormName()] = ['#type' => 'hidden', '#value' => 1];

    // By default, render the form using theme_confirm_form().
    if (!isset($form['#theme'])) {
      $form['#theme'] = 'confirm_form';
    }
    $form['actions'] = ['#type' => 'actions'];
    $form['actions'] += $this->actions($form, $form_state);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $cached_values = $this->tempstore->get($this->tempstoreId)->get($this->machineName);
    /** @var \Drupal\password_policy\Entity\PasswordPolicy $policy */
    $policy = $cached_values['password_policy'];
    $constraints = $policy->getConstraints();
    unset($constraints[$this->id]);
    $policy->set('policy_constraints', $constraints);
    $this->tempstore->get($this->tempstoreId)->set($this->machineName, $cached_values);
    $form_state->setRedirect('entity.password_policy.wizard.edit', ['machine_name' => $this->machineName, 'step' => 'constraint']);
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion($id = NULL, $cached_values = NULL) {
    /** @var \Drupal\password_policy\Entity\PasswordPolicy $password_policy */
    $password_policy = $cached_values['password_policy'];
    $context = $password_policy->getConstraint($id);
    return $this->t('Are you sure you want to delete the @label constraint?', [
      '@label' => $context['id'],
    ]);
  }

  /**
   * Returns the route to go to if the user cancels the action.
   *
   * @return \Drupal\Core\Url
   *   A URL object.
   */
  public function getCancelUrl() {
    return new Url('entity.password_policy.wizard.edit', ['machine_name' => $this->machineName, 'step' => 'constraint']);
  }

  /**
   * Provides the action buttons for submitting this form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   A set of actions associated with this form.
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    return [
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->getConfirmText(),
        '#submit' => [
          [$this, 'submitForm'],
        ],
      ],
      'cancel' => ConfirmFormHelper::buildCancelLink($this, $this->getRequest()),
    ];
  }

}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**response** | [**\Swagger\Client\Model\Response**](Response.md) |  |
**data** | [**\Swagger\Client\Model\PostbackTest**](PostbackTest.md) | Test results |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Algorithms.ObjectFittingStrategies._3D;
using Logic.Domain.Containers._3D;
using Logic.Domain.Containers._3D.Guillotine;

namespace Logic.Algorithms.Implementations._3D.Guillotine
{
	public class ShorterAxisGuillotineCut3DAlgorithm : AbstractGuillotineCut3DAlgorithm
	{
		public ShorterAxisGuillotineCut3DAlgorithm(Container3D initialContainer, AbstractFittingStrategy3D strategy) : base(initialContainer, strategy)
		{
			containers = new List<Container3D>();

			containers.Add(new GuillotineCutShorterAxisContainer3D(initialContainer.Width, initialContainer.Height, initialContainer.Depth));

		}

		public override void AddContainer()
		{
			if (containers != null)
				containers.Add(new GuillotineCutShorterAxisContainer3D(containers.First().Width, containers.First().Height, containers.First().Depth));

		}
	}
}


text:
package com.thoughtworks.go.config.update;

import com.thoughtworks.go.config.BasicCruiseConfig;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.commands.EntityConfigUpdateCommand;
import com.thoughtworks.go.config.exceptions.EntityType;
import com.thoughtworks.go.domain.scm.SCM;
import com.thoughtworks.go.domain.scm.SCMs;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.server.service.materials.PluggableScmService;
import com.thoughtworks.go.server.service.result.LocalizedOperationResult;
import com.thoughtworks.go.serverhealth.HealthStateType;

import static com.thoughtworks.go.serverhealth.HealthStateType.forbidden;

public abstract class SCMConfigCommand implements EntityConfigUpdateCommand<SCM> {
    protected final SCM globalScmConfig;
    protected final LocalizedOperationResult result;
    private final PluggableScmService pluggableScmService;
    protected SCM preprocessedGlobalScmConfig;
    protected final GoConfigService goConfigService;
    protected final Username currentUser;

    public SCMConfigCommand(SCM globalScmConfig, PluggableScmService pluggableScmService, GoConfigService goConfigService, Username currentUser, LocalizedOperationResult result) {
        this.globalScmConfig = globalScmConfig;
        this.pluggableScmService = pluggableScmService;
        this.goConfigService = goConfigService;
        this.currentUser = currentUser;
        this.result = result;
    }

    @Override
    public boolean isValid(CruiseConfig preprocessedConfig) {
        SCMs scms = preprocessedConfig.getSCMs();
        preprocessedGlobalScmConfig = scms.find(globalScmConfig.getSCMId());
        preprocessedGlobalScmConfig.validate(null);
        if (preprocessedGlobalScmConfig.getAllErrors().isEmpty()) {
            scms.validate(null);
            boolean isValid = pluggableScmService.isValid(preprocessedGlobalScmConfig);
            BasicCruiseConfig.copyErrors(preprocessedGlobalScmConfig, globalScmConfig);
            return preprocessedGlobalScmConfig.getAllErrors().isEmpty() && scms.errors().isEmpty() && isValid;
        }
        BasicCruiseConfig.copyErrors(preprocessedGlobalScmConfig, globalScmConfig);
        return false;
    }

    @Override
    public SCM getPreprocessedEntityConfig() {
        return preprocessedGlobalScmConfig;
    }

    @Override
    public void clearErrors() {
        BasicCruiseConfig.clearErrors(globalScmConfig);
    }

    @Override
    public boolean canContinue(CruiseConfig cruiseConfig) {
        return isAuthorized();
    }

    private boolean isAuthorized() {
        if (!(goConfigService.isUserAdmin(currentUser) || goConfigService.isGroupAdministrator(currentUser.getUsername()))) {
            result.forbidden(EntityType.SCM.forbiddenToEdit(globalScmConfig.getId(), currentUser.getUsername()), forbidden());
            return false;
        }
        return true;
    }

    SCM findSCM(CruiseConfig cruiseConfig) {
        SCMs scms = cruiseConfig.getSCMs();
        SCM existingSCM = scms.find(globalScmConfig.getSCMId());
        if (existingSCM == null) {
            result.notFound(EntityType.SCM.notFoundMessage(globalScmConfig.getSCMId()), HealthStateType.notFound());
            throw new NullPointerException(String.format("The pluggable scm material with id '%s' is not found.", globalScmConfig.getSCMId()));
        } else {
            return existingSCM;
        }
    }
}


text:
package dockermachine

import (
	"bufio"
	"bytes"
	"net/http"
	"path/filepath"
	"runtime"
	"strings"

	dockerclient "github.com/docker/docker/client"
	"github.com/docker/go-connections/tlsconfig"
	"github.com/openshift/origin/pkg/oc/bootstrap/docker/dockerhelper"
	"github.com/openshift/origin/pkg/oc/bootstrap/docker/errors"
	"github.com/openshift/origin/pkg/oc/bootstrap/docker/localcmd"
	"k8s.io/apimachinery/pkg/util/net"
)

// IsRunning returns true if a Docker machine is running
func IsRunning(name string) bool {
	err := localcmd.New(dockerMachineBinary()).Args("ip", name).Run()
	return err == nil
}

// IP returns the IP address of the Docker machine
func IP(name string) (string, error) {
	output, _, err := localcmd.New(dockerMachineBinary()).Args("ip", name).Output()
	if err != nil {
		return "", ErrDockerMachineExec("ip", err)
	}
	return strings.TrimSpace(output), nil
}

// Start starts up an existing Docker machine
func Start(name string) error {
	err := localcmd.New(dockerMachineBinary()).Args("start", name).Run()
	if err != nil {
		return ErrDockerMachineExec("start", err)
	}
	return nil
}

// Client returns a Docker client for the given Docker machine
func Client(name string) (dockerhelper.Interface, error) {
	output, _, err := localcmd.New(dockerMachineBinary()).Args("env", name).Output()
	if err != nil {
		return nil, ErrDockerMachineExec("env", err)
	}
	scanner := bufio.NewScanner(bytes.NewBufferString(output))
	var (
		dockerHost, certPath string
		tlsVerify            bool
	)
	prefix := "export "
	if runtime.GOOS == "windows" {
		prefix = "SET "
	}
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, prefix) {
			line = strings.TrimPrefix(line, prefix)
			parts := strings.SplitN(line, "=", 2)
			if len(parts) != 2 {
				continue
			}
			switch strings.ToUpper(parts[0]) {
			case "DOCKER_HOST":
				dockerHost = strings.Trim(parts[1], "\"")
			case "DOCKER_CERT_PATH":
				certPath = strings.Trim(parts[1], "\"")
			case "DOCKER_TLS_VERIFY":
				tlsVerify = len(parts[1]) > 0
			}
		}
	}
	var httpClient *http.Client
	if len(certPath) > 0 {
		tlscOptions := tlsconfig.Options{
			CAFile:             filepath.Join(certPath, "ca.pem"),
			CertFile:           filepath.Join(certPath, "cert.pem"),
			KeyFile:            filepath.Join(certPath, "key.pem"),
			InsecureSkipVerify: !tlsVerify,
		}
		tlsc, tlsErr := tlsconfig.Client(tlscOptions)
		if tlsErr != nil {
			return nil, errors.NewError("could not create TLS config client for machine %s", name).WithCause(tlsErr)
		}
		httpClient = &http.Client{
			Transport: net.SetTransportDefaults(&http.Transport{
				TLSClientConfig: tlsc,
			}),
		}
	}

	engineAPIClient, err := dockerclient.NewClient(dockerHost, "1.24", httpClient, nil)
	if err != nil {
		return nil, errors.NewError("cannot create Docker engine API client").WithCause(err)
	}
	return dockerhelper.NewClient(dockerHost, engineAPIClient), nil
}

func dockerMachineBinary() string {
	if runtime.GOOS == "windows" {
		return "docker-machine.exe"
	}
	return "docker-machine"
}


text:
"use strict";
const TextLintTester = require("textlint-tester");
const tester = new TextLintTester();
const rule = require("../src/textlint-rule-google-quotation-marks");
tester.run("textlint-rule-google-quotation-marks", rule, {
    valid: [
        'See the section titled "Care and feeding of the emu."',
        'If you enter "foo", the program crashes.',
        "If you enter `foo`, the program crashes.",
        "In the latter case, put the primary speaker's quote in double quotation marks and the quote inside the primary speaker's quote in single quotation marks, in the standard American style. (This is opposite to the standard British style.)",
        'My high school English teacher made me learn that Shakespeare quote: "All the world\'s a stage, And all the men and women merely players ...."',
        'document it as "click Save".', // <= keyword,
        `She said, "I heard him shout 'Help', and saw him floundering in the water."`
    ],
    invalid: [
        // Commas and periods with quotation marks
        // {
        //     text: "See the section titled \"Care and feeding of the emu\".",
        //     output: "See the section titled \"Care and feeding of the emu.\"",
        //     errors: [
        //         {}
        //     ]
        // },
        // {
        //     text: "If you enter \"foo,\" the program crashes.",
        //     output: "If you enter \"foo\", the program crashes.",
        //     errors: [
        //         {}
        //     ]
        // },
        // Single quotation marks
        {
            text: `She said, 'I heard him shout "Help", and saw him floundering in the water.'`,
            output: `She said, "I heard him shout 'Help', and saw him floundering in the water."`,
            errors: [{}]
        }
    ]
});


text:
GridEnhancer
============

Magento Grid Enhancer v0.3.0.

What it does
----------
The Grid Enhancer extension allows you to manage the columns in the following grids:
 - Products grid
 - Customers grid
 - Product attributes grid
 - Catalog price rules grid
 - Shopping cart price rules
 - CMS Pages

Other grids may follow.
Since in a web shop different admins need different information displayed on the grid, each admin can manage it's own grid.
The guys in charge of marketing may want to see the special price.
The special price may not have any value to the people in charge of delivery. They may want to see the product weight.
Both of the above have no meaning to a the person in charge of SEO, that might want to see the meta title and keywords in the grid.
You get the point.

Reqiurements
--------
Magento CE 1.7.0.2 or 1.8.0.0.
it probably works on other versions. I didn't test.

How to use.
----------

After installation go to `Catalog->Manage products` and near the `Add product` button you should see a button called `Manage columns`.
This button will take you to a new page where you can add columns to the grid. You cannot remove default columns.
Click on the add column button on the top right and you should see 2 dropdowns. One with the available attributes and one with the columns that are already in the grid.
The first one determines the attribute and the second the position.

It works the same for the other supported grids.

You can add as many columns as you want. Just don't over do it.
When you are done click on `Save`.
If you get tired of the columns you have you can go to the same page and delete the configuration. This will make you see the default grid.

Warning
--------
Each admin can manage his own columns, if he has access to it.
The configuration you set is not available for other admins.
A way to modify what other admins see will follow (maybe).

Limitations
--------
Now all attributes can be shown in the grid. Image attributes are not yet supported.
Not all columns you add support sorting. This is a magento limitation. See the comment in  `Easylife_GridEnhancer_Model_Observer_Abstract::_getColumnConfig()`
Because of the way the attribute grid is constructed, you can use observers just to add columns at the beginning of the grid. I didn't want to rewrite that block also, so this is a limitation.

Rewrite and conflicts
----------
The extension rewrites the customer grid block (`Mage_Adminhtml_Block_Customer_Grid`) in order to be able to add to collection the selected columns.
The extension might conflict with other extensions that alter the grids that can be enhanced.
If the extensions that modify the product grid (and other grids) are properly written this should still work.
If you manually added columns in the grids and they do not appear in the position field modify this section of the `config.xml` by adding your columns: Xpath: `config/gridenhancer/{GRID_IDENTIFIER_HERE}/system_attributes`.

Known issue(s):
-------
If you choose to add a column after the `Name` column in the product grid and you look at the grid in a specific store then your new column will appear after the `Name` column and you cannot set it to appear after `Name in store` column.

Uninstall
-------

To uninstall the extension delete the following files and folders
 - app/etc/modules/Easylife_GridEnhancer.xml
 - app/locale/en\_US/Easylife\_GridEnhancer.csv
 - app/code/community/Easylife\_GridEnhancer/
 - app/design/adminhtml/default/default/layout/easylife\_gridenhancer.xml
 - app/design/adminhtml/default/default/template/easylife\_gridenhancer/
 - js/easylife\_gridenhancer/

Run these queries on your database. Add table prefix if you have one:
 - `DROP TABLE easylife_gridenhancer_settings;`
 - `DELETE FROM core_resource where code = 'easylife_gridenahcer_setup'`

Bug Report
------
Please submit any bugs or feature requests here.

Lessons learned
--------
IE does not like it when you add a function called "delete" inside a prototype js "class".
IE does not take into account the "selected" parameter when creating a select option using `new Option(label, value, selected)`


text:
package org.javalite.test.jspec;

public final class JSpec{

    private JSpec() {

    }

    public static Expectation<Object> a(Object o1){
        return new Expectation<>(o1);
    }

    /**
     * Synonym of methods {@link JSpec#the(Object)} or {@link JSpec#a(Object)}.
     *
     * @param o1 instance for checking
     * @return generalized expectation
     */
    public static Expectation<Object> $(Object o1){
        return a(o1);
    }

    public static Expectation<Object> the(Object o1){
        return a(o1);
    }

    /**
     * Works the same way as methods {@link JSpec#the(Object)} or {@link JSpec#a(Object)}, but takes generalized instance as parameter.

     * For example you can't use it(12345).shouldBeEqual("12345"); you will get compilation error.

     * You can perform checking only for the same type instances.

     *
     * Valid examples:
     *

     *
it(1).shouldNotBeEqual(2)

     *
it("a").shouldNotBeEqual("b")

     *

     *

     *
     * Not valid examples:
     *

     *
it(1L).shouldNotBeEqual(2)

     *
it("aaa").shouldNotBeEqual(1)

     *

     *
     * @param <T> generic type of expectation
     * @param o1 generic instance for checking
     * @return generalized expectation
     */
    public static <T> Expectation<T> it(T o1) {
        return new Expectation<T>(o1);
    }

    public static <T> void expect(ExceptionExpectation<T> expectation){

        try{
            expectation.exec();
        }catch(Exception e){
            if(!e.getClass().getName().equals(expectation.getClazz().getName())){
                e.printStackTrace();
                throw new TestException("Expected exception: " + expectation.getClazz() + ", but instead got: " + e);
            }

            return;
        }
        throw new  TestException("Expected exception: " + expectation.getClazz() + ", but instead got nothing");
    }

    /**
     * Expect that the results are different, throw TestException if same.
     *
     * @param expectation difference expectation.
     */
    public static <T> void expect(DifferenceExpectation<T> expectation) {
        a(expectation.getExpected()).shouldNotBeEqual(expectation.exec());
    }
}


text:
<?php

namespace SOPHP\Core\Service\Discovery\Registry\Exception;

use Exception;
use RuntimeException;

class RegistrationFailed extends RuntimeException {
    public function __construct($message = "Service Registration Failed", $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

}


text:
<MarketplaceDetails>
  <SmallAppTile>logo_99x99.png</SmallAppTile>
  <LargeAppTile>logo_173x173.png</LargeAppTile>
  <PCAppTile>logo_200x200.png</PCAppTile>
  <ScreenShots>SH.png;SH2.png;;;;;;;</ScreenShots>
</MarketplaceDetails>


text:
<?php

declare(strict_types=1);

namespace Faker\Test\Core;

use Faker\Test\TestCase;
use Faker\UniqueGenerator;

final class BloodTest extends TestCase
{
    public function testBloodType(): void
    {
        $expected = [
            'A',
            'AB',
            'B',
            'O',
        ];

        $faker = new UniqueGenerator($this->faker);

        $generated = [];

        for ($i = 0; $i < count($expected); ++$i) {
            $generated[] = $faker->bloodType();
        }

        self::assertEqualsCanonicalizing($expected, $generated);
    }

    public function testBloodRh(): void
    {
        $expected = [
            '+',
            '-',
        ];

        $faker = new UniqueGenerator($this->faker);

        $generated = [];

        for ($i = 0; $i < count($expected); ++$i) {
            $generated[] = $faker->bloodRh();
        }

        self::assertEqualsCanonicalizing($expected, $generated);
    }

    public function testBloodGroup(): void
    {
        $expected = [
            'A+',
            'A-',
            'AB+',
            'AB-',
            'B+',
            'B-',
            'O+',
            'O-',
        ];

        $faker = new UniqueGenerator($this->faker);

        $generated = [];

        for ($i = 0; $i < count($expected); ++$i) {
            $generated[] = $faker->bloodGroup();
        }

        self::assertEqualsCanonicalizing($expected, $generated);
    }
}


text:
import pymdownx.emoji
from bleach.sanitizer import Cleaner
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model
from django.utils.encoding import force_str
from django.utils.html import escape
from djblets import markdown as djblets_markdown
from djblets.siteconfig.models import SiteConfiguration
from markdown import markdown

# Keyword arguments used when calling a Markdown renderer function.
#
# We use XHTML instead of HTML5 to ensure the results can be parsed by an
# XML parser, needed for doing diffs in change descriptions and the Markdown
# review UI.
MARKDOWN_KWARGS = {
    'enable_attributes': False,
    'output_format': 'xhtml',
    'lazy_ol': False,
    'extensions': [
        'markdown.extensions.fenced_code',
        'markdown.extensions.codehilite',
        'markdown.extensions.sane_lists',
        'markdown.extensions.tables',
        'markdown.extensions.nl2br',
        'pymdownx.tilde',
        'pymdownx.emoji',
        'djblets.markdown.extensions.escape_html',
        'djblets.markdown.extensions.wysiwyg',
    ],
    'extension_configs': {
        'markdown.extensions.codehilite': {
            'guess_lang': False,
        },
        'pymdownx.emoji': {
            'emoji_index': pymdownx.emoji.gemoji,
            'options': {
                'classes': 'emoji',
                'image_path': ('https://github.githubassets.com/images/icons/'
                               'emoji/unicode/'),
                'non_standard_image_path': ('https://github.githubassets.com/'
                                            'images/icons/emoji/'),
            },
        },
    },
}

#: A list of HTML tags considered to be safe in Markdown-generated output.
#:
#: Anything not in this list will be escaped when sanitizing the resulting
#: HTML.
#:
#: Version Added:
#:     3.0.22
SAFE_MARKDOWN_TAGS = [
    'a',
    'b',
    'blockquote',
    'br',
    'code',
    'dd',
    'del',
    'div',
    'dt',
    'em',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'hr',
    'i',
    'img',
    'li',
    'ol',
    'p',
    'pre',
    'span',
    'strong',
    'sub',
    'sup',
    'table',
    'tbody',
    'td',
    'foot',
    'th',
    'thead',
    'tr',
    'tt',
    'ul',
]

#: Mappings of HTML tags to attributes considered to be safe for Markdown.
#:
#: Anything not in this list will be removed when sanitizing the resulting
#: HTML.
#:
#: Version Added:
#:     3.0.22
SAFE_MARKDOWN_ATTRS = {
    '*': ['class', 'id'],
    'a': ['href', 'alt', 'title'],
    'img': ['src', 'alt', 'title'],
}

#: A list of protocols considered safe for URLs.
#:
#: This can be overridden by setting
#: ``settings.ALLOWED_MARKDOWN_URL_PROTOCOLS``.
#:
#: Version Added:
#:     3.0.24
SAFE_MARKDOWN_URL_PROTOCOLS = ['http', 'https', 'mailto']

def markdown_escape_field(obj, field_name):
    """Escapes Markdown text in a model or dictionary's field.

    This is a convenience around markdown_escape to escape the contents of
    a particular field in a model or dictionary.
    """
    if isinstance(obj, Model):
        setattr(obj, field_name,
                djblets_markdown.markdown_escape(getattr(obj, field_name)))
    elif isinstance(obj, dict):
        obj[field_name] = djblets_markdown.markdown_escape(obj[field_name])
    else:
        raise TypeError('Unexpected type %r passed to markdown_escape_field'
                        % obj)

def markdown_unescape_field(obj, field_name):
    """Unescapes Markdown text in a model or dictionary's field.

    This is a convenience around markdown_unescape to unescape the contents of
    a particular field in a model or dictionary.
    """
    if isinstance(obj, Model):
        setattr(obj, field_name,
                djblets_markdown.markdown_unescape(getattr(obj, field_name)))
    elif isinstance(obj, dict):
        obj[field_name] = djblets_markdown.markdown_unescape(obj[field_name])
    else:
        raise TypeError('Unexpected type %r passed to markdown_unescape_field'
                        % obj)

def normalize_text_for_edit(user, text, rich_text, escape_html=True):
    """Normalizes text, converting it for editing.

    This will normalize text for editing based on the rich_text flag and
    the user settings.

    If the text is not in Markdown and the user edits in Markdown by default,
    this will return the text escaped for edit. Otherwise, the text is
    returned as-is.
    """
    if text is None:
        return ''

    if not rich_text and is_rich_text_default_for_user(user):
        # This isn't rich text, but it's going to be edited as rich text,
        # so escape it.
        text = djblets_markdown.markdown_escape(text)

    if escape_html:
        text = escape(text)

    return text

def markdown_render_conditional(text, rich_text):
    """Return the escaped HTML content based on the rich_text flag."""
    if rich_text:
        return render_markdown(text)
    else:
        return escape(text)

def is_rich_text_default_for_user(user):
    """Returns whether the user edits in Markdown by default."""
    if user.is_authenticated:
        try:
            return user.get_profile().should_use_rich_text
        except ObjectDoesNotExist:
            pass

    siteconfig = SiteConfiguration.objects.get_current()

    return siteconfig.get('default_use_rich_text')

def markdown_set_field_escaped(obj, field, escaped):
    """Escapes or unescapes the specified field in a model or dictionary."""
    if escaped:
        markdown_escape_field(obj, field)
    else:
        markdown_unescape_field(obj, field)

def clean_markdown_html(html):
    """Return a cleaned, secure version of Markdown-rendered HTML/XHTML.

    This will sanitize Markdown-rendered HTML, ensuring that only a trusted
    list of HTML tags, attributes, and URI schemes are included in the
    HTML. Anything else will be left out or transformed into a safe
    representation of the original content.

    The result will always be in XHTML form, to allow for XML processing of the
    content.

    Version Added:
        3.0.24

    Args:
        html (unicode):
            The Markdown-rendered HTML to clean.

    Returns:
        unicode:
        A sanitizied XHTML representation of the Markdown-rendered HTML.
    """
    # Allow users to override the protocols. We're checking for this
    # dynamically, partly to ease unit testing, and partly to eventually
    # allow dynamic configuration.
    safe_url_protocols = SAFE_MARKDOWN_URL_PROTOCOLS
    custom_safe_url_protocols = settings.ALLOWED_MARKDOWN_URL_PROTOCOLS

    if custom_safe_url_protocols:
        safe_url_protocols = list(
            set(safe_url_protocols) |
            set(custom_safe_url_protocols))

    # Create a bleach HTML cleaner, and override settings on the html5lib
    # serializer it contains to ensure we use self-closing HTML tags, like
    # <br/>. This is needed so that we can parse the resulting HTML in
    # Djblets for things like Markdown diffing.
    cleaner = Cleaner(tags=SAFE_MARKDOWN_TAGS,
                      attributes=SAFE_MARKDOWN_ATTRS,
                      protocols=safe_url_protocols)
    cleaner.serializer.use_trailing_solidus = True

    return cleaner.clean(html)

def render_markdown(text):
    """Render Markdown text to XHTML.

    The Markdown text will be sanitized to prevent injecting custom HTML
    or dangerous links. It will also enable a few plugins for code
    highlighting and sane lists.

    It's rendered to XHTML in order to allow the element tree to be easily
    parsed for code review and change description diffing.

    Args:
        text (bytes or unicode):
            The Markdown text to render.

            If this is a byte string, it must represent UTF-8-encoded text.

    Returns:
        unicode:
        The Markdown-rendered XHTML.
    """
    return clean_markdown_html(markdown(force_str(text), **MARKDOWN_KWARGS))

def render_markdown_from_file(f):
    """Render Markdown text from a file to XHTML.

    The Markdown text will be sanitized to prevent injecting custom HTML.
    It will also enable a few plugins for code highlighting and sane lists.

    Version Changed:
        3.0.24:
        This has been updated to sanitize the rendered HTML to avoid any
        security issues.

    Args:
        f (file):
            The file stream to read from.

    Returns:
        unicode:
        The Markdown-rendered XHTML.
    """
    return clean_markdown_html(djblets_markdown.render_markdown_from_file(
        f, **MARKDOWN_KWARGS))


text:
@interface BTAPIHTTP ()

@property (nonatomic, strong) NSString *accessToken;

@end

@implementation BTAPIHTTP

- (instancetype)initWithBaseURL:(NSURL *)URL accessToken:(NSString *)accessToken {
    if (self = [super initWithBaseURL:URL]) {
        self.accessToken = accessToken;
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        configuration.HTTPAdditionalHeaders = self.defaultHeaders;

        NSOperationQueue *delegateQueue = [[NSOperationQueue alloc] init];
        delegateQueue.name = @"com.braintreepayments.BTHTTP";
        delegateQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;

        self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:delegateQueue];
        self.pinnedCertificates = [BTAPIPinnedCertificates trustedCertificates];
    }
    return self;
}

- (NSDictionary *)defaultHeaders {
        return @{ @"User-Agent": [self userAgentString],
                  @"Accept": [self acceptString],
                  @"Accept-Language": [self acceptLanguageString],
                  @"Braintree-Version": BT_API_VERSION,
                  @"Authorization": [NSString stringWithFormat:@"Bearer %@", self.accessToken]};
}

@end


text:
#include "wx/wxprec.h"

#if wxUSE_METAFILE

#ifndef WX_PRECOMP
    #include "wx/utils.h"
    #include "wx/app.h"
#endif

#include "wx/metafile.h"
#include "wx/clipbrd.h"
#include "wx/osx/private.h"
#include "wx/graphics.h"
#include "wx/osx/metafile.h"

#include <stdio.h>
#include <string.h>

IMPLEMENT_DYNAMIC_CLASS(wxMetafile, wxObject)
IMPLEMENT_ABSTRACT_CLASS(wxMetafileDC, wxDC)
IMPLEMENT_ABSTRACT_CLASS(wxMetafileDCImpl, wxGCDCImpl)

#define M_METAFILEREFDATA( a ) ((wxMetafileRefData*)(a).GetRefData())

class wxMetafileRefData : public wxGDIRefData
{
public:
    // default ctor needed for CreateGDIRefData(), must be initialized later
    wxMetafileRefData() { Init(); }

    // creates a metafile from memory, assumes ownership
    wxMetafileRefData(CFDataRef data);

    // prepares a recording metafile
    wxMetafileRefData( int width, int height);

    // prepares a metafile to be read from a file (if filename is not empty)
    wxMetafileRefData( const wxString& filename);

    virtual ~wxMetafileRefData();

    virtual bool IsOk() const { return m_data != NULL; }

    void Init();

    int GetWidth() const { return m_width; }
    int GetHeight() const { return m_height; }

    CGPDFDocumentRef GetPDFDocument() const { return m_pdfDoc; }
    void UpdateDocumentFromData() ;

    const wxCFDataRef& GetData() const { return m_data; }
    CGContextRef GetContext() const { return m_context; }

    // ends the recording
    void Close();
private:
    wxCFDataRef m_data;
    wxCFRef<CGPDFDocumentRef> m_pdfDoc;
    CGContextRef m_context;

    int m_width ;
    int m_height ;
};

wxMetafileRefData::wxMetafileRefData(CFDataRef data) :
    m_data(data)
{
    Init();
    UpdateDocumentFromData();
}

wxMetafileRefData::wxMetafileRefData( const wxString& filename )
{
    Init();

    if ( !filename.empty() )
    {
        wxCFRef<CFMutableStringRef> cfMutableString(CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(filename)));
        CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
        wxCFRef<CFURLRef> url(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kCFURLPOSIXPathStyle, false));
        m_pdfDoc.reset(CGPDFDocumentCreateWithURL(url));
    }
}

wxMetafileRefData::wxMetafileRefData( int width, int height)
{
    Init();

    m_width = width;
    m_height = height;

    CGRect r = CGRectMake( 0 , 0 , width  , height );

    CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0);
    m_data.reset(data);
    CGDataConsumerRef dataConsumer = wxMacCGDataConsumerCreateWithCFData(data);
    m_context = CGPDFContextCreate( dataConsumer, (width != 0 && height != 0) ? &r : NULL , NULL );
    CGDataConsumerRelease( dataConsumer );
    if ( m_context )
    {
        CGPDFContextBeginPage(m_context, NULL);

        CGColorSpaceRef genericColorSpace  = wxMacGetGenericRGBColorSpace();

        CGContextSetFillColorSpace( m_context, genericColorSpace );
        CGContextSetStrokeColorSpace( m_context, genericColorSpace );

        CGContextTranslateCTM( m_context , 0 ,  height ) ;
        CGContextScaleCTM( m_context , 1 , -1 ) ;
    }
}

wxMetafileRefData::~wxMetafileRefData()
{
}

void wxMetafileRefData::Init()
{
    m_context = NULL;
    m_width = -1;
    m_height = -1;
}

void wxMetafileRefData::Close()
{
    CGPDFContextEndPage(m_context);

    CGContextRelease(m_context);
    m_context = NULL;

    UpdateDocumentFromData();
}

void wxMetafileRefData::UpdateDocumentFromData()
{
    wxCFRef<CGDataProviderRef> provider(wxMacCGDataProviderCreateWithCFData(m_data));
    m_pdfDoc.reset(CGPDFDocumentCreateWithProvider(provider));
    if ( m_pdfDoc != NULL )
    {
        CGPDFPageRef page = CGPDFDocumentGetPage( m_pdfDoc, 1 );
        CGRect rect = CGPDFPageGetBoxRect ( page, kCGPDFMediaBox);
        m_width = static_cast<int>(rect.size.width);
        m_height = static_cast<int>(rect.size.height);
    }
}

wxMetaFile::wxMetaFile(const wxString& file)
{
    m_refData = new wxMetafileRefData(file);
}

wxMetaFile::~wxMetaFile()
{
}

wxGDIRefData *wxMetaFile::CreateGDIRefData() const
{
    return new wxMetafileRefData;
}

wxGDIRefData *wxMetaFile::CloneGDIRefData(const wxGDIRefData *data) const
{
    return new wxMetafileRefData(*static_cast<const wxMetafileRefData *>(data));
}

WXHMETAFILE wxMetaFile::GetHMETAFILE() const
{
    return (WXHMETAFILE) (CFDataRef) M_METAFILEDATA->GetData();
}

bool wxMetaFile::SetClipboard(int WXUNUSED(width), int WXUNUSED(height))
{
    bool success = true;

#if wxUSE_DRAG_AND_DROP
    if (m_refData == NULL)
        return false;

    bool alreadyOpen = wxTheClipboard->IsOpened();
    if (!alreadyOpen)
    {
        wxTheClipboard->Open();
        wxTheClipboard->Clear();
    }

    wxDataObject *data = new wxMetafileDataObject( *this );
    success = wxTheClipboard->SetData( data );
    if (!alreadyOpen)
        wxTheClipboard->Close();
#endif

    return success;
}

void wxMetafile::SetHMETAFILE(WXHMETAFILE mf)
{
    UnRef();

    m_refData = new wxMetafileRefData((CFDataRef)mf);
}

#if wxOSX_USE_COCOA_OR_CARBON && !defined( __LP64__ )
void wxMetafile::SetPICT(void* pictHandle)
{
    UnRef();

    Handle picHandle = (Handle) pictHandle;
    HLock(picHandle);
    CFDataRef data = CFDataCreateWithBytesNoCopy( kCFAllocatorDefault, (const UInt8*) *picHandle, GetHandleSize(picHandle), kCFAllocatorNull);
    wxCFRef<CGDataProviderRef> provider(wxMacCGDataProviderCreateWithCFData(data));
    QDPictRef pictRef = QDPictCreateWithProvider(provider);
    CGRect rect = QDPictGetBounds(pictRef);
    m_refData = new wxMetafileRefData(static_cast<int>(rect.size.width),
                                      static_cast<int>(rect.size.height));
    QDPictDrawToCGContext( ((wxMetafileRefData*) m_refData)->GetContext(), rect, pictRef );
    CFRelease( data );
    QDPictRelease( pictRef );
    ((wxMetafileRefData*) m_refData)->Close();
}
#endif

bool wxMetaFile::Play(wxDC *dc)
{
    if (!m_refData)
        return false;

    if (!dc->IsOk())
        return false;

    {
        wxDCImpl *impl = dc->GetImpl();
        wxGCDCImpl *gc_impl = wxDynamicCast(impl, wxGCDCImpl);
        if (gc_impl)
        {
            CGContextRef cg = (CGContextRef) (gc_impl->GetGraphicsContext()->GetNativeContext());
            CGPDFDocumentRef doc = M_METAFILEDATA->GetPDFDocument();
            CGPDFPageRef page = CGPDFDocumentGetPage( doc, 1 );
            wxMacCGContextStateSaver save(cg);
            CGContextDrawPDFPage( cg, page );
        }
//        CGContextTranslateCTM( cg, 0, bounds.size.width );
//        CGContextScaleCTM( cg, 1, -1 );
    }

    return true;
}

wxSize wxMetaFile::GetSize() const
{
    wxSize dataSize = wxDefaultSize;

    if (Ok())
    {
        dataSize.x = M_METAFILEDATA->GetWidth();
        dataSize.y = M_METAFILEDATA->GetHeight();
    }

    return dataSize;
}

// Metafile device context

// New constructor that takes origin and extent. If you use this, don't
// give origin/extent arguments to wxMakeMetaFilePlaceable.

wxMetafileDCImpl::wxMetafileDCImpl(
    wxDC *owner,
    const wxString& filename,
    int width, int height,
    const wxString& WXUNUSED(description) ) :
    wxGCDCImpl( owner )
{
    wxASSERT_MSG( width != 0 || height != 0, wxT("no arbitration of metafile size supported") );
    wxASSERT_MSG( filename.empty(), wxT("no file based metafile support yet"));

    m_metaFile = new wxMetaFile( filename );
    wxMetafileRefData* metafiledata = new wxMetafileRefData(width, height);
    m_metaFile->UnRef();
    m_metaFile->SetRefData( metafiledata );

    SetGraphicsContext( wxGraphicsContext::CreateFromNative(metafiledata->GetContext()));
    m_ok = (m_graphicContext != NULL) ;

    SetMapMode( wxMM_TEXT );
}

wxMetafileDCImpl::~wxMetafileDCImpl()
{
}

void wxMetafileDCImpl::DoGetSize(int *width, int *height) const
{
    wxCHECK_RET( m_metaFile, wxT("GetSize() doesn't work without a metafile") );

    wxSize sz = m_metaFile->GetSize();
    if (width)
        (*width) = sz.x;
    if (height)
        (*height) = sz.y;
}

wxMetaFile *wxMetafileDCImpl::Close()
{
    wxDELETE(m_graphicContext);
    m_ok = false;

    M_METAFILEREFDATA(*m_metaFile)->Close();

    return m_metaFile;
}

#if wxUSE_DATAOBJ
size_t wxMetafileDataObject::GetDataSize() const
{
    CFIndex length = 0;
    wxMetafileRefData* refData = M_METAFILEREFDATA(m_metafile);
    if ( refData )
        length = refData->GetData().GetLength();
    return length;
}

bool wxMetafileDataObject::GetDataHere(void *buf) const
{
    bool result = false;

    wxMetafileRefData* refData = M_METAFILEREFDATA(m_metafile);
    if ( refData )
    {
        CFIndex length = refData->GetData().GetLength();
        if ( length > 0 )
        {
            result = true ;
            refData->GetData().GetBytes(CFRangeMake(0,length), (UInt8 *) buf);
        }
    }
    return result;
}

bool wxMetafileDataObject::SetData(size_t len, const void *buf)
{
    wxMetafileRefData* metafiledata = new wxMetafileRefData(wxCFRefFromGet(wxCFDataRef((UInt8*)buf, len).get()));
    m_metafile.UnRef();
    m_metafile.SetRefData( metafiledata );
    return true;
}
#endif

#endif


text:
Self-Driving Car Engineer Nanodegree Program

## Reflection

### Use of Frenet Coordinates

The car in this project will exactly follow the x and y coordinates that are
passed to it. Frenet coordinates are used throughout the path planner because
they are easier to work with. The s and d coordinates are calculated using
helper functions and then converted back to x and y coordinates after for use in the simulator.

The car is able to stay within specific lanes using the d coordinate (width across
the road). The s coordinate is used to be able to determine the distance along
the road and is useful for determining distance between the ego vehicle and
other vehicles.

### Path Planning

The vehicle looks through sensor fusion data of all vehicles on the right-hand
side of the road and produces a cost for each lane based on the following:

* Distance from right lane (right lane is desired)
* Distance from current lane (changing lanes discouraged unless necessary)
* Distance to nearest vehicle in lane (further vehicle reduces cost)
* Average speed of vehicles ahead of current vehicle in lane (further from reference velocity is worse)

Once the cost is calculated for each lane, the lane with the smallest cost
is set to the desired lane. The lane is then assessed for other vehicles in
close proximity to determine if it is safe. If it is safe, the vehicle will
switch in the direction of the desired lane. In order to reduce jerk if
switching across two lanes, the vehicle waits at least 10 iterations before
switching two lanes. In order to avoid the vehicle switching lanes without
a safe velocity, lane changes are only performed above 30mph.

Finite states of keep lane, perform lane changes, and prepare for lane changes
are used in this path planner. They are simplified in that they do not involve
target velocities with acceleration / deceleration in this iteration.

### Path Smoothing

In order to produce a smooth trajectory, points from the previous path that
have not yet been visited are included. Equally spaced points in the s horizon
are used to determine the trajectory. A spline is then fit to these future
points to smooth the trajectory. Points along this spline are chosen
that will be within safe acceleration limits and finally converted to x, y
coordinates for use in the simulator.

### Results

The car is able to successfully navigate along the highway without colliding
or exceeding jerk requirements. In testing, the path planner is able to run
for more than 30 minutes without incidents. Though it performs well, the path planner
is not always optimal and is often overcautious with changing lanes. There can of course
be unanticipated simulator behaviour which results in near-misses.

### Future Improvements

The following can be done to improve the path planner further:

* Following target velocities of different vehicles for reduced acceleration changes
* Using polynomial fitting for jerk minimizing paths
* Predicting other vehicles' intentions using a classification algorithm such as Naive Bayes
* More precise definitions of finite states which might result in smoother and less overtly cautious lane changing.

### Simulator. You can download the Term3 Simulator BETA which contains the Path Planning Project from the [releases tab](https://github.com/udacity/self-driving-car-sim/releases).

In this project your goal is to safely navigate around a virtual highway with other traffic that is driving +-10 MPH of the 50 MPH speed limit. You will be provided the car's localization and sensor fusion data, there is also a sparse map list of waypoints around the highway. The car should try to go as close as possible to the 50 MPH speed limit, which means passing slower traffic when possible, note that other cars will try to change lanes too. The car should avoid hitting other cars at all cost as well as driving inside of the marked road lanes at all times, unless going from one lane to another. The car should be able to make one complete loop around the 6946m highway. Since the car is trying to go 50 MPH, it should take a little over 5 minutes to complete 1 loop. Also the car should not experience total acceleration over 10 m/s^2 and jerk that is greater than 50 m/s^3.

#### The map of the highway is in data/highway_map.txt
Each waypoint in the list contains  [x,y,s,dx,dy] values. x and y are the waypoint's map coordinate position, the s value is the distance along the road to get to that waypoint in meters, the dx and dy values define the unit normal vector pointing outward of the highway loop.

The highway's waypoints loop around so the frenet s value, distance along the road, goes  from 0 to 6945.554.

## Basic Build Instructions

1. Clone this repo.
2. Make a build directory: `mkdir build && cd build`
3. Compile: `cmake .. && make`
4. Run it: `./path_planning`.

Here is the data provided from the Simulator to the C++ Program

#### Main car's localization Data (No Noise)

["x"] The car's x position in map coordinates

["y"] The car's y position in map coordinates

["s"] The car's s position in frenet coordinates

["d"] The car's d position in frenet coordinates

["yaw"] The car's yaw angle in the map

["speed"] The car's speed in MPH

#### Previous path data given to the Planner

//Note: Return the previous list but with processed points removed, can be a nice tool to show how far along
the path has processed since last time.

["previous_path_x"] The previous list of x points previously given to the simulator

["previous_path_y"] The previous list of y points previously given to the simulator

#### Previous path's end s and d values

["end_path_s"] The previous list's last point's frenet s value

["end_path_d"] The previous list's last point's frenet d value

#### Sensor Fusion Data, a list of all other car's attributes on the same side of the road. (No Noise)

["sensor_fusion"] A 2d vector of cars and then that car's [car's unique ID, car's x position in map coordinates, car's y position in map coordinates, car's x velocity in m/s, car's y velocity in m/s, car's s position in frenet coordinates, car's d position in frenet coordinates.

## Details

1. The car uses a perfect controller and will visit every (x,y) point it recieves in the list every .02 seconds. The units for the (x,y) points are in meters and the spacing of the points determines the speed of the car. The vector going from a point to the next point in the list dictates the angle of the car. Acceleration both in the tangential and normal directions is measured along with the jerk, the rate of change of total Acceleration. The (x,y) point paths that the planner recieves should not have a total acceleration that goes over 10 m/s^2, also the jerk should not go over 50 m/s^3. (NOTE: As this is BETA, these requirements might change. Also currently jerk is over a .02 second interval, it would probably be better to average total acceleration over 1 second and measure jerk from that.

2. There will be some latency between the simulator running and the path planner returning a path, with optimized code usually its not very long maybe just 1-3 time steps. During this delay the simulator will continue using points that it was last given, because of this its a good idea to store the last points you have used so you can have a smooth transition. previous_path_x, and previous_path_y can be helpful for this transition since they show the last points given to the simulator controller with the processed points already removed. You would either return a path that extends this previous path or make sure to create a new path that has a smooth transition with this last path.

## Dependencies

* cmake >= 3.5
 * All OSes: [click here for installation instructions](https://cmake.org/install/)
* make >= 4.1
  * Linux: make is installed by default on most Linux distros
  * Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/)
  * Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm)
* gcc/g++ >= 5.4
  * Linux: gcc / g++ is installed by default on most Linux distros
  * Mac: same deal as make - [install Xcode command line tools]((https://developer.apple.com/xcode/features/)
  * Windows: recommend using [MinGW](http://www.mingw.org/)
* [uWebSockets](https://github.com/uWebSockets/uWebSockets)
  * Run either `install-mac.sh` or `install-ubuntu.sh`.
  * If you install from source, checkout to commit `e94b6e1`, i.e.
    ```
    git clone https://github.com/uWebSockets/uWebSockets
    cd uWebSockets
    git checkout e94b6e1
    ```


text:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.samples.androidtesting.login.LoginFragment"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <EditText
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/hint_name"
        android:inputType="textPersonName"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/email"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <Button
        android:id="@+id/login"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="32dp"
        android:text="@string/button_login"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/email" />
</android.support.constraint.ConstraintLayout>


text:
#if NET40
namespace Fx.Serialization
{
    using System.Text;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Unit tests for the <see cref="JsonSerializer"/>
    /// </summary>
    /// <threadsafety static="true" instance="true"/>
    [TestClass]
    public sealed class JsonSerializerUnitTests
    {
        #region Default

        /// <summary>
        /// Serializes and deserializes an object to bytes and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to bytes and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void SerializeBytes()
        {
            SerializerUnitTests.SerializeBytes(JsonSerializer.Default);
        }

        /// <summary>
        /// Serializes and deserializes an object to a stream and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to a stream and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void SerializeStream()
        {
            SerializerUnitTests.SerializeStream(JsonSerializer.Default);
        }

        /// <summary>
        /// Serializes and deserializes an object to a string and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to a string and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void SerializeString()
        {
            SerializerUnitTests.SerializeString(JsonSerializer.Default);
        }

        /// <summary>
        /// Serializes and deserializes a string and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes a string and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void StringSerialization()
        {
            SerializerUnitTests.StringSerialization(JsonSerializer.Default);
        }

        #endregion

        #region ASCII

        /// <summary>
        /// Serializes and deserializes an object to bytes and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to bytes and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void AsciiSerializeBytes()
        {
            SerializerUnitTests.SerializeBytes(JsonSerializer.Create(Encoding.ASCII));
        }

        /// <summary>
        /// Serializes and deserializes an object to a stream and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to a stream and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void AsciiSerializeStream()
        {
            SerializerUnitTests.SerializeStream(JsonSerializer.Create(Encoding.ASCII));
        }

        /// <summary>
        /// Serializes and deserializes an object to a string and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes an object to a string and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void AsciiSerializeString()
        {
            SerializerUnitTests.SerializeString(JsonSerializer.Create(Encoding.ASCII));
        }

        /// <summary>
        /// Serializes and deserializes a string and asserts that they are equivalent
        /// </summary>
        [TestCategory("Unit")]
        [Description("Serializes and deserializes a string and asserts that they are equivalent")]
        [Priority(1)]
        [TestMethod]
        public void AsciiStringSerialization()
        {
            SerializerUnitTests.StringSerialization(JsonSerializer.Create(Encoding.ASCII));
        }

        #endregion

        /// <summary>
        /// Creates the default instance of the serializer
        /// </summary>
        [TestCategory("Unit")]
        [Description("Creates the default instance of the serializer")]
        [Priority(1)]
        [TestMethod]
        public void DefaultCreation()
        {
            Assert.AreEqual(JsonSerializer.Default, JsonSerializer.Create(Encoding.UTF8));
        }
    }
}
#endif


text:
namespace SynoDuplicateFolders.Data
{
    public class SynoReportContentTimeLine : BSynoReportTimeLine
    {
        public SynoReportContentTimeLine()
            : base()
        { }
    }
}


text:
var END = {
  mousedown:     'mouseup',
  touchstart:    'touchend',
  pointerdown:   'touchend',
  MSPointerDown: 'touchend'
};

var MOVE = {
  mousedown:     'mousemove',
  touchstart:    'touchmove',
  pointerdown:   'touchmove',
  MSPointerDown: 'touchmove'
};

function distance(a, b) {
  var dx = a.x - b.x, dy = a.y - b.y;
  return Math.sqrt(dx * dx + dy * dy);
}

/**
 * Drag handler
 * @class L.Path.Drag
 * @extends {L.Handler}
 */
L.Handler.PathDrag = L.Handler.extend( /** @lends  L.Path.Drag.prototype */ {

  statics: {
    DRAGGING_CLS: 'leaflet-path-draggable',
  },

  /**
   * @param  {L.Path} path
   * @constructor
   */
  initialize: function(path) {

    /**
     * @type {L.Path}
     */
    this._path = path;

    /**
     * @type {Array.<Number>}
     */
    this._matrix = null;

    /**
     * @type {L.Point}
     */
    this._startPoint = null;

    /**
     * @type {L.Point}
     */
    this._dragStartPoint = null;

    /**
     * @type {Boolean}
     */
    this._mapDraggingWasEnabled = false;

  },

  /**
   * Enable dragging
   */
  addHooks: function() {
    this._path.on('mousedown', this._onDragStart, this);

    this._path.options.className = this._path.options.className ?
        (this._path.options.className + ' ' + L.Handler.PathDrag.DRAGGING_CLS) :
         L.Handler.PathDrag.DRAGGING_CLS;

    if (this._path._path) {
      L.DomUtil.addClass(this._path._path, L.Handler.PathDrag.DRAGGING_CLS);
    }
  },

  /**
   * Disable dragging
   */
  removeHooks: function() {
    this._path.off('mousedown', this._onDragStart, this);

    this._path.options.className = this._path.options.className
      .replace(new RegExp('\\s+' + L.Handler.PathDrag.DRAGGING_CLS), '');
    if (this._path._path) {
      L.DomUtil.removeClass(this._path._path, L.Handler.PathDrag.DRAGGING_CLS);
    }
  },

  /**
   * @return {Boolean}
   */
  moved: function() {
    return this._path._dragMoved;
  },

  /**
   * Start drag
   * @param  {L.MouseEvent} evt
   */
  _onDragStart: function(evt) {
    var eventType = evt.originalEvent._simulated ? 'touchstart' : evt.originalEvent.type;

    this._mapDraggingWasEnabled = false;
    this._startPoint = evt.containerPoint.clone();
    this._dragStartPoint = evt.containerPoint.clone();
    this._matrix = [1, 0, 0, 1, 0, 0];
    L.DomEvent.stop(evt.originalEvent);

    L.DomUtil.addClass(this._path._renderer._container, 'leaflet-interactive');
    L.DomEvent
      .on(document, MOVE[eventType], this._onDrag,    this)
      .on(document, END[eventType],  this._onDragEnd, this);

    if (this._path._map.dragging.enabled()) {
      // I guess it's required because mousdown gets simulated with a delay
      //this._path._map.dragging._draggable._onUp(evt);

      this._path._map.dragging.disable();
      this._mapDraggingWasEnabled = true;
    }
    this._path._dragMoved = false;

    if (this._path._popup) { // that might be a case on touch devices as well
      this._path._popup._close();
    }

    this._replaceCoordGetters(evt);
  },

  /**
   * Dragging
   * @param  {L.MouseEvent} evt
   */
  _onDrag: function(evt) {
    L.DomEvent.stop(evt);

    var first = (evt.touches && evt.touches.length >= 1 ? evt.touches[0] : evt);
    var containerPoint = this._path._map.mouseEventToContainerPoint(first);

    // skip taps
    if (evt.type === 'touchmove' && !this._path._dragMoved) {
      var totalMouseDragDistance = this._dragStartPoint.distanceTo(containerPoint);
      if (totalMouseDragDistance <= this._path._map.options.tapTolerance) {
        return;
      }
    }

    var x = containerPoint.x;
    var y = containerPoint.y;

    var dx = x - this._startPoint.x;
    var dy = y - this._startPoint.y;

    // Send events only if point was moved
    if (dx || dy) {
      if (!this._path._dragMoved) {
        this._path._dragMoved = true;
        this._path.fire('dragstart', evt);
        // we don't want that to happen on click
        this._path.bringToFront();
      }

      this._matrix[4] += dx;
      this._matrix[5] += dy;

      this._startPoint.x = x;
      this._startPoint.y = y;

      this._path.fire('predrag', evt);
      this._path._transform(this._matrix);
      this._path.fire('drag', evt);
    }
  },

  /**
   * Dragging stopped, apply
   * @param  {L.MouseEvent} evt
   */
  _onDragEnd: function(evt) {
    var containerPoint = this._path._map.mouseEventToContainerPoint(evt);
    var moved = this.moved();

    // apply matrix
    if (moved) {
      this._transformPoints(this._matrix);
      this._path._updatePath();
      this._path._project();
      this._path._transform(null);

      L.DomEvent.stop(evt);
    }

    L.DomEvent.off(document, 'mousemove touchmove', this._onDrag,    this);
    L.DomEvent.off(document, 'mouseup touchend',    this._onDragEnd, this);

    this._restoreCoordGetters();

    // consistency
    if (moved) {
      this._path.fire('dragend', {
        distance: distance(this._dragStartPoint, containerPoint)
      });

      // hack for skipping the click in canvas-rendered layers
      var contains = this._path._containsPoint;
      this._path._containsPoint = L.Util.falseFn;
      L.Util.requestAnimFrame(function() {
        L.DomEvent.skipped({ type: 'click' });
        this._path._containsPoint = contains;
      }, this);
    }

    this._matrix          = null;
    this._startPoint      = null;
    this._dragStartPoint  = null;
    this._path._dragMoved = false;

    if (this._mapDraggingWasEnabled) {
      if (moved) L.DomEvent.fakeStop({ type: 'click' });
      this._path._map.dragging.enable();
    }
  },

  /**
   * Applies transformation, does it in one sweep for performance,
   * so don't be surprised about the code repetition.
   *
   * [ x ]   [ a  b  tx ] [ x ]   [ a * x + b * y + tx ]
   * [ y ] = [ c  d  ty ] [ y ] = [ c * x + d * y + ty ]
   *
   * @param {Array.<Number>} matrix
   */
  _transformPoints: function(matrix, dest) {
    var path = this._path;
    var i, len, latlng;

    var px = L.point(matrix[4], matrix[5]);

    var crs = path._map.options.crs;
    var transformation = crs.transformation;
    var scale = crs.scale(path._map.getZoom());
    var projection = crs.projection;

    var diff = transformation.untransform(px, scale)
      .subtract(transformation.untransform(L.point(0, 0), scale));
    var applyTransform = !dest;

    path._bounds = new L.LatLngBounds();

    // console.time('transform');
    // all shifts are in-place
    if (path._point) { // L.Circle
      dest = projection.unproject(
        projection.project(path._latlng)._add(diff));
      if (applyTransform) {
        path._latlng = dest;
        path._point._add(px);
      }
    } else if (path._rings || path._parts) { // everything else
      var rings   = path._rings || path._parts;
      var latlngs = path._latlngs;
      dest = dest || latlngs;
      if (!L.Util.isArray(latlngs[0])) { // polyline
        latlngs = [latlngs];
        dest    = [dest];
      }
      for (i = 0, len = rings.length; i < len; i++) {
        dest[i] = dest[i] || [];
        for (var j = 0, jj = rings[i].length; j < jj; j++) {
          latlng     = latlngs[i][j];
          dest[i][j] = projection
            .unproject(projection.project(latlng)._add(diff));
          if (applyTransform) {
            path._bounds.extend(latlngs[i][j]);
            rings[i][j]._add(px);
          }
        }
      }
    }
    return dest;
    // console.timeEnd('transform');
  },

  /**
   * If you want to read the latlngs during the drag - your right,
   * but they have to be transformed
   */
  _replaceCoordGetters: function() {
    if (this._path.getLatLng) { // Circle, CircleMarker
      this._path.getLatLng_ = this._path.getLatLng;
      this._path.getLatLng = L.Util.bind(function() {
        return this.dragging._transformPoints(this.dragging._matrix, {});
      }, this._path);
    } else if (this._path.getLatLngs) {
      this._path.getLatLngs_ = this._path.getLatLngs;
      this._path.getLatLngs = L.Util.bind(function() {
        return this.dragging._transformPoints(this.dragging._matrix, []);
      }, this._path);
    }
  },

  /**
   * Put back the getters
   */
  _restoreCoordGetters: function() {
    if (this._path.getLatLng_) {
      this._path.getLatLng = this._path.getLatLng_;
      delete this._path.getLatLng_;
    } else if (this._path.getLatLngs_) {
      this._path.getLatLngs = this._path.getLatLngs_;
      delete this._path.getLatLngs_;
    }
  }

});

/**
 * @param  {L.Path} layer
 * @return {L.Path}
 */
L.Handler.PathDrag.makeDraggable = function(layer) {
  layer.dragging = new L.Handler.PathDrag(layer);
  return layer;
};

/**
 * Also expose as a method
 * @return {L.Path}
 */
L.Path.prototype.makeDraggable = function() {
  return L.Handler.PathDrag.makeDraggable(this);
};

L.Path.addInitHook(function() {
  if (this.options.draggable) {
    // ensure interactive
    this.options.interactive = true;

    if (this.dragging) {
      this.dragging.enable();
    } else {
      L.Handler.PathDrag.makeDraggable(this);
      this.dragging.enable();
    }
  } else if (this.dragging) {
    this.dragging.disable();
  }
});