text:
package org.orekit.propagation.conversion;

import java.util.ArrayList;
import java.util.List;

import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.util.FastMath;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.attitudes.InertialProvider;
import org.orekit.errors.OrekitIllegalArgumentException;
import org.orekit.forces.gravity.NewtonianAttraction;
import org.orekit.frames.Frame;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.integration.AdditionalDerivativesProvider;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.ParameterDriver;
import org.orekit.utils.ParameterDriversList;
import org.orekit.utils.ParameterDriversList.DelegatingDriver;
import org.orekit.utils.ParameterObserver;

/** Base class for propagator builders.
 * @author Pascal Parraud
 * @since 7.1
 */
public abstract class AbstractPropagatorBuilder implements PropagatorBuilder {

    /** Central attraction scaling factor.
     *

     * We use a power of 2 to avoid numeric noise introduction
     * in the multiplications/divisions sequences.
     *

     */
    private static final double MU_SCALE = FastMath.scalb(1.0, 32);

    /** Date of the initial orbit. */
    private AbsoluteDate initialOrbitDate;

    /** Frame in which the orbit is propagated. */
    private final Frame frame;

    /** Central attraction coefficient (m³/s²). */
    private double mu;

    /** Drivers for orbital parameters. */
    private final ParameterDriversList orbitalDrivers;

    /** List of the supported parameters. */
    private ParameterDriversList propagationDrivers;

    /** Orbit type to use. */
    private final OrbitType orbitType;

    /** Position angle type to use. */
    private final PositionAngle positionAngle;

    /** Position scale to use for the orbital drivers. */
    private final double positionScale;

    /** Attitude provider for the propagator. */
    private AttitudeProvider attitudeProvider;

    /** Additional equations. */
    @Deprecated
    private List<org.orekit.propagation.integration.AdditionalEquations> additionalEquations;

    /** Additional derivatives providers.
     * @since 11.1
     */
    private List<AdditionalDerivativesProvider> additionalDerivativesProviders;

    /** Build a new instance.
     *

     * The template orbit is used as a model to {@link
     * #createInitialOrbit() create initial orbit}. It defines the
     * inertial frame, the central attraction coefficient, the orbit type, and is also
     * used together with the {@code positionScale} to convert from the {@link
     * ParameterDriver#setNormalizedValue(double) normalized} parameters used by the
     * callers of this builder to the real orbital parameters. The initial attitude
     * provider is aligned with the inertial frame.
     *

     *

     * By default, all the {@link #getOrbitalParametersDrivers() orbital parameters drivers}
     * are selected, which means that if the builder is used for orbit determination or
     * propagator conversion, all orbital parameters will be estimated. If only a subset
     * of the orbital parameters must be estimated, caller must retrieve the orbital
     * parameters by calling {@link #getOrbitalParametersDrivers()} and then call
     * {@link ParameterDriver#setSelected(boolean) setSelected(false)}.
     *

     * @param templateOrbit reference orbit from which real orbits will be built
     * @param positionAngle position angle type to use
     * @param positionScale scaling factor used for orbital parameters normalization
     * (typically set to the expected standard deviation of the position)
     * @param addDriverForCentralAttraction if true, a {@link ParameterDriver} should
     * be set up for central attraction coefficient
     * @since 8.0
     * @see #AbstractPropagatorBuilder(Orbit, PositionAngle, double, boolean,
     * AttitudeProvider)
     */
    protected AbstractPropagatorBuilder(final Orbit templateOrbit, final PositionAngle positionAngle,
                                        final double positionScale, final boolean addDriverForCentralAttraction) {
        this(templateOrbit, positionAngle, positionScale, addDriverForCentralAttraction,
             new InertialProvider(templateOrbit.getFrame()));
    }

    /** Build a new instance.
     *

     * The template orbit is used as a model to {@link
     * #createInitialOrbit() create initial orbit}. It defines the
     * inertial frame, the central attraction coefficient, the orbit type, and is also
     * used together with the {@code positionScale} to convert from the {@link
     * ParameterDriver#setNormalizedValue(double) normalized} parameters used by the
     * callers of this builder to the real orbital parameters.
     *

     *

     * By default, all the {@link #getOrbitalParametersDrivers() orbital parameters drivers}
     * are selected, which means that if the builder is used for orbit determination or
     * propagator conversion, all orbital parameters will be estimated. If only a subset
     * of the orbital parameters must be estimated, caller must retrieve the orbital
     * parameters by calling {@link #getOrbitalParametersDrivers()} and then call
     * {@link ParameterDriver#setSelected(boolean) setSelected(false)}.
     *

     * @param templateOrbit reference orbit from which real orbits will be built
     * @param positionAngle position angle type to use
     * @param positionScale scaling factor used for orbital parameters normalization
     * (typically set to the expected standard deviation of the position)
     * @param addDriverForCentralAttraction if true, a {@link ParameterDriver} should
     * be set up for central attraction coefficient
     * @param attitudeProvider for the propagator.
     * @since 10.1
     * @see #AbstractPropagatorBuilder(Orbit, PositionAngle, double, boolean)
     */
    protected AbstractPropagatorBuilder(final Orbit templateOrbit,
                                        final PositionAngle positionAngle,
                                        final double positionScale,
                                        final boolean addDriverForCentralAttraction,
                                        final AttitudeProvider attitudeProvider) {

        this.initialOrbitDate    = templateOrbit.getDate();
        this.frame               = templateOrbit.getFrame();
        this.mu                  = templateOrbit.getMu();
        this.propagationDrivers  = new ParameterDriversList();
        this.orbitType           = templateOrbit.getType();
        this.positionAngle       = positionAngle;
        this.positionScale       = positionScale;
        this.orbitalDrivers      = orbitType.getDrivers(positionScale, templateOrbit, positionAngle);
        this.attitudeProvider = attitudeProvider;
        for (final DelegatingDriver driver : orbitalDrivers.getDrivers()) {
            driver.setSelected(true);
        }

        this.additionalEquations             = new ArrayList<>();
        this.additionalDerivativesProviders  = new ArrayList<>();

        if (addDriverForCentralAttraction) {
            final ParameterDriver muDriver = new ParameterDriver(NewtonianAttraction.CENTRAL_ATTRACTION_COEFFICIENT,
                                                                 mu, MU_SCALE, 0, Double.POSITIVE_INFINITY);
            muDriver.addObserver(new ParameterObserver() {
                /** {@inheridDoc} */
                @Override
                public void valueChanged(final double previousValue, final ParameterDriver driver) {
                    AbstractPropagatorBuilder.this.mu = driver.getValue();
                }
            });
            propagationDrivers.add(muDriver);
        }

    }

    /** {@inheritDoc} */
    public OrbitType getOrbitType() {
        return orbitType;
    }

    /** {@inheritDoc} */
    public PositionAngle getPositionAngle() {
        return positionAngle;
    }

    /** {@inheritDoc} */
    public AbsoluteDate getInitialOrbitDate() {
        return initialOrbitDate;
    }

    /** {@inheritDoc} */
    public Frame getFrame() {
        return frame;
    }

    /** {@inheritDoc} */
    public ParameterDriversList getOrbitalParametersDrivers() {
        return orbitalDrivers;
    }

    /** {@inheritDoc} */
    public ParameterDriversList getPropagationParametersDrivers() {
        return propagationDrivers;
    }

    /**
     * Get the attitude provider.
     *
     * @return the attitude provider
     * @since 10.1
     */
    public AttitudeProvider getAttitudeProvider() {
        return attitudeProvider;
    }

    /**
     * Set the attitude provider.
     *
     * @param attitudeProvider attitude provider
     * @since 10.1
     */
    public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
        this.attitudeProvider = attitudeProvider;
    }

    /** Get the position scale.
     * @return the position scale used to scale the orbital drivers
     */
    public double getPositionScale() {
        return positionScale;
    }

    /** Get the central attraction coefficient (µ - m³/s²) value.
     * @return the central attraction coefficient (µ - m³/s²) value
     * @since 9.2
     */
    public double getMu() {
        return mu;
    }

    /** Get the number of selected parameters.
     * @return number of selected parameters
     */
    private int getNbSelected() {

        int count = 0;

        // count orbital parameters
        for (final ParameterDriver driver : orbitalDrivers.getDrivers()) {
            if (driver.isSelected()) {
                ++count;
            }
        }

        // count propagation parameters
        for (final ParameterDriver driver : propagationDrivers.getDrivers()) {
            if (driver.isSelected()) {
                ++count;
            }
        }

        return count;

    }

    /** {@inheritDoc} */
    public double[] getSelectedNormalizedParameters() {

        // allocate array
        final double[] selected = new double[getNbSelected()];

        // fill data
        int index = 0;
        for (final ParameterDriver driver : orbitalDrivers.getDrivers()) {
            if (driver.isSelected()) {
                selected[index++] = driver.getNormalizedValue();
            }
        }
        for (final ParameterDriver driver : propagationDrivers.getDrivers()) {
            if (driver.isSelected()) {
                selected[index++] = driver.getNormalizedValue();
            }
        }

        return selected;

    }

    /** Build an initial orbit using the current selected parameters.
     *

     * This method is a stripped down version of {@link #buildPropagator(double[])}
     * that only builds the initial orbit and not the full propagator.
     *

     * @return an initial orbit
     * @since 8.0
     */
    protected Orbit createInitialOrbit() {
        final double[] unNormalized = new double[orbitalDrivers.getNbParams()];
        for (int i = 0; i < unNormalized.length; ++i) {
            unNormalized[i] = orbitalDrivers.getDrivers().get(i).getValue();
        }
        return getOrbitType().mapArrayToOrbit(unNormalized, null, positionAngle, initialOrbitDate, mu, frame);
    }

    /** Set the selected parameters.
     * @param normalizedParameters normalized values for the selected parameters
     */
    protected void setParameters(final double[] normalizedParameters) {

        if (normalizedParameters.length != getNbSelected()) {
            throw new OrekitIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
                                                     normalizedParameters.length,
                                                     getNbSelected());
        }

        int index = 0;

        // manage orbital parameters
        for (final ParameterDriver driver : orbitalDrivers.getDrivers()) {
            if (driver.isSelected()) {
                driver.setNormalizedValue(normalizedParameters[index++]);
            }
        }

        // manage propagation parameters
        for (final ParameterDriver driver : propagationDrivers.getDrivers()) {
            if (driver.isSelected()) {
                driver.setNormalizedValue(normalizedParameters[index++]);
            }
        }

    }

    /** Add a supported parameter.
     * @param driver driver for the parameter
     */
    protected void addSupportedParameter(final ParameterDriver driver) {
        propagationDrivers.add(driver);
        propagationDrivers.sort();
    }

    /** Reset the orbit in the propagator builder.
     * @param newOrbit New orbit to set in the propagator builder
     */
    public void resetOrbit(final Orbit newOrbit) {

        // Map the new orbit in an array of double
        final double[] orbitArray = new double[6];
        orbitType.mapOrbitToArray(newOrbit, getPositionAngle(), orbitArray, null);

        // Update all the orbital drivers, selected or unselected
        // Reset values and reference values
        final List<DelegatingDriver> orbitalDriversList = getOrbitalParametersDrivers().getDrivers();
        int i = 0;
        for (DelegatingDriver driver : orbitalDriversList) {
            driver.setReferenceValue(orbitArray[i]);
            driver.setValue(orbitArray[i++]);
        }

        // Change the initial orbit date in the builder
        this.initialOrbitDate = newOrbit.getDate();
    }

    /** Add a set of user-specified equations to be integrated along with the orbit propagation (author Shiva Iyer).
     * @param additional additional equations
     * @since 10.1
     * @deprecated as of 11.1, replaced by {@link #addAdditionalDerivativesProvider(AdditionalDerivativesProvider)}
     */
    @Deprecated
    public void addAdditionalEquations(final org.orekit.propagation.integration.AdditionalEquations additional) {
        additionalEquations.add(additional);
    }

    /** Get the list of additional equations.
     * @return the list of additional equations
     * @since 10.1
     * @deprecated as of 11.1, replaced by {@link #addAdditionalDerivativesProvider(AdditionalDerivativesProvider)}
     */
    @Deprecated
    protected List<org.orekit.propagation.integration.AdditionalEquations> getAdditionalEquations() {
        return additionalEquations;
    }

    /** Add a set of user-specified equations to be integrated along with the orbit propagation (author Shiva Iyer).
     * @param provider provider for additional derivatives
     * @since 11.1
     */
    public void addAdditionalDerivativesProvider(final AdditionalDerivativesProvider provider) {
        additionalDerivativesProviders.add(provider);
    }

    /** Get the list of additional equations.
     * @return the list of additional equations
     * @since 11.1
     */
    protected List<AdditionalDerivativesProvider> getAdditionalDerivativesProviders() {
        return additionalDerivativesProviders;
    }

    /** Deselects orbital and propagation drivers. */
    public void deselectDynamicParameters() {
        for (ParameterDriver driver : getPropagationParametersDrivers().getDrivers()) {
            driver.setSelected(false);
        }
        for (ParameterDriver driver : getOrbitalParametersDrivers().getDrivers()) {
            driver.setSelected(false);
        }
    }

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactIconBase = require('react-icon-base');

var _reactIconBase2 = _interopRequireDefault(_reactIconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var IoAndroidWarning = function IoAndroidWarning(props) {
    return _react2.default.createElement(
        _reactIconBase2.default,
        _extends({ viewBox: '0 0 40 40' }, props),
        _react2.default.createElement(
            'g',
            null,
            _react2.default.createElement('path', { d: 'm0 36.3l17.5-32.5 17.5 32.5h-35z m19.4-5v-3.8h-3.8v3.8h3.8z m0-6.3v-7.5h-3.8v7.5h3.8z' })
        )
    );
};

exports.default = IoAndroidWarning;
module.exports = exports['default'];

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\models\forms;

use Yii;
use yii\base\Model;

class RequirementCommentForm extends Model
{
    public $comment;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['comment'], 'required'],
        ];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'comment' => Yii::t('app', 'Comment'),
        ];
    }
}


text:
<?php
/**
 * TOP API: taobao.hanoi.template.add request
 *
 * @author auto create
 * @since 1.0, 2013-12-10 16:57:25
 */
class HanoiTemplateAddRequest
{
	/**
	 * 认证信息
	 **/
	private $appName;

	/**
	 * 所使用的数据模板
	 **/
	private $dataTemplateId;

	/**
	 * 模板的描述
	 **/
	private $description;

	/**
	 * 模板的表达式
	 **/
	private $expression;

	/**
	 * 模板的名称
	 **/
	private $name;

	/**
	 * 模板的开放策略,默认false不开放
	 **/
	private $open;

	/**
	 * 设置表达式中参数的类型。ParaVO对象的json格式
	 **/
	private $paraList;

	/**
	 * 模板的源模板id,用于模板分配,不填或者为0时,则视为创建新模板
	 **/
	private $sourceTemplateId;

	/**
	 * 模板的编码
	 **/
	private $templateCode;

	private $apiParas = array();

	public function setAppName($appName)
	{
		$this->appName = $appName;
		$this->apiParas["app_name"] = $appName;
	}

	public function getAppName()
	{
		return $this->appName;
	}

	public function setDataTemplateId($dataTemplateId)
	{
		$this->dataTemplateId = $dataTemplateId;
		$this->apiParas["data_template_id"] = $dataTemplateId;
	}

	public function getDataTemplateId()
	{
		return $this->dataTemplateId;
	}

	public function setDescription($description)
	{
		$this->description = $description;
		$this->apiParas["description"] = $description;
	}

	public function getDescription()
	{
		return $this->description;
	}

	public function setExpression($expression)
	{
		$this->expression = $expression;
		$this->apiParas["expression"] = $expression;
	}

	public function getExpression()
	{
		return $this->expression;
	}

	public function setName($name)
	{
		$this->name = $name;
		$this->apiParas["name"] = $name;
	}

	public function getName()
	{
		return $this->name;
	}

	public function setOpen($open)
	{
		$this->open = $open;
		$this->apiParas["open"] = $open;
	}

	public function getOpen()
	{
		return $this->open;
	}

	public function setParaList($paraList)
	{
		$this->paraList = $paraList;
		$this->apiParas["para_list"] = $paraList;
	}

	public function getParaList()
	{
		return $this->paraList;
	}

	public function setSourceTemplateId($sourceTemplateId)
	{
		$this->sourceTemplateId = $sourceTemplateId;
		$this->apiParas["source_template_id"] = $sourceTemplateId;
	}

	public function getSourceTemplateId()
	{
		return $this->sourceTemplateId;
	}

	public function setTemplateCode($templateCode)
	{
		$this->templateCode = $templateCode;
		$this->apiParas["template_code"] = $templateCode;
	}

	public function getTemplateCode()
	{
		return $this->templateCode;
	}

	public function getApiMethodName()
	{
		return "taobao.hanoi.template.add";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->appName,"appName");
		RequestCheckUtil::checkNotNull($this->dataTemplateId,"dataTemplateId");
		RequestCheckUtil::checkNotNull($this->expression,"expression");
		RequestCheckUtil::checkNotNull($this->name,"name");
		RequestCheckUtil::checkNotNull($this->templateCode,"templateCode");
		RequestCheckUtil::checkMaxLength($this->templateCode,50,"templateCode");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
package dev.minco.javatransformer.internal.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import javax.annotation.Nonnull;

import lombok.RequiredArgsConstructor;
import lombok.val;

public final class CollectionUtil {
	@SafeVarargs
	@SuppressWarnings("varargs")
	public static <T> Stream<T> union(Collection<T>... collections) {
		return union(Arrays.asList(collections));
	}

	@SafeVarargs
	@SuppressWarnings({"varargs", "unchecked"})
	public static <T> Iterator<T> union(Iterable<T>... iterables) {
		Iterator<T>[] iterators = (Iterator<T>[]) new Iterator<?>[iterables.length];
		for (int i = 0; i < iterators.length; i++) {
			iterators[i] = iterables[i].iterator();
		}
		return new IteratorIterator<>(iterators);
	}

	public static <T> Stream<T> union(Collection<Collection<T>> collections) {
		return collections.stream().flatMap(x -> x == null ? Stream.empty() : x.stream());
	}

	public static <T> Stream<T> stream(Supplier<T> supplier) {
		return stream(iterable(supplier));
	}

	public static <T> Stream<T> stream(Iterable<T> iterable) {
		if (iterable instanceof Collection)
			return ((Collection<T>) iterable).stream();

		return StreamSupport.stream(iterable.spliterator(), false);
	}

	public static <T> Iterable<T> iterable(Stream<T> supplier) {
		return supplier::iterator;
	}

	public static <T> Iterable<T> iterable(Supplier<T> supplier) {
		return () -> new IteratorFromSupplier<>(supplier);
	}

	public static <T> boolean equals(Collection<T> a, Collection<T> b, Comparer<T> c) {
		if (a.size() != b.size())
			return false;
		val bIterator = b.iterator();
		for (val aa : a) {
			val bb = bIterator.next();
			if (!c.compare(aa, bb))
				return false;
		}
		return true;
	}

	@FunctionalInterface
	public interface Comparer<T> {
		boolean compare(T a, T b);
	}

	private static class IteratorFromSupplier<T> implements Iterator<T> {
		private final Supplier<T> supplier;
		private T next;

		public IteratorFromSupplier(Supplier<T> supplier) {
			this.supplier = supplier;
			next = supplier.get();
		}

		@Override
		public boolean hasNext() {
			return next != null;
		}

		@Override
		public T next() {
			if (next == null)
				throw new NoSuchElementException();

			try {
				return next;
			} finally {
				next = supplier.get();
			}
		}
	}

	@RequiredArgsConstructor
	private static class IteratorIterator<T> implements Iterator<T> {
		@Nonnull
		private final Iterator<T>[] iterators;
		private int current;

		@Override
		public boolean hasNext() {
			while (current < iterators.length && !iterators[current].hasNext())
				current++;

			return current < iterators.length;
		}

		@Override
		public T next() {
			if (!hasNext())
				throw new NoSuchElementException();

			return iterators[current].next();
		}
	}
}


text:
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class SaharaImageRegistry(resource.Resource):
    """A resource for registering an image in sahara.

    Allows to register an image in the sahara image registry and add tags.
    """

    support_status = support.SupportStatus(version='6.0.0')

    PROPERTIES = (
        IMAGE, USERNAME, DESCRIPTION, TAGS

    ) = (
        'image', 'username', 'description', 'tags'
    )

    properties_schema = {
        IMAGE: properties.Schema(
            properties.Schema.STRING,
            _("ID or name of the image to register."),
            constraints=[
                constraints.CustomConstraint('glance.image')
            ],
            required=True
        ),
        USERNAME: properties.Schema(
            properties.Schema.STRING,
            _('Username of privileged user in the image.'),
            required=True,
            update_allowed=True
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description of the image.'),
            default='',
            update_allowed=True
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            _('Tags to add to the image.'),
            schema=properties.Schema(
                properties.Schema.STRING
            ),
            update_allowed=True,
            default=[]
        )
    }

    default_client_name = 'sahara'

    entity = 'images'

    def handle_create(self):
        self.resource_id_set(self.client_plugin(
            'glance').find_image_by_name_or_id(
            self.properties[self.IMAGE]))

        self.client().images.update_image(
            self.resource_id,
            self.properties[self.USERNAME],
            self.properties[self.DESCRIPTION]
        )
        if self.properties[self.TAGS]:
            self.client().images.update_tags(self.resource_id,
                                             self.properties[self.TAGS])

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.properties = json_snippet.properties(
                self.properties_schema,
                self.context)
            if self.USERNAME in prop_diff or self.DESCRIPTION in prop_diff:
                self.client().images.update_image(
                    self.resource_id,
                    self.properties[self.USERNAME],
                    self.properties[self.DESCRIPTION]
                )
            if self.TAGS in prop_diff:
                self.client().images.update_tags(self.resource_id,
                                                 self.properties[self.TAGS])

    def handle_delete(self):
        if self.resource_id is None:
            return

        try:
            self.client().images.unregister_image(self.resource_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)

def resource_mapping():
    return {
        'OS::Sahara::ImageRegistry': SaharaImageRegistry
    }


text:
var mainApp = angular.module('mainApp', ['treeGrid']);

mainApp.controller('syncGridController', ['$scope', '$http', function ($scope, $http) {
    $scope.my_tree = {};
    $scope.tree_data = [];
    $scope.expanding_property = "Name";
    $scope.col_defs = [
        { field: "Value" },
        { field: "LastUpdatedAt" },
        { field: "DelayedBy" },
        { field: "Status" }
    ];

    $scope.$evalAsync(function () {
        $http.get('http://www.corsproxy.com/yourblob/sqldatasync/syncstatus')
            .success(function (data, status, headers, config) {
                $scope.tree_data = data;
            })
            .error(function (data, status, headers, config) {
                $scope.message = "Failed to retrieve data. " + status + " " + data + ". ";
                $('#msgModal').modal('show');
            });
    });
}]);


text:
namespace rx
{

RendererWGL::RendererWGL(std::unique_ptr<FunctionsGL> functionsGL,
                         const egl::AttributeMap &attribMap,
                         DisplayWGL *display,
                         HGLRC context,
                         HGLRC sharedContext,
                         const std::vector<int> workerContextAttribs)
    : RendererGL(std::move(functionsGL), attribMap, display),
      mDisplay(display),
      mContext(context),
      mSharedContext(sharedContext),
      mWorkerContextAttribs(workerContextAttribs)
{}

RendererWGL::~RendererWGL()
{
    if (mSharedContext != nullptr)
    {
        mDisplay->destroyNativeContext(mSharedContext);
    }
    mDisplay->destroyNativeContext(mContext);
    mContext = nullptr;
}

HGLRC RendererWGL::getContext() const
{
    return mContext;
}

WorkerContext *RendererWGL::createWorkerContext(std::string *infoLog)
{
    return mDisplay->createWorkerContext(infoLog, mSharedContext, mWorkerContextAttribs);
}

}  // namespace rx


text:
package openstack

import (
	"bytes"
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/terraform/helper/hashcode"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"

	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
)

func resourceNetworkingPortV2() *schema.Resource {
	return &schema.Resource{
		Create: resourceNetworkingPortV2Create,
		Read:   resourceNetworkingPortV2Read,
		Update: resourceNetworkingPortV2Update,
		Delete: resourceNetworkingPortV2Delete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Timeouts: &schema.ResourceTimeout{
			Create: schema.DefaultTimeout(10 * time.Minute),
			Delete: schema.DefaultTimeout(10 * time.Minute),
		},

		Schema: map[string]*schema.Schema{
			"region": &schema.Schema{
				Type:        schema.TypeString,
				Required:    true,
				ForceNew:    true,
				DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
			},
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: false,
			},
			"network_id": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"admin_state_up": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				ForceNew: false,
				Computed: true,
			},
			"mac_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
			"tenant_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
			"device_owner": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
			"security_group_ids": &schema.Schema{
				Type:     schema.TypeSet,
				Optional: true,
				ForceNew: false,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
			"device_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
			"fixed_ip": &schema.Schema{
				Type:     schema.TypeList,
				Optional: true,
				ForceNew: false,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"subnet_id": &schema.Schema{
							Type:     schema.TypeString,
							Required: true,
						},
						"ip_address": &schema.Schema{
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"allowed_address_pairs": &schema.Schema{
				Type:     schema.TypeSet,
				Optional: true,
				ForceNew: false,
				Computed: true,
				Set:      allowedAddressPairsHash,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"ip_address": &schema.Schema{
							Type:     schema.TypeString,
							Required: true,
						},
						"mac_address": &schema.Schema{
							Type:     schema.TypeString,
							Optional: true,
							Computed: true,
						},
					},
				},
			},
			"value_specs": &schema.Schema{
				Type:     schema.TypeMap,
				Optional: true,
				ForceNew: true,
			},
			"all_fixed_ips": &schema.Schema{
				Type:     schema.TypeList,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
		},
	}
}

func resourceNetworkingPortV2Create(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(GetRegion(d))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	createOpts := PortCreateOpts{
		ports.CreateOpts{
			Name:                d.Get("name").(string),
			AdminStateUp:        resourcePortAdminStateUpV2(d),
			NetworkID:           d.Get("network_id").(string),
			MACAddress:          d.Get("mac_address").(string),
			TenantID:            d.Get("tenant_id").(string),
			DeviceOwner:         d.Get("device_owner").(string),
			SecurityGroups:      resourcePortSecurityGroupsV2(d),
			DeviceID:            d.Get("device_id").(string),
			FixedIPs:            resourcePortFixedIpsV2(d),
			AllowedAddressPairs: resourceAllowedAddressPairsV2(d),
		},
		MapValueSpecs(d),
	}

	log.Printf("[DEBUG] Create Options: %#v", createOpts)
	p, err := ports.Create(networkingClient, createOpts).Extract()
	if err != nil {
		return fmt.Errorf("Error creating OpenStack Neutron network: %s", err)
	}
	log.Printf("[INFO] Network ID: %s", p.ID)

	log.Printf("[DEBUG] Waiting for OpenStack Neutron Port (%s) to become available.", p.ID)

	stateConf := &resource.StateChangeConf{
		Target:     []string{"ACTIVE"},
		Refresh:    waitForNetworkPortActive(networkingClient, p.ID),
		Timeout:    d.Timeout(schema.TimeoutCreate),
		Delay:      5 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()

	d.SetId(p.ID)

	return resourceNetworkingPortV2Read(d, meta)
}

func resourceNetworkingPortV2Read(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(GetRegion(d))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	p, err := ports.Get(networkingClient, d.Id()).Extract()
	if err != nil {
		return CheckDeleted(d, err, "port")
	}

	log.Printf("[DEBUG] Retrieved Port %s: %+v", d.Id(), p)

	d.Set("name", p.Name)
	d.Set("admin_state_up", p.AdminStateUp)
	d.Set("network_id", p.NetworkID)
	d.Set("mac_address", p.MACAddress)
	d.Set("tenant_id", p.TenantID)
	d.Set("device_owner", p.DeviceOwner)
	d.Set("security_group_ids", p.SecurityGroups)
	d.Set("device_id", p.DeviceID)

	// Create a slice of all returned Fixed IPs.
	// This will be in the order returned by the API,
	// which is usually alpha-numeric.
	var ips []string
	for _, ipObject := range p.FixedIPs {
		ips = append(ips, ipObject.IPAddress)
	}
	d.Set("all_fixed_ips", ips)

	// Convert AllowedAddressPairs to list of map
	var pairs []map[string]interface{}
	for _, pairObject := range p.AllowedAddressPairs {
		pair := make(map[string]interface{})
		pair["ip_address"] = pairObject.IPAddress
		pair["mac_address"] = pairObject.MACAddress
		pairs = append(pairs, pair)
	}
	d.Set("allowed_address_pairs", pairs)

	d.Set("region", GetRegion(d))

	return nil
}

func resourceNetworkingPortV2Update(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(GetRegion(d))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	var updateOpts ports.UpdateOpts

	if d.HasChange("name") {
		updateOpts.Name = d.Get("name").(string)
	}

	if d.HasChange("admin_state_up") {
		updateOpts.AdminStateUp = resourcePortAdminStateUpV2(d)
	}

	if d.HasChange("device_owner") {
		updateOpts.DeviceOwner = d.Get("device_owner").(string)
	}

	if d.HasChange("security_group_ids") {
		updateOpts.SecurityGroups = resourcePortSecurityGroupsV2(d)
	}

	if d.HasChange("device_id") {
		updateOpts.DeviceID = d.Get("device_id").(string)
	}

	if d.HasChange("fixed_ip") {
		updateOpts.FixedIPs = resourcePortFixedIpsV2(d)
	}

	if d.HasChange("allowed_address_pairs") {
		updateOpts.AllowedAddressPairs = resourceAllowedAddressPairsV2(d)
	}

	log.Printf("[DEBUG] Updating Port %s with options: %+v", d.Id(), updateOpts)

	_, err = ports.Update(networkingClient, d.Id(), updateOpts).Extract()
	if err != nil {
		return fmt.Errorf("Error updating OpenStack Neutron Network: %s", err)
	}

	return resourceNetworkingPortV2Read(d, meta)
}

func resourceNetworkingPortV2Delete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(GetRegion(d))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"ACTIVE"},
		Target:     []string{"DELETED"},
		Refresh:    waitForNetworkPortDelete(networkingClient, d.Id()),
		Timeout:    d.Timeout(schema.TimeoutDelete),
		Delay:      5 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf("Error deleting OpenStack Neutron Network: %s", err)
	}

	d.SetId("")
	return nil
}

func resourcePortSecurityGroupsV2(d *schema.ResourceData) []string {
	rawSecurityGroups := d.Get("security_group_ids").(*schema.Set)
	groups := make([]string, rawSecurityGroups.Len())
	for i, raw := range rawSecurityGroups.List() {
		groups[i] = raw.(string)
	}
	return groups
}

func resourcePortFixedIpsV2(d *schema.ResourceData) interface{} {
	rawIP := d.Get("fixed_ip").([]interface{})

	if len(rawIP) == 0 {
		return nil
	}

	ip := make([]ports.IP, len(rawIP))
	for i, raw := range rawIP {
		rawMap := raw.(map[string]interface{})
		ip[i] = ports.IP{
			SubnetID:  rawMap["subnet_id"].(string),
			IPAddress: rawMap["ip_address"].(string),
		}
	}
	return ip
}

func resourceAllowedAddressPairsV2(d *schema.ResourceData) []ports.AddressPair {
	// ports.AddressPair
	rawPairs := d.Get("allowed_address_pairs").(*schema.Set).List()

	if len(rawPairs) == 0 {
		return nil
	}

	pairs := make([]ports.AddressPair, len(rawPairs))
	for i, raw := range rawPairs {
		rawMap := raw.(map[string]interface{})
		pairs[i] = ports.AddressPair{
			IPAddress:  rawMap["ip_address"].(string),
			MACAddress: rawMap["mac_address"].(string),
		}
	}
	return pairs
}

func resourcePortAdminStateUpV2(d *schema.ResourceData) *bool {
	value := false

	if raw, ok := d.GetOk("admin_state_up"); ok && raw == true {
		value = true
	}

	return &value
}

func allowedAddressPairsHash(v interface{}) int {
	var buf bytes.Buffer
	m := v.(map[string]interface{})
	buf.WriteString(fmt.Sprintf("%s", m["ip_address"].(string)))

	return hashcode.String(buf.String())
}

func waitForNetworkPortActive(networkingClient *gophercloud.ServiceClient, portId string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		p, err := ports.Get(networkingClient, portId).Extract()
		if err != nil {
			return nil, "", err
		}

		log.Printf("[DEBUG] OpenStack Neutron Port: %+v", p)
		if p.Status == "DOWN" || p.Status == "ACTIVE" {
			return p, "ACTIVE", nil
		}

		return p, p.Status, nil
	}
}

func waitForNetworkPortDelete(networkingClient *gophercloud.ServiceClient, portId string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		log.Printf("[DEBUG] Attempting to delete OpenStack Neutron Port %s", portId)

		p, err := ports.Get(networkingClient, portId).Extract()
		if err != nil {
			if _, ok := err.(gophercloud.ErrDefault404); ok {
				log.Printf("[DEBUG] Successfully deleted OpenStack Port %s", portId)
				return p, "DELETED", nil
			}
			return p, "ACTIVE", err
		}

		err = ports.Delete(networkingClient, portId).ExtractErr()
		if err != nil {
			if _, ok := err.(gophercloud.ErrDefault404); ok {
				log.Printf("[DEBUG] Successfully deleted OpenStack Port %s", portId)
				return p, "DELETED", nil
			}
			return p, "ACTIVE", err
		}

		log.Printf("[DEBUG] OpenStack Port %s still active.\n", portId)
		return p, "ACTIVE", nil
	}
}


text:
import os
import re
import subprocess
import sys
import requests
import getpass

from six.moves import input
import six

try:
    import jira.client
    JIRA_IMPORTED = True
except ImportError:
    JIRA_IMPORTED = False

# Location of your Arrow git clone
SEP = os.path.sep
ARROW_HOME = os.path.abspath(__file__).rsplit(SEP, 2)[0]
PROJECT_NAME = ARROW_HOME.rsplit(SEP, 1)[1]
print("ARROW_HOME = " + ARROW_HOME)
print("PROJECT_NAME = " + PROJECT_NAME)

# Remote name which points to the Gihub site
PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github")
# Remote name which points to Apache git
PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache")
# ASF JIRA username
JIRA_USERNAME = os.environ.get("JIRA_USERNAME")
# ASF JIRA password
JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD")

GITHUB_BASE = "https://github.com/apache/" + PROJECT_NAME + "/pull"
GITHUB_API_BASE = "https://api.github.com/repos/apache/" + PROJECT_NAME
JIRA_BASE = "https://issues.apache.org/jira/browse"
JIRA_API_BASE = "https://issues.apache.org/jira"
# Prefix added to temporary branches
BRANCH_PREFIX = "PR_TOOL"

os.chdir(ARROW_HOME)

def get_json(url):
    req = requests.get(url)
    return req.json()

def fail(msg):
    print(msg)
    clean_up()
    sys.exit(-1)

def run_cmd(cmd):
    if isinstance(cmd, six.string_types):
        cmd = cmd.split(' ')

    try:
        output = subprocess.check_output(cmd)
    except subprocess.CalledProcessError as e:
        # this avoids hiding the stdout / stderr of failed processes
        print('Command failed: %s' % cmd)
        print('With output:')
        print('--------------')
        print(e.output)
        print('--------------')
        raise e

    if isinstance(output, six.binary_type):
        output = output.decode('utf-8')
    return output

def continue_maybe(prompt):
    result = input("\n%s (y/n): " % prompt)
    if result.lower() != "y":
        fail("Okay, exiting")

original_head = run_cmd("git rev-parse HEAD")[:8]

def clean_up():
    print("Restoring head pointer to %s" % original_head)
    run_cmd("git checkout %s" % original_head)

    branches = run_cmd("git branch").replace(" ", "").split("\n")

    for branch in [x for x in branches if x.startswith(BRANCH_PREFIX)]:
        print("Deleting local branch %s" % branch)
        run_cmd("git branch -D %s" % branch)

# merge the requested PR and return the merge hash
def merge_pr(pr_num, target_ref):
    pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, pr_num)
    target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, pr_num,
                                                target_ref.upper())
    run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num,
                                              pr_branch_name))
    run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref,
                                    target_branch_name))
    run_cmd("git checkout %s" % target_branch_name)

    had_conflicts = False
    try:
        run_cmd(['git', 'merge', pr_branch_name, '--squash'])
    except Exception as e:
        msg = ("Error merging: %s\nWould you like to "
               "manually fix-up this merge?" % e)
        continue_maybe(msg)
        msg = ("Okay, please fix any conflicts and 'git add' "
               "conflicting files... Finished?")
        continue_maybe(msg)
        had_conflicts = True

    commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
                             '--pretty=format:%an <%ae>']).split("\n")
    distinct_authors = sorted(set(commit_authors),
                              key=lambda x: commit_authors.count(x),
                              reverse=True)
    primary_author = distinct_authors[0]
    commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
                      '--pretty=format:%h <%an> %s']).split("\n\n")

    merge_message_flags = []

    merge_message_flags += ["-m", title]
    if body is not None:
        merge_message_flags += ["-m", body]

    authors = "\n".join(["Author: %s" % a for a in distinct_authors])

    merge_message_flags += ["-m", authors]

    if had_conflicts:
        committer_name = run_cmd("git config --get user.name").strip()
        committer_email = run_cmd("git config --get user.email").strip()
        message = ("This patch had conflicts when merged, "
                   "resolved by\nCommitter: %s <%s>" %
                   (committer_name, committer_email))
        merge_message_flags += ["-m", message]

    # The string "Closes #%s" string is required for GitHub to correctly close
    # the PR
    merge_message_flags += [
        "-m",
        "Closes #%s from %s and squashes the following commits:"
        % (pr_num, pr_repo_desc)]
    for c in commits:
        stripped_message = strip_ci_directives(c).strip()
        merge_message_flags += ["-m", stripped_message]

    run_cmd(['git', 'commit',
             '--no-verify',  # do not run commit hooks
             '--author="%s"' % primary_author] +
            merge_message_flags)

    continue_maybe("Merge complete (local ref %s). Push to %s?" % (
        target_branch_name, PUSH_REMOTE_NAME))

    try:
        run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name,
                                       target_ref))
    except Exception as e:
        clean_up()
        fail("Exception while pushing: %s" % e)

    merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8]
    clean_up()
    print("Pull request #%s merged!" % pr_num)
    print("Merge hash: %s" % merge_hash)
    return merge_hash

_REGEX_CI_DIRECTIVE = re.compile('\[[^\]]*\]')

def strip_ci_directives(commit_message):
    # Remove things like '[force ci]', '[skip appveyor]' from the assembled
    # commit message
    return _REGEX_CI_DIRECTIVE.sub('', commit_message)

def fix_version_from_branch(branch, versions):
    # Note: Assumes this is a sorted (newest->oldest) list of un-released
    # versions
    if branch == "master":
        return versions[0]
    else:
        branch_ver = branch.replace("branch-", "")
        return [x for x in versions if x.name.startswith(branch_ver)][-1]

def extract_jira_id(title):
    m = re.search(r'^(ARROW-[0-9]+)\b.*$', title)
    if m:
        return m.group(1)
    else:
        fail("PR title should be prefixed by a jira id "
             "\"ARROW-XXX: ...\", found: \"%s\"" % title)

def check_jira(title):
    jira_id = extract_jira_id(title)
    asf_jira = jira.client.JIRA({'server': JIRA_API_BASE},
                                basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
    try:
        asf_jira.issue(jira_id)
    except Exception as e:
        fail("ASF JIRA could not find %s\n%s" % (jira_id, e))

def resolve_jira(title, merge_branches, comment):
    asf_jira = jira.client.JIRA({'server': JIRA_API_BASE},
                                basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))

    default_jira_id = extract_jira_id(title)

    jira_id = input("Enter a JIRA id [%s]: " % default_jira_id)
    if jira_id == "":
        jira_id = default_jira_id

    try:
        issue = asf_jira.issue(jira_id)
    except Exception as e:
        fail("ASF JIRA could not find %s\n%s" % (jira_id, e))

    cur_status = issue.fields.status.name
    cur_summary = issue.fields.summary
    cur_assignee = issue.fields.assignee
    if cur_assignee is None:
        cur_assignee = "NOT ASSIGNED!!!"
    else:
        cur_assignee = cur_assignee.displayName

    if cur_status == "Resolved" or cur_status == "Closed":
        fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status))
    print("=== JIRA %s ===" % jira_id)
    print("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n"
          % (cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id))

    jira_fix_versions = _get_fix_version(asf_jira, merge_branches)

    resolve = [x for x in asf_jira.transitions(jira_id)
               if x['name'] == "Resolve Issue"][0]
    asf_jira.transition_issue(jira_id, resolve["id"], comment=comment,
                              fixVersions=jira_fix_versions)

    print("Successfully resolved %s!" % (jira_id))

def _get_fix_version(asf_jira, merge_branches):
    versions = asf_jira.project_versions("ARROW")
    versions = sorted(versions, key=lambda x: x.name, reverse=True)
    versions = [x for x in versions if not x.raw['released']]

    default_fix_versions = [fix_version_from_branch(x, versions).name
                            for x in merge_branches]
    for v in default_fix_versions:
        # Handles the case where we have forked a release branch but not yet
        # made the release.  In this case, if the PR is committed to the master
        # branch and the release branch, we only consider the release branch to
        # be the fix version. E.g. it is not valid to have both 1.1.0 and 1.0.0
        # as fix versions.
        (major, minor, patch) = v.split(".")
        if patch == "0":
            previous = "%s.%s.%s" % (major, int(minor) - 1, 0)
            if previous in default_fix_versions:
                default_fix_versions = [x for x in default_fix_versions
                                        if x != v]
    default_fix_versions = ",".join(default_fix_versions)

    fix_versions = input("Enter comma-separated fix version(s) [%s]: "
                         % default_fix_versions)
    if fix_versions == "":
        fix_versions = default_fix_versions
    fix_versions = fix_versions.replace(" ", "").split(",")

    def get_version_json(version_str):
        return [x for x in versions if x.name == version_str][0].raw

    return [get_version_json(v) for v in fix_versions]

if not JIRA_USERNAME:
    JIRA_USERNAME = input("Env JIRA_USERNAME not set, "
                          "please enter your JIRA username:")

if not JIRA_PASSWORD:
    JIRA_PASSWORD = getpass.getpass("Env JIRA_PASSWORD not set, please enter "
                                    "your JIRA password:")

branches = get_json("%s/branches" % GITHUB_API_BASE)
branch_names = [x['name'] for x in branches if x['name'].startswith('branch-')]

# Assumes branch names can be sorted lexicographically
# Julien: I commented this out as we don't have any "branch-*" branch yet
# latest_branch = sorted(branch_names, reverse=True)[0]

pr_num = input("Which pull request would you like to merge? (e.g. 34): ")
pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))

url = pr["url"]
title = pr["title"]
check_jira(title)
body = pr["body"]
target_ref = pr["base"]["ref"]
user_login = pr["user"]["login"]
base_ref = pr["head"]["ref"]
pr_repo_desc = "%s/%s" % (user_login, base_ref)

if pr["merged"] is True:
    print("Pull request %s has already been merged, "
          "assuming you want to backport" % pr_num)
    merge_commit_desc = run_cmd([
        'git', 'log', '--merges', '--first-parent',
        '--grep=pull request #%s' % pr_num, '--oneline']).split("\n")[0]
    if merge_commit_desc == "":
        fail("Couldn't find any merge commit for #%s, "
             "you may need to update HEAD." % pr_num)

    merge_hash = merge_commit_desc[:7]
    message = merge_commit_desc[8:]

    print("Found: %s" % message)
    sys.exit(0)

if not bool(pr["mergeable"]):
    msg = ("Pull request %s is not mergeable in its current form.\n"
           % pr_num + "Continue? (experts only!)")
    continue_maybe(msg)

print("\n=== Pull Request #%s ===" % pr_num)
print("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s"
      % (title, pr_repo_desc, target_ref, url))
continue_maybe("Proceed with merging pull request #%s?" % pr_num)

merged_refs = [target_ref]

merge_hash = merge_pr(pr_num, target_ref)

if JIRA_IMPORTED:
    continue_maybe("Would you like to update the associated JIRA?")
    jira_comment = ("Issue resolved by pull request %s\n[%s/%s]"
                    % (pr_num, GITHUB_BASE, pr_num))
    resolve_jira(title, merged_refs, jira_comment)
else:
    print("Could not find jira-python library. "
          "Run 'sudo pip install jira-python' to install.")
    print("Exiting without trying to close the associated JIRA.")


text:
void print_linker_error(std::string message){
    std::cerr<<"LINKER ERROR: " << message << "\n";
}

Node::~Node(){}

Bash_node::Bash_node(std::string bash_command, Group* parent):bash_command(bash_command){
    this->parent = parent;
    visited = false;
    needed = false;
    cycle_dfs_active = false;
    node_type = BASH_NODE;
}

bool Bash_node::is_input(){
    return (this->parent->input_node == this);
}

bool Bash_node::is_output(){
    return (this->parent->output_node == this);
}

Io_node::Io_node(std::string io_type_str, int number, Group* parent):number(number){
    this->parent = parent;
    io_type = (io_type_str == "infile") ? INPUT : OUTPUT;
    visited = false;
    needed = false;
    cycle_dfs_active = false;
    node_type = IO_NODE;
}

bool Io_node::is_input(){
    return io_type == INPUT;
}

bool Io_node::is_output(){
    return io_type == OUTPUT;
}

Stdio_node::Stdio_node(Io_type io_type,Group* parent):io_type(io_type){
    this->parent = parent;
    visited = false;
    needed = false;
    cycle_dfs_active = false;
    node_type = STDIO_NODE;
    name = (io_type == INPUT) ? "input" : "output";
}

bool Stdio_node::is_input(){
    return io_type == INPUT;
}

bool Stdio_node::is_output(){
    return io_type == OUTPUT;
}

Instance_node::Instance_node(std::string group_name,Group* parent):group_name(group_name){
    this->parent = parent;
    visited = false;
    needed = false;
    recursive = false;
    cycle_dfs_active = false;
    node_type = INSTANCE_NODE;
}

bool Instance_node::is_input(){
    return false;
}

bool Instance_node::is_output(){
    return false;
}

bool Instance_node::link_groups(std::unordered_map<std::string, Group*> & groups_namespace){
    if(groups_namespace.find(group_name) != groups_namespace.end()){
	group = groups_namespace[group_name]; // link to group
	if(group->parent != parent){
	    // found a recursive call
	    // this will have to be adjusted
	    // if the namespace system changes
	    recursive = true;
	}
	return true;
    }else{
	print_linker_error("Group \"" + group_name + "\" could not be found.");
	return false;
    }
}

// The edge constructor
Edge::Edge(std::string source_name,
	   std::string mod_source_str,
	   std::string destination_name,
	   std::string mod_destination_str)
{
    this->source_name = source_name;
    this->destination_name = destination_name;

    mod_source = (mod_source_str == "inv") ? INVERSE : NONE;
    if(mod_destination_str == ""){
	mod_destination = NONE;
	mod_nr_destination = 0;
    }else{
	mod_destination = (mod_destination_str[0] == 'h') ? HORIZONTAL : VERTICAL;
	mod_nr_destination = stoi(mod_destination_str.substr(1));
    }

    needed = true;
}

bool Edge::link_nodes(std::unordered_map<std::string, Node*> & nodes_namespace){

    // link source node
    if(nodes_namespace.find(source_name) == nodes_namespace.end()){
	print_linker_error("Source node \"" + source_name + "\" could not be found.");
	return false;
    }

    if(nodes_namespace[source_name]->is_output()){
	print_linker_error("Node \"" + source_name + "\" cannot be used as source.");
	return false;
    }

    source = nodes_namespace[source_name];

    // link destination node
    if(nodes_namespace.find(destination_name) == nodes_namespace.end()){
	print_linker_error("Destination node \"" + destination_name + "\" could not be found.");
	return false;
    }

    if(nodes_namespace[destination_name]->is_input()){
	print_linker_error("Node \"" + destination_name + "\" cannot be used as destination.");
	return false;
    }

    destination = nodes_namespace[destination_name];

    return true;
}

Group::Group(Group* parent):parent(parent){
    visited = false;
    name = "";
    input_node = new Stdio_node(INPUT, this);
    output_node = new Stdio_node(OUTPUT, this);
}

std::vector<Node*> Group::list_inputs(){
    std::vector<Node*> out;
    std::vector<Node*> nodes = list_all_nodes();
    for(auto n:nodes){
	if(n->is_input()){
	    out.push_back(n);
	}
    }
    return out;
}

std::vector<Node*> Group::list_all_nodes(){
    std::vector<Node*> out;
    if(input_node != 0){
	out.push_back(input_node);
    }
    if(output_node != 0){
	out.push_back(output_node);
    }
    for(auto n:children_io_nodes){
	out.push_back(n);
    }
    for(auto n:children_bash_nodes){
	out.push_back(n);
    }
    for(auto n:children_instance_nodes){
	out.push_back(n);
    }
    return out;
}


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

<!-- -->
<!-- Copyright 2011 Uri Shaked -->
<!-- Licensed under the Apache License, Version 2.0 (the "License"); you -->
<!-- may not use this file except in compliance with the License. You may -->
<!-- may obtain a copy of the License at -->
<!-- -->
<!-- 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. License for the specific language governing permissions and -->
<!-- limitations under the License. -->

<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>org.urish.gwt-titanium</groupId>
	<artifactId>gwt-titanium</artifactId>
	<version>0.2.2-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>gwt-titanium</name>
	<description>Titanium Module for Google Web Toolkit</description>
	<url>http://www.iphonejava.org</url>

	<developers>
		<developer>
			<name>Uri Shaked</name>
			<roles>
				<role>Lead Programmer</role>
			</roles>
			<email>uri@salsa4fun.co.il</email>
		</developer>
	</developers>

	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<parent>
		<groupId>org.sonatype.oss</groupId>
		<artifactId>oss-parent</artifactId>
		<version>7</version>
	</parent>

	<scm>
		<connection>scm:git:git@github.com:urish/gwt-titanium.git</connection>
		<developerConnection>scm:git:git@github.com:urish/gwt-titanium.git</developerConnection>
		<url>git@github.com:urish/gwt-titanium.git</url>
	</scm>

	<properties>
		<gwt.version>2.3.0</gwt.version>
	</properties>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<additionalprojectnatures>
						<projectnature>org.maven.ide.eclipse.maven2Nature</projectnature>
					</additionalprojectnatures>
					<additionalbuildcommands>
						<buildcommand>org.maven.ide.eclipse.maven2Builder</buildcommand>
					</additionalbuildcommands>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/client/**</include>
					<include>**/titanium/**</include>
					<include>**/*.gwt.xml</include>
				</includes>
			</resource>
		</resources>
	</build>
	<dependencies>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-user</artifactId>
			<version>${gwt.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-dev</artifactId>
			<version>${gwt.version}</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>


text:
package de.tu_berlin.dima.bdapro.flink.oddsemordnilaps.vincent12344

import org.apache.flink.api.scala._

object OddSemordnilaps {

  def main(args: Array[String]): Unit = {

    val env = ExecutionEnvironment.getExecutionEnvironment

    val input = env.readTextFile(args{0})

    val distinctOddNumbers = input.flatMap { _.split("\\n") }
      .flatMap {_.split(" ")}
      .filter {a => a.length != 0 && a.toInt % 2 == 1}
      .distinct

    val semoCount = distinctOddNumbers.cross(distinctOddNumbers)
      .filter {a => a._1.equals(a._2.reverse)}
      .count

    print("The result is " + semoCount)
  }
}


text:
Rails.application.routes.draw do
  if Rails.env.development?
    require 'sidekiq/web'
    mount Sidekiq::Web => '/sidekiq'
    # get '/rails/mailers' => 'rails/mailers#index'
    # get '/rails/mailers/*path' => 'rails/mailers#preview'
  end

  resource :health_check, only: [:show]

  # API Routes
  scope :api, format: false, defaults: { format: :jsonapi } do
    resource :app_settings, only: [:show, :update]

    resource :registrations, only: [:create]
    resource :sessions, only: [:create, :destroy]
    resource :passwords, only: [:create, :update]

    resources :users, only: [:index, :show, :create, :update, :destroy] do
      resource :password, only: [:update], module: :users
      resource :action, only: [:create], module: :users
    end

    resource :account_info, only: [:show]

    resources :provider_types, only: [:index, :show]
    resources :provider_data, only: [:index, :show]
    resources :providers do
      resource :connection, only: [:update], module: :providers
      resource :sync, only: [:create], module: :providers
    end
    namespace :providers do
      resource :credentials, only: [:create]
    end

    resources :product_categories

    resources :product_types, only: [:index, :show]
    resources :products

    resources :service_requests do
      resource :approval, only: [:create], module: :service_requests
    end
    resources :service_orders
    resources :services do
      resource :action, only: [:create], module: :services
    end
    resources :service_details, only: [:index, :show]

    resources :project_requests do
      resource :approval, only: [:create], module: :project_requests
    end
    resources :projects

    resources :project_questions

    resources :memberships
    resources :members, only: [:index, :show]

    resources :filters
  end

  # NOTICE: If the Client is extracted from the API remove the following routes.
  # Client Handling
  root 'client#index'
  resource :remote_auth_sessions, only: [:create], path: :remote_login
  match '*path' => 'client#index', via: :all
end


text:
(function(){
  'use strict';
  Handlebars.registerHelper('i18n',
    function(options){
      return app.i18n.translate(options.hash.string, options.hash);
    }
  );

  app.i18n.registerEN();
  app.i18n.registerFR();
  app.i18n.setDefault('en');
  app.i18n.setLanguage('fr');
})();


text:
import {
    ReactAttr,
    ReactAnchorAttr,
    FCReturn,
    ForwardRefProps,
} from '../../../typings/shared';
import { LinkProps } from "./Link";

interface InheritedProps {
    children?: ReactAttr["children"],
    className?: ReactAttr["className"],
}

export interface SideNavMenuItemPropsBase extends InheritedProps {
    isActive?: boolean,
}

export type SideNavMenuItemProps<E extends object = ReactAnchorAttr> = LinkProps<E> & SideNavMenuItemPropsBase;

declare function SideNavMenuItem<E extends object = ReactAnchorAttr, R = HTMLElement>(
    props: ForwardRefProps<R, SideNavMenuItemProps<E>>
): FCReturn;

export default SideNavMenuItem;


text:
package com.bagri.core.model;

public class Null implements Comparable {

	public static final Null _null = new Null();

	private Null() {}

	@Override
	public int compareTo(Object o) {
		return -1;
	}

	@Override
	public String toString() {
		return "null";
	}

}


text:
using System;
using Robust.Shared.Map;
using Robust.Shared.Maths;

namespace Content.Server.Atmos
{
    public static class EntityNetworkUtils
    {
        public static Vector2i CardinalToIntVec(this Direction dir)
        {
            switch (dir)
            {
                case Direction.North:
                    return new Vector2i(0, 1);
                case Direction.East:
                    return new Vector2i(1, 0);
                case Direction.South:
                    return new Vector2i(0, -1);
                case Direction.West:
                    return new Vector2i(-1, 0);
                default:
                    throw new ArgumentException($"Direction dir {dir} is not a cardinal direction", nameof(dir));
            }
        }

        public static Vector2i Offset(this Vector2i pos, Direction dir)
        {
            return pos + (Vector2i) dir.CardinalToIntVec();
        }
    }
}


text:
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/

(function ($, Drupal, Sortable) {
  Drupal.behaviors.MediaLibraryWidgetSortable = {
    attach: function attach(context) {
      var selection = context.querySelectorAll('.js-media-library-selection');
      selection.forEach(function (widget) {
        Sortable.create(widget, {
          draggable: '.js-media-library-item',
          handle: '.js-media-library-item-preview',
          onEnd: function onEnd() {
            $(widget).children().each(function (index, child) {
              $(child).find('.js-media-library-item-weight')[0].value = index;
            });
          }
        });
      });
    }
  };
  Drupal.behaviors.MediaLibraryWidgetToggleWeight = {
    attach: function attach(context) {
      var strings = {
        show: Drupal.t('Show media item weights'),
        hide: Drupal.t('Hide media item weights')
      };
      var mediaLibraryToggle = once('media-library-toggle', '.js-media-library-widget-toggle-weight', context);
      $(mediaLibraryToggle).on('click', function (e) {
        e.preventDefault();
        var $target = $(e.currentTarget);
        e.currentTarget.textContent = $target.hasClass('active') ? strings.show : strings.hide;
        $target.toggleClass('active').closest('.js-media-library-widget').find('.js-media-library-item-weight').parent().toggle();
      });
      mediaLibraryToggle.forEach(function (item) {
        item.textContent = strings.show;
      });
      $(once('media-library-toggle', '.js-media-library-item-weight', context)).parent().hide();
    }
  };
  Drupal.behaviors.MediaLibraryWidgetDisableButton = {
    attach: function attach(context) {
      once('media-library-disable', '.js-media-library-open-button[data-disabled-focus="true"]', context).forEach(function (button) {
        $(button).focus();
        setTimeout(function () {
          $(button).attr('disabled', 'disabled');
        }, 50);
      });
    }
  };
})(jQuery, Drupal, Sortable);


text:
Fixes # .

Changes proposed in this request:
-
-
-

@ISS-Mimic


text:
//
//  ClockBuilder.h
//  JLIGameEngineTest
//
//  Created by James Folk on 11/22/14.
//  Copyright (c) 2014 James Folk. All rights reserved.
//

#ifndef __JLIGameEngineTest__ClockBuilder__
#define __JLIGameEngineTest__ClockBuilder__

#include "btAlignedObjectArray.h"
#include "Util.h"
#include "AbstractBuilder.h"
#include "btSerializer.h"
#include "lua.hpp"

namespace njli
{
    /**
     *  <#Description#>
     */
    ATTRIBUTE_ALIGNED16(class) ClockBuilder :
    public AbstractBuilder
    {
        friend class WorldFactory;
    protected:
        ClockBuilder();
        ClockBuilder(const ClockBuilder &);
        BT_DECLARE_ALIGNED_ALLOCATOR();
        virtual ~ClockBuilder();

        ClockBuilder &operator=(const ClockBuilder &);

    public:
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        virtual	s32	calculateSerializeBufferSize() const;

        /**
         *  @author James Folk, 16-02-11 15:02:52
         *
         *  @brief <#Description#>
         *
         *  @param dataBuffer   <#dataBuffer description#>
         *  @param btSerializer <#btSerializer description#>
         */
        virtual	void serialize(void*dataBuffer, btSerializer*) const;

        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        virtual u32 getObjectType()const;
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        virtual const char *getClassName()const;
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        virtual s32 getType()const;
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        operator std::string() const;

        /**
         *  <#Description#>
         *
         *  @param size <#size description#>
         *
         *  @return <#return value description#>
         */
        static ClockBuilder **createArray(const u32 size);
        /**
         *  <#Description#>
         *
         *  @param array <#array description#>
         */
        static void destroyArray(ClockBuilder **array, const u32 size = 0);
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        static ClockBuilder *create();
        /**
         *  <#Description#>
         *
         *  @param object <#object description#>
         *
         *  @return <#return value description#>
         */
        static ClockBuilder *clone(const ClockBuilder &object);
        /**
         *  <#Description#>
         *
         *  @param object <#object description#>
         */
        static void destroy(ClockBuilder *object);
        /**
         *  <#Description#>
         *
         *  @param object      <#object description#>
         *  @param L           <#L description#>
         *  @param stack_index <#stack_index description#>
         */
        static void load(ClockBuilder &object, lua_State *L, int stack_index);
        /**
         *  <#Description#>
         *
         *  @return <#return value description#>
         */
        static u32 type();
    };
}

#endif /* defined(__JLIGameEngineTest__ClockBuilder__) */


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Layout;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using Xunit;

namespace Avalonia.Controls.UnitTests
{
    public class WindowTests
    {
        [Fact]
        public void Setting_Title_Should_Set_Impl_Title()
        {
            var windowImpl = new Mock<IWindowImpl>();
            var windowingPlatform = new MockWindowingPlatform(() => windowImpl.Object);

            using (UnitTestApplication.Start(new TestServices(windowingPlatform: windowingPlatform)))
            {
                var target = new Window();

                target.Title = "Hello World";

                windowImpl.Verify(x => x.SetTitle("Hello World"));
            }
        }

        [Fact]
        public void IsVisible_Should_Initially_Be_False()
        {
            using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
            {
                var window = new Window();

                Assert.False(window.IsVisible);
            }
        }

        [Fact]
        public void IsVisible_Should_Be_True_After_Show()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var window = new Window();

                window.Show();

                Assert.True(window.IsVisible);
            }
        }

        [Fact]
        public void IsVisible_Should_Be_True_After_ShowDialog()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var parent = new Window();
                parent.Show();
                var window = new Window();

                var task = window.ShowDialog(parent);

                Assert.True(window.IsVisible);
            }
        }

        [Fact]
        public void IsVisible_Should_Be_False_After_Hide()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var window = new Window();

                window.Show();
                window.Hide();

                Assert.False(window.IsVisible);
            }
        }

        [Fact]
        public void IsVisible_Should_Be_False_After_Close()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var window = new Window();

                window.Show();
                window.Close();

                Assert.False(window.IsVisible);
            }
        }

        [Fact]
        public void IsVisible_Should_Be_False_After_Impl_Signals_Close()
        {
            var windowImpl = new Mock<IWindowImpl>();
            windowImpl.SetupProperty(x => x.Closed);
            windowImpl.Setup(x => x.DesktopScaling).Returns(1);
            windowImpl.Setup(x => x.RenderScaling).Returns(1);

            var services = TestServices.StyledWindow.With(
                windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object));

            using (UnitTestApplication.Start(services))
            {
                var window = new Window();

                window.Show();
                windowImpl.Object.Closed();

                Assert.False(window.IsVisible);
            }
        }

        [Fact]
        public void Closing_Should_Only_Be_Invoked_Once()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var window = new Window();
                var count = 0;

                window.Closing +=
                    (sender, e) =>
                    {
                        count++;
                    };

                window.Show();
                window.Close();

                Assert.Equal(1, count);
            }
        }

        [Fact]
        public void Showing_Should_Start_Renderer()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var renderer = new Mock<IRenderer>();
                var target = new Window(CreateImpl(renderer));

                target.Show();

                renderer.Verify(x => x.Start(), Times.Once);
            }
        }

        [Fact]
        public void ShowDialog_Should_Start_Renderer()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var parent = Mock.Of<Window>();
                var renderer = new Mock<IRenderer>();
                var target = new Window(CreateImpl(renderer));

                target.ShowDialog<object>(parent);

                renderer.Verify(x => x.Start(), Times.Once);
            }
        }

        [Fact]
        public void ShowDialog_Should_Raise_Opened()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var parent = Mock.Of<Window>();
                var target = new Window();
                var raised = false;

                target.Opened += (s, e) => raised = true;

                target.ShowDialog<object>(parent);

                Assert.True(raised);
            }
        }

        [Fact]
        public void Hiding_Should_Stop_Renderer()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var renderer = new Mock<IRenderer>();
                var target = new Window(CreateImpl(renderer));

                target.Show();
                target.Hide();

                renderer.Verify(x => x.Stop(), Times.Once);
            }
        }

        [Fact]
        public async Task ShowDialog_With_ValueType_Returns_Default_When_Closed()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var parent = new Mock<Window>();
                var windowImpl = new Mock<IWindowImpl>();
                windowImpl.SetupProperty(x => x.Closed);
                windowImpl.Setup(x => x.DesktopScaling).Returns(1);
                windowImpl.Setup(x => x.RenderScaling).Returns(1);

                var target = new Window(windowImpl.Object);
                var task = target.ShowDialog<bool>(parent.Object);

                windowImpl.Object.Closed();

                var result = await task;
                Assert.False(result);
            }
        }

        [Fact]
        public void Calling_Show_On_Closed_Window_Should_Throw()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var target = new Window();

                target.Show();
                target.Close();

                var openedRaised = false;
                target.Opened += (s, e) => openedRaised = true;

                var ex = Assert.Throws<InvalidOperationException>(() => target.Show());
                Assert.Equal("Cannot re-show a closed window.", ex.Message);
                Assert.False(openedRaised);
            }
        }

        [Fact]
        public async Task Calling_ShowDialog_On_Closed_Window_Should_Throw()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var parent = new Mock<Window>();
                var windowImpl = new Mock<IWindowImpl>();
                windowImpl.SetupProperty(x => x.Closed);
                windowImpl.Setup(x => x.DesktopScaling).Returns(1);
                windowImpl.Setup(x => x.RenderScaling).Returns(1);

                var target = new Window(windowImpl.Object);
                var task = target.ShowDialog<bool>(parent.Object);

                windowImpl.Object.Closed();
                await task;

                var openedRaised = false;
                target.Opened += (s, e) => openedRaised = true;

                var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => target.ShowDialog<bool>(parent.Object));
                Assert.Equal("Cannot re-show a closed window.", ex.Message);
                Assert.False(openedRaised);
            }
        }

        [Fact]
        public void Window_Should_Be_Centered_When_WindowStartupLocation_Is_CenterScreen()
        {
            var screen1 = new Mock<Screen>(1.0, new PixelRect(new PixelSize(1920, 1080)), new PixelRect(new PixelSize(1920, 1040)), true);
            var screen2 = new Mock<Screen>(1.0, new PixelRect(new PixelSize(1366, 768)), new PixelRect(new PixelSize(1366, 728)), false);

            var screens = new Mock<IScreenImpl>();
            screens.Setup(x => x.AllScreens).Returns(new Screen[] { screen1.Object, screen2.Object });

            var windowImpl = MockWindowingPlatform.CreateWindowMock();
            windowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480));
            windowImpl.Setup(x => x.DesktopScaling).Returns(1);
            windowImpl.Setup(x => x.RenderScaling).Returns(1);
            windowImpl.Setup(x => x.Screen).Returns(screens.Object);

            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var window = new Window(windowImpl.Object);
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.Position = new PixelPoint(60, 40);

                window.Show();

                var expectedPosition = new PixelPoint(
                    (int)(screen1.Object.WorkingArea.Size.Width / 2 - window.ClientSize.Width / 2),
                    (int)(screen1.Object.WorkingArea.Size.Height / 2 - window.ClientSize.Height / 2));

                Assert.Equal(window.Position, expectedPosition);
            }
        }

        [Fact]
        public void Window_Should_Be_Centered_Relative_To_Owner_When_WindowStartupLocation_Is_CenterOwner()
        {
            var parentWindowImpl = MockWindowingPlatform.CreateWindowMock();
            parentWindowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480));
            parentWindowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1920, 1080));
            parentWindowImpl.Setup(x => x.DesktopScaling).Returns(1);
            parentWindowImpl.Setup(x => x.RenderScaling).Returns(1);

            var windowImpl = MockWindowingPlatform.CreateWindowMock();
            windowImpl.Setup(x => x.ClientSize).Returns(new Size(320, 200));
            windowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1920, 1080));
            windowImpl.Setup(x => x.DesktopScaling).Returns(1);
            windowImpl.Setup(x => x.RenderScaling).Returns(1);

            var parentWindowServices = TestServices.StyledWindow.With(
                windowingPlatform: new MockWindowingPlatform(() => parentWindowImpl.Object));

            var windowServices = TestServices.StyledWindow.With(
                windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object));

            using (UnitTestApplication.Start(parentWindowServices))
            {
                var parentWindow = new Window();
                parentWindow.Position = new PixelPoint(60, 40);

                parentWindow.Show();

                using (UnitTestApplication.Start(windowServices))
                {
                    var window = new Window();
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    window.Position = new PixelPoint(60, 40);

                    window.ShowDialog(parentWindow);

                    var expectedPosition = new PixelPoint(
                        (int)(parentWindow.Position.X + parentWindow.ClientSize.Width / 2 - window.ClientSize.Width / 2),
                        (int)(parentWindow.Position.Y + parentWindow.ClientSize.Height / 2 - window.ClientSize.Height / 2));

                    Assert.Equal(window.Position, expectedPosition);
                }
            }
        }

        public class SizingTests
        {
            [Fact]
            public void Child_Should_Be_Measured_With_Width_And_Height_If_SizeToContent_Is_Manual()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var child = new ChildControl();
                    var target = new Window
                    {
                        Width = 100,
                        Height = 50,
                        SizeToContent = SizeToContent.Manual,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(1, child.MeasureSizes.Count);
                    Assert.Equal(new Size(100, 50), child.MeasureSizes[0]);
                }
            }

            [Fact]
            public void Child_Should_Be_Measured_With_ClientSize_If_SizeToContent_Is_Manual_And_No_Width_Height_Specified()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var windowImpl = MockWindowingPlatform.CreateWindowMock();
                    windowImpl.Setup(x => x.ClientSize).Returns(new Size(550, 450));

                    var child = new ChildControl();
                    var target = new Window(windowImpl.Object)
                    {
                        SizeToContent = SizeToContent.Manual,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(1, child.MeasureSizes.Count);
                    Assert.Equal(new Size(550, 450), child.MeasureSizes[0]);
                }
            }

            [Fact]
            public void Child_Should_Be_Measured_With_MaxAutoSizeHint_If_SizeToContent_Is_WidthAndHeight()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var windowImpl = MockWindowingPlatform.CreateWindowMock();
                    windowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1200, 1000));

                    var child = new ChildControl();
                    var target = new Window(windowImpl.Object)
                    {
                        Width = 100,
                        Height = 50,
                        SizeToContent = SizeToContent.WidthAndHeight,
                        Content = child
                    };

                    target.Show();

                    Assert.Equal(1, child.MeasureSizes.Count);
                    Assert.Equal(new Size(1200, 1000), child.MeasureSizes[0]);
                }
            }

            [Fact]
            public void Should_Not_Have_Offset_On_Bounds_When_Content_Larger_Than_Max_Window_Size()
            {
                // Issue #3784.
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var windowImpl = MockWindowingPlatform.CreateWindowMock();
                    var clientSize = new Size(200, 200);
                    var maxClientSize = new Size(480, 480);

                    windowImpl.Setup(x => x.Resize(It.IsAny<Size>())).Callback<Size>(size =>
                    {
                        clientSize = size.Constrain(maxClientSize);
                        windowImpl.Object.Resized?.Invoke(clientSize);
                    });

                    windowImpl.Setup(x => x.ClientSize).Returns(() => clientSize);

                    var child = new Canvas
                    {
                        Width = 400,
                        Height = 800,
                    };
                    var target = new Window(windowImpl.Object)
                    {
                        SizeToContent = SizeToContent.WidthAndHeight,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(new Size(400, 480), target.Bounds.Size);

                    // Issue #3784 causes this to be (0, 160) which makes no sense as Window has no
                    // parent control to be offset against.
                    Assert.Equal(new Point(0, 0), target.Bounds.Position);
                }
            }

            [Fact]
            public void Width_Height_Should_Not_Be_NaN_After_Show_With_SizeToContent_WidthAndHeight()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var child = new Canvas
                    {
                        Width = 400,
                        Height = 800,
                    };

                    var target = new Window()
                    {
                        SizeToContent = SizeToContent.WidthAndHeight,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(400, target.Width);
                    Assert.Equal(800, target.Height);
                }
            }

            [Fact]
            public void SizeToContent_Should_Not_Be_Lost_On_Show()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var child = new Canvas
                    {
                        Width = 400,
                        Height = 800,
                    };

                    var target = new Window()
                    {
                        SizeToContent = SizeToContent.WidthAndHeight,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(SizeToContent.WidthAndHeight, target.SizeToContent);
                }
            }

            [Fact]
            public void Width_Height_Should_Be_Updated_When_SizeToContent_Is_WidthAndHeight()
            {
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var child = new Canvas
                    {
                        Width = 400,
                        Height = 800,
                    };

                    var target = new Window()
                    {
                        SizeToContent = SizeToContent.WidthAndHeight,
                        Content = child
                    };

                    Show(target);

                    Assert.Equal(400, target.Width);
                    Assert.Equal(800, target.Height);

                    child.Width = 410;
                    target.LayoutManager.ExecuteLayoutPass();

                    Assert.Equal(410, target.Width);
                    Assert.Equal(800, target.Height);
                    Assert.Equal(SizeToContent.WidthAndHeight, target.SizeToContent);
                }
            }

            [Fact]
            public void Setting_Width_Should_Resize_WindowImpl()
            {
                // Issue #3796
                using (UnitTestApplication.Start(TestServices.StyledWindow))
                {
                    var target = new Window()
                    {
                        Width = 400,
                        Height = 800,
                    };

                    Show(target);

                    Assert.Equal(400, target.Width);
                    Assert.Equal(800, target.Height);

                    target.Width = 410;
                    target.LayoutManager.ExecuteLayoutPass();

                    var windowImpl = Mock.Get(target.PlatformImpl);
                    windowImpl.Verify(x => x.Resize(new Size(410, 800)));
                    Assert.Equal(410, target.Width);
                }
            }

            protected virtual void Show(Window window)
            {
                window.Show();
            }
        }

        public class DialogSizingTests : SizingTests
        {
            protected override void Show(Window window)
            {
                var owner = new Window();
                window.ShowDialog(owner);
            }
        }

        private IWindowImpl CreateImpl(Mock<IRenderer> renderer)
        {
            return Mock.Of<IWindowImpl>(x =>
                x.RenderScaling == 1 &&
                x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer.Object);
        }

        private class ChildControl : Control
        {
            public List<Size> MeasureSizes { get; } = new List<Size>();

            protected override Size MeasureOverride(Size availableSize)
            {
                MeasureSizes.Add(availableSize);
                return base.MeasureOverride(availableSize);
            }
        }
    }
}


text:
import requests

import fullcontact
from .error import FullContactError

__author__ = 'Amil Osmanli'

class APIResource(dict):
    _api_url = 'https://api.fullcontact.com/v2'
    options = {}

    @classmethod
    def set_version(cls, value):
        cls.options['headers'] = {'API-Version': value}

    @classmethod
    def new(cls, item, response=None):
        if isinstance(item, list):
            instances = (cls(rec) for rec in item)
            for instance in instances:
                instance['response'] = response

        else:
            instances = cls(item)
            instances['response'] = response

        return instances

    @classmethod
    def _get(cls, endpoint, **kwargs):

        if fullcontact.key:
            kwargs['apiKey'] = fullcontact.key
        else:
            raise FullContactError('No key provided')

        url = '%s/%s' % (cls._api_url, endpoint)
        response = requests.get(url, params=kwargs)
        instance = None

        if response.status_code == 200:
            instance = cls.new(response.json())
        if response.status_code == 202:
            instance = cls.new({'pending': True})
        elif response.status_code == requests.codes.not_found:
            instance = None
        else:
            response.raise_for_status()

        if instance:
            instance['response'] = response

        return instance

    def __getitem__(self, key):
        return dict.__getitem__(self, key)


text:
from os.path import basename

import dbus

from i3pystatus import IntervalModule, formatp
from i3pystatus.core.util import TimeWrapper

def proxyobj(bus, path, interface):
    """ commodity to apply an interface to a proxy object """
    obj = bus.get_object('org.bluez', path)
    return dbus.Interface(obj, interface)

def filter_by_interface(objects, interface_name):
    """ filters the objects based on their support
        for the specified interface """
    result = []
    for path in objects.keys():
        interfaces = objects[path]
        for interface in interfaces.keys():
            if interface == interface_name:
                result.append(path)
    return result

def getprop(obj, prop, t):
    return t(obj.Get("org.bluez.Device1", prop))

def get_bluetooth_device_list(show_disconnected):
    # shamelessly stolen from https://stackoverflow.com/questions/14262315/list-nearby-discoverable-bluetooth-devices-including-already-paired-in-python/14267310#14267310
    bus = dbus.SystemBus()

    # we need a dbus object manager
    manager = proxyobj(bus, "/", "org.freedesktop.DBus.ObjectManager")
    objects = manager.GetManagedObjects()

    # once we get the objects we have to pick the bluetooth devices.
    # They support the org.bluez.Device1 interface
    devices = filter_by_interface(objects, "org.bluez.Device1")

    # now we are ready to get the informations we need
    bt_devices = []
    for device in devices:
        obj = proxyobj(bus, device, 'org.freedesktop.DBus.Properties')
        # skip blocked and unpaired devices.
        if getprop(obj, "Blocked", bool):
            continue
        if not getprop(obj, "Paired", bool):
            continue
        if not show_disconnected:
            if not getprop(obj, "Connected", bool):
                continue
        bt_devices.append({
            "name": getprop(obj, "Name", str),
            "dev_addr": getprop(obj, "Address", str),
            "connected": getprop(obj, "Connected", bool)
        })
    return bt_devices

class Bluetooth(IntervalModule):
    """
    Shows currently connected bluetooth devices.

        * Requires ``python-dbus`` from your distro package manager, or \
``dbus-python`` from PyPI.

        Left click on the module to cycle forwards through devices, and right \
click to cycle backwards.

        .. rubric:: Available formatters (uses :ref:`formatp`)

        * `{name}` — (the name of the device)
        * `{dev_addr}` — (the bluetooth device address)

        .. rubric:: Available callbacks

        * ``next_device`` — iterate forward through devices
        * ``prev_device`` — iterate backwards through devices

        Example module registration with callbacks:

        ::
            status.register("now_playing",
                on_leftclick="next_device",
                on_rightclick="prev_device",
                on_upscroll="next_device",
                on_downscroll="prev_device")
    """

    interval = 1

    settings = (
        ("format", "formatp string"),
        ("color", "Text color"),
        ("connected_color", "Connected device color"),
        ("show_disconnected", "Show disconnected but paired devices")
    )

    format = "{name}: {dev_addr}"
    color = "#ffffff"
    connected_color = "#00ff00"

    on_leftclick = "next_device"
    on_rightclick = "prev_device"
    on_upscroll = 'next_device'
    on_downscroll = 'prev_device'

    num_devices = 0
    dev_index = 0
    devices = []
    show_disconnected = True

    def run(self):
        try:
            self.devices = get_bluetooth_device_list(self.show_disconnected)
            if len(self.devices) < 1:
                if hasattr(self, "data"):
                    del self.data
                self.output = None
                return
            self.dev_index = self.dev_index % len(self.devices)
            self.num_devices = len(self.devices)

            fdict = {
                "name": self.devices[self.dev_index]['name'],
                "dev_addr": self.devices[self.dev_index]['dev_addr']
            }

            self.data = fdict
            color = self.color
            if self.devices[self.dev_index]['connected']:
                color = self.connected_color
            self.output = {
                "full_text": formatp(self.format, **fdict).strip(),
                "color": color,
            }
            return
        except dbus.exceptions.DBusException as e:
            self.output = {
                "full_text": "DBus error: " + e.get_dbus_message(),
                "color": "#ff0000",
            }
            if hasattr(self, "data"):
                del self.data
            return

    def next_device(self):
        self.dev_index = (self.dev_index + 1) % self.num_devices

    def prev_device(self):
        self.dev_index = (self.dev_index - 1) % self.num_devices


text:
C implementation of PalDB.

## Limitations

+ Bytes only API.
+ Memory mapping is always active.
+ Read only.

## Performance

Read throughputs for different index sizes (each key ~10 bytes):

+ 1e2 keys: 8.1e6 reads/sec.
+ 1e4 keys: 6.4e6 reads/sec.
+ 1e6 keys: 2.7e6 reads/sec.