text:
var selectLanguage = function(lang){
	switch(lang) {
		case 'br.kingsage.gameforge.com':
			return br;
		case 'kingsage.de':
		case 'de.kingsage.gameforge.com':
			return de;
		case 'kingsage.nl':
		case 'nl.kingsage.gameforge.com':
			return nl;
		case 'kingsage.pl':
		case 'pl.kingsage.gameforge.com':
			return pl;
		case 'kingsage.fr':
		case 'fr.kingsage.gameforge.com':
			return fr;
		case 'kingsage.tr':
		case 'tr.kingsage.gameforge.com':
			return tr;
		case 'kingsage.com':
		case 'kingsage.org':
		case 'en.kingsage.gameforge.com':
		case 'us.kingsage.gameforge.com':
			return en;
		default:
			return en;
	}
};


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>
Moby-Dick</title>
        <link rel="stylesheet" href="css/stylesheet.css" type="text/css" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Chapter 122. Midnight Aloft.—Thunder and Lightning.

THE MAIN-TOP-SAIL YARD.—TASHTEGO PASSING NEW LASHINGS AROUND IT.

"Um, um, um. Stop that thunder! Plenty too much thunder up here. What's the use of thunder? Um, um, um. We don't want thunder; we want rum; give us a glass of rum. Um, um, um!"

redpajama_set_name: RedPajamaGithub


text:
/* (function () {
  'use strict';

  angular
    .module('dispositivos')
    .run(menuConfig);

  menuConfig.$inject = ['Menus'];

  function menuConfig(Menus) {
    // Set top bar menu items
    Menus.addMenuItem('topbar', {
      title: 'Dispositivos',
      state: 'dispositivos',
      type: 'dropdown',
      roles: ['admin', 'user']
    });

    // Add the dropdown list item
    Menus.addSubMenuItem('topbar', 'dispositivos', {
      title: 'List Dispositivos',
      state: 'dispositivos.list'
    });

    // Add the dropdown create item
    Menus.addSubMenuItem('topbar', 'dispositivos', {
      title: 'Create Dispositivo',
      state: 'dispositivos.create',
      roles: ['admin']
    });
  }
})();
*/


text:
package r2rml.engine;

import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;

/**
 * R2RML Class.
 *
 * @author Christophe Debruyne
 * @version 0.1
 *
 */
public final class R2RML {

	public static final String NS = "http://www.w3.org/ns/r2rml#";

	public static final Resource BLANKNODE = ResourceFactory.createResource(NS + "BlankNode");
	public static final Resource IRI = ResourceFactory.createResource(NS + "IRI");
	public static final Resource LITERAL = ResourceFactory.createResource(NS + "Literal");

	// Special resource for default graph
	public static final Resource defaultGraph = ResourceFactory.createResource(NS + "defaultGraph");

	// Classes
	public static final Resource BaseTableOrView = ResourceFactory.createResource(NS + "BaseTableOrView");
	public static final Resource GraphMap = ResourceFactory.createResource(NS + "GraphMap");
	public static final Resource LogicalTable = ResourceFactory.createResource(NS + "LogicalTable");
	public static final Resource ObjectMap = ResourceFactory.createResource(NS + "ObjectMap");
	public static final Resource R2RMLView = ResourceFactory.createResource(NS + "R2RMLView");
	public static final Resource RefObjectMap = ResourceFactory.createResource(NS + "RefObjectMap");
	public static final Resource SubjectMap = ResourceFactory.createResource(NS + "SubjectMap");
	public static final Resource TermMap = ResourceFactory.createResource(NS + "TermMap");
	public static final Resource TriplesMap = ResourceFactory.createResource(NS + "TriplesMap");

	// Properties
	public static final Property child = ResourceFactory.createProperty(NS + "child");
	public static final Property clazz = ResourceFactory.createProperty(NS + "class");
	public static final Property column = ResourceFactory.createProperty(NS + "column");
	public static final Property constant = ResourceFactory.createProperty(NS + "constant");
	public static final Property datatype = ResourceFactory.createProperty(NS + "datatype");
	public static final Property graph = ResourceFactory.createProperty(NS + "graph");
	public static final Property graphMap = ResourceFactory.createProperty(NS + "graphMap");
	public static final Property joinCondition = ResourceFactory.createProperty(NS + "joinCondition");
	public static final Property language = ResourceFactory.createProperty(NS + "language");
	public static final Property logicalTable = ResourceFactory.createProperty(NS + "logicalTable");
	public static final Property object = ResourceFactory.createProperty(NS + "object");
	public static final Property objectMap = ResourceFactory.createProperty(NS + "objectMap");
	public static final Property parent = ResourceFactory.createProperty(NS + "parent");
	public static final Property parentTriplesMap = ResourceFactory.createProperty(NS + "parentTriplesMap");
	public static final Property predicate = ResourceFactory.createProperty(NS + "predicate");
	public static final Property predicateMap = ResourceFactory.createProperty(NS + "predicateMap");
	public static final Property predicateObjectMap = ResourceFactory.createProperty(NS + "predicateObjectMap");
	public static final Property sqlQuery = ResourceFactory.createProperty(NS + "sqlQuery");
	public static final Property subject = ResourceFactory.createProperty(NS + "subject");
	public static final Property subjectMap = ResourceFactory.createProperty(NS + "subjectMap");
	public static final Property tableName = ResourceFactory.createProperty(NS + "tableName");
	public static final Property template = ResourceFactory.createProperty(NS + "template");
	public static final Property termType = ResourceFactory.createProperty(NS + "termType");

}


text:
#ifndef HAL_UGV_IDLE_H
#define HAL_UGV_IDLE_H

// Base controller type
#include <hal_ugv/control/Controller.h>

namespace hal
{
    namespace ugv
    {
        //! A ugv Emergency controller
        /*!
          A more elaborate class description.
        */
        class Idle : public Controller
        {
        public:
            //! Obtain control from state and timestep
            /*!
              \param state the current platform state
              \param dt the discrete time step
              \param control the output control from the controller
              \return if the state could be updated
            */
            void Update(const hal_ugv::State &state,
                double dt, hal_ugv::Control &control);

            //! Goal reach implementations
            /*!
              \return Whether the goal has been reached
            */
            bool HasGoalBeenReached();

            //! Reset implementation
            /*!
              \return Reset the internal state of the controller
            */
            void Reset();
        };
    }
}

#endif


text:
function [M, Mx, My, Mz] = diffusionTerm(D)
% This function uses the central difference scheme to discretize a 2D
% diffusion term in the form \grad . (D \grad \phi) where u is a face vactor
% It also returns the x and y parts of the matrix of coefficient.
%
% SYNOPSIS:
%   [M, Mx, My, Mz] = diffusionTerm(D)
%
% PARAMETERS:
%   D   - diffusion coefficient, FaceVariable
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

d = D.domain.dimension;
switch d
    case 1
        M = diffusionTerm1D(D);
    case 1.5
        M = diffusionTermCylindrical1D(D);
    case 1.8
        M = diffusionTermSpherical1D(D);
    case 2
        [M, Mx, My] = diffusionTerm2D(D);
    case 2.5
        [M, Mx, My] = diffusionTermCylindrical2D(D);
    case 2.8
        [M, Mx, My] = diffusionTermRadial2D(D);
    case 3
        [M, Mx, My, Mz] = diffusionTerm3D(D);
    case 3.2
        [M, Mx, My, Mz] = diffusionTermCylindrical3D(D);
end


text: <google-plus-signin></google-plus-signin>


text:
<TITLE>Review for Big Night (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Big Night (1996)

reviewed by
Vince Waldron

                                  BIG NIGHT

               A film review by Vince Waldron

                Copyright 1997 Vince Waldron

One of the real joys of this past season, and definite must-see.  A wholly
original film that's packed with great performances and privileged
moments.  Though nominally the tale of two brothers struggling to save the
failing restaurant on which they've pegged their hopes and dreams, that
synopsis doesn't begin to do justice to the film's poetry, nor does it
prepare you for the surprising generosity of the film's exquisite pace.
Alternately riveting and almost maddeningly langorous, this is a film of
paradoxes: a film of nuanced subtlety whose comedy is at times painted in
broad strokes indeed.  Making this film must have been an act of faith on
the part of all involved, since it's difficult to imagine how any of the
film's grace notes could possibly have been spelled out in the script, as
good as it may have been.  An elegant tale, deftly told.
reply directly to vince at
ag644@lafn.org

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
Core Datastore Overview
-----------------------

Introduction
------------
The high-level goal of the Mangrove datastore is to allow the free submission
of data about a known set of *entities* and the quick and easy retrieval of
data aggregated across time and hierarchy *without* requiring any upfront
definition of schemas or entity structure.

The key goals can be summarized as:

*   **Support Schema-less submission of arbitrary data**

    This is motivated by expected usage patterns where an organization will
    frequently modify the data collected based on actual usage. By avoiding
    requiring any a-priori definition of data-sets users are given full
    flexibility to adjust data collected on-the-fly.

    for example, a health NGO operating rural clinics might begin by simply
    collecting a monthly report of how many patients where seen in that month.
    As they get more sophisticated they may start collecting separate values for
    men, women, girls and boys. This transition should not require any datastore
    restructuring.

*   **Support aggregation of data across time and hierarchy (geographic as special case)**

    Time-based aggregations include queries such as "Average number of patients seen in 2011" or
    more complex segmented time aggregations such as "Average number of patients seen each month in 2011"

    The key hierarchical aggregation is by geographic administrative boundaries. For example:
    "Total number of patients seen in 2011 for all clinics in San Francisco
    (or California or United States)"

    Non-geographic arbitrary aggregation trees as supported as well. For example, aggregation by
    organization chart: "Patients seen at clinics managed by the Child Protection group"

*   **Provide data consistency on a field level via 'Data Dictionary'**

    To make it easy for users to aggregate data collect for a given entity via
    unstructured data submissions, the core datastore will include a 'Data Dictionary'
    where semantic-types are defined at stored. These types are then applied to submitted
    data fields allowing aggregation across different submissions and encouraging data
    consistency.

    For example, our health NGO now wishes to  collecting data on each patient who receives an HIV
    test so they submit data for each patient test in form (name, age-in-years, test-administered).

    Later they start recording patients who receive family-planning counseling and collect:
    (name, age-in-years, counseling-program-attended)

    When they want to get the average age of patients who received HIV Tests or Family Planning Counseling
    the system can aggregate values of 'age-in-years' from both submissions even though the structure of
    each submission is different.

    And later, when they want to start registering infants seen, they can define a more useful 'Age in Months'
    field (with values ranging from 0-60) and still run aggregations of the form
    "Average age of patients seen" by multiplying any aggregated "Age in Years" values by 12 before averaging
    with "Age in Months" fields.

*   **Provide simple Python and RESTful APIs for accessing data and standard aggregation queries**

    The datastore is agnostic as to both the sources and consumers of data. These APIs will allow data sources
    ranging from SMS engines, to XForms clients and Web applications to submit data.

    On the visualization and reporting side, charting, plotting, graphing, and geographic visualization
    clients may access data series suitable for visualization pre-aggregated across time and hierarchy.

Core Structures
---------------

The logical architecture as envision has very few structures:

*   **Entity**

    An 'entity' is anything that users may want to report on. For example: a patient, a clinic,
    a waterpoint, etc... Entities are *typed* (e.g. 'Clinic', 'Waterpoint') and *uniquely identified*

    Entities contain *no data* beyond **UID** and **TYPE**

    Entities must be *registered* in the system before data can be collected on them.
    Registration is nothing more than the process of assigning a UID to the entity and does *not*
    have to be a distinct user-action—the datastore can register an entity as part of the process of
    recording the first submission of data on the entity.

*   **Data Record**

    Every time data is submitted to the datastore it is saved as an independent time-stamped data record.

    Each data record is associated with a single Entity. The set of data records for a given Entity
    comprises all the values/data known about that Entity.

    For example, if a user submits a report that 10 patients were seen in May at Clinic1, and other user
    submits a report that Clinic1 had stock of 20 bednets in May, the set of
    information known about Clinic1 is that in May 10 patients were seen and 20 bednets are in stock.

*   **Fields and Values**

    Each data record contains an arbitrary set of field/value tuples with fields optionally
    typed from the Data Dictionary.

*   **Data Dictionary Types**

    These are definitions of types which can be associated with fields in a data record. Defined types
    maybe contain the following:

    * Type name
    * Base type (numeric, string, choice, geocode etc...)
    * User readable description
    * Validation constraints

Questions we want to ask the Data Store
---------------------------------------
Rather than set out specific technical proposals, or get caught in the argument
over what should be done in the DB vs. in application logic, here I try to
categorize the different kinds of questions we want to be able to ask the data store.

For the examples, assume the datastore is holding information for a NGO that operates health
clinics throughout the United State.

Basic Retrieval
+++++++++++++++

**Question**
    Retrieve all the Entities of a specific type.
**Example**
    Show a list of all health clinics.

--------

**Question**
    Retrieve specific entity by a unique id.
**Example**
    Show health clinic with ID Clinic001:

--------

**Question**
    Retrieve specific entity by a semi-unique id. This may return a list if there are multiple matches.
**Example**
    Show health clinic with "Free Clinic" in its name.

State Queries
+++++++++++++

**Question**
    Retrieve an Entity (or set of Entities) with a specific set of values.
**Example**
    Show a list of all health clinics and include with each clinic:

    * Geographic location
    * Clinic Directors Name
    * Current stock of Cipro (an antibiotic)

--------

**Question**
    Return an Entity (or set of Entities) with *all* the latest values associated with it.
**Example**
    Show the latest information for Clinic001. This should include the latest reported value of
    every field every reported on this clinic.

--------

**Question**
    Retrieve an Entity (or set of Entities) a set of values *as of a given date*
**Example**
    Show all the latest information on Clinic001 as of Jan 15, 2010

Time Aggregated Queries
+++++++++++++++++++++++

**Question**
    Retrieve an Entity (or set of Entities) with a specific set of values *aggregated* by
    a function such as ``sum()`` or ``avg()`` over a given time range.
**Example**
    Show a list of all health clinics and include with each clinic:

    * Total number of patients seen in 2011

--------

**Question**
    Retrieve an Entity (or set of Entities) with a specific set of values *aggregated* by
    a function such as ``sum()`` or ``avg()`` over a given time range with a given *periodicity*.
**Example**
    Show a list of all health clinics and include with each clinic:

    * Average number of patients seen each *month* for each month in 2011

Selection Queries
+++++++++++++++++
**Question**
    Retrieve all Entities which have a specific value.
**Example**
    Show all health clinics where "Population Served" > 1000

--------

**Question**
    Retrieve all Entities which have a specific *aggregated* value.
**Example**
    Show all health clinics where "Total Patients Seen" > 1000

--------

**Question**
    Retrieve all Entities which have a specific aggregated value over time.
**Example**
    Show all health clinics where "Total Patients Seen in 2011" > 1000

Hierarchy Aggregated Queries
++++++++++++++++++++++++++++
**Note**: These queries don't return entities, they return values aggregated by a
hierarchy node (e.g. 'California' or 'San Francisco') which suggests that maybe
Matt Berg is right and hierarchy nodes maybe should be consider 'Entities', or
'Generated Entities'...

**Question**
    Retrieve a set of *Values* aggregated by a given *node* in a hierarchy.
**Example**
    From the set of all clinics in California show:

    * Total number of patients seen in 2011 (in California)
    * Average number of patients seen in 2011 (in California)

--------

**Question**
    Retrieve a set of *Values* aggregated by a given *level* in a hierarchy.
**Example**
    From each State in the United States show:

    * Total number of patients seen in clinics in that state 2011
    * Average number of patients seen in clinics in that state in 2011


text:
package org.apache.flink.runtime.hadoop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Responsible telling if specific Hadoop dependencies are on classpath. */
public class HadoopDependency {

    private static final Logger LOG = LoggerFactory.getLogger(HadoopDependency.class);

    public static boolean isHadoopCommonOnClasspath(ClassLoader classLoader) {
        try {
            LOG.debug("Checking whether hadoop common dependency in on classpath.");
            Class.forName("org.apache.hadoop.conf.Configuration", false, classLoader);
            Class.forName("org.apache.hadoop.security.UserGroupInformation", false, classLoader);
            LOG.debug("Hadoop common dependency found on classpath.");
            return true;
        } catch (ClassNotFoundException e) {
            LOG.debug("Hadoop common dependency cannot be found on classpath.");
            return false;
        }
    }
}


text:
#ifndef _GLCSHADERSTRUCTTESTS_HPP
#define _GLCSHADERSTRUCTTESTS_HPP
 /*!
 * \file
 * \brief Shader struct tests.
 */ /*-------------------------------------------------------------------*/

#include "glcTestCase.hpp"
#include "gluShaderUtil.hpp"

namespace deqp
{

class ShaderStructTests : public TestCaseGroup
{
public:
	ShaderStructTests(Context& context, glu::GLSLVersion glslVersion);
	virtual ~ShaderStructTests(void);

	virtual void init(void);

private:
	ShaderStructTests(const ShaderStructTests&);			// not allowed!
	ShaderStructTests& operator=(const ShaderStructTests&); // not allowed!

	glu::GLSLVersion m_glslVersion;
};

} // deqp

#endif // _GLCSHADERSTRUCTTESTS_HPP


text:
---
id: 587d824c367417b2b2512c4e
title: Testar se um valor estiver abaixo ou se for pelo menos tão grande quanto outro
challengeType: 2
forumTopicId: 301606
dashedName: test-if-one-value-is-below-or-at-least-as-large-as-another
---

# --description--

Lembrando que este projeto está sendo construído a partir do [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), ou pose ser clonado no [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).

# --instructions--

Em `tests/1_unit-tests.js`, no teste classificado como `#9` e na suíte `Comparisons`, modifique cada `assert` para `assert.isBelow` ou para `assert.isAtLeast`, de maneira que cada teste passe (seja avaliado como `true`). Não altere os argumentos passados às afirmações.

# --hints--

Todos os testes devem passar.

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=8').then(
    (data) => {
      assert.equal(data.state, 'passed');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

Você deve escolher o método correto para a primeira afirmação - `isBelow` ou `isAtLeast`.

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=8').then(
    (data) => {
      assert.equal(
        data.assertions[0].method,
        'isAtLeast',
        '5 is at least (>=) 5'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

Você deve escolher o método correto para a segunda afirmação - `isBelow` ou `isAtLeast`.

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=8').then(
    (data) => {
      assert.equal(
        data.assertions[1].method,
        'isAtLeast',
        '2 * Math.random() is at least 0'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

Você deve escolher o método correto para a terceira afirmação - `isBelow` ou `isAtLeast`.

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=8').then(
    (data) => {
      assert.equal(data.assertions[2].method, 'isBelow', '1 is smaller than 2');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

Você deve escolher o método correto para a quarta afirmação - `isBelow` ou `isAtLeast`.

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=8').then(
    (data) => {
      assert.equal(
        data.assertions[3].method,
        'isBelow',
        '2/3 (0.6666) is smaller than 1'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
//=================================================================================================

//=================================================================================================

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <blaze/util/Timing.h>
#include <blazemark/boost/init/CompressedMatrix.h>
#include <blazemark/boost/TSMatSMatAdd.h>
#include <blazemark/system/Config.h>

namespace blazemark {

namespace boost {

//=================================================================================================
//
//  KERNEL FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Boost uBLAS transpose sparse matrix/sparse matrix addition kernel.
//
// \param N The number of rows and columns of the matrices.
// \param F The number of non-zero elements in each row/column of the sparse matrices.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the transpose sparse matrix/sparse matrix addition by means
// of the Boost uBLAS functionality.
*/
double tsmatsmatadd( size_t N, size_t F, size_t steps )
{
   using ::blazemark::element_t;
   using ::boost::numeric::ublas::row_major;
   using ::boost::numeric::ublas::column_major;

   ::blaze::setSeed( seed );

   ::boost::numeric::ublas::compressed_matrix<element_t,column_major> A( N, N ), C( N, N );
   ::boost::numeric::ublas::compressed_matrix<element_t,row_major> B( N, N );
   ::blaze::timing::WcTimer timer;

   init( A, F );
   init( B, F );

   noalias( C ) = A + B;

   for( size_t rep=0UL; rep<reps; ++rep )
   {
      timer.start();
      for( size_t step=0UL; step<steps; ++step ) {
         noalias( C ) = A + B;
      }
      timer.end();

      if( C.size1() != N )
         std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";

      if( timer.last() > maxtime )
         break;
   }

   const double minTime( timer.min()     );
   const double avgTime( timer.average() );

   if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
      std::cerr << " Boost uBLAS kernel 'tsmatsmatadd': Time deviation too large!!!\n";

   return minTime;
}
//*************************************************************************************************

} // namespace boost

} // namespace blazemark


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

namespace ClosedXML.Excel
{
    internal class XLConditionalFormats : IXLConditionalFormats
    {
        private readonly List<IXLConditionalFormat> _conditionalFormats = new List<IXLConditionalFormat>();

        private static readonly List<XLConditionalFormatType> _conditionalFormatTypesExcludedFromConsolidation = new List<XLConditionalFormatType>()
        {
            XLConditionalFormatType.DataBar,
            XLConditionalFormatType.ColorScale,
            XLConditionalFormatType.IconSet,
            XLConditionalFormatType.Top10,
            XLConditionalFormatType.AboveAverage,
            XLConditionalFormatType.IsDuplicate,
            XLConditionalFormatType.IsUnique
        };

        public void Add(IXLConditionalFormat conditionalFormat)
        {
            _conditionalFormats.Add(conditionalFormat);
        }

        public IEnumerator<IXLConditionalFormat> GetEnumerator()
        {
            return _conditionalFormats.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Remove(Predicate<IXLConditionalFormat> predicate)
        {
            _conditionalFormats.RemoveAll(predicate);
        }

        /// <summary>
        /// The method consolidate the same conditional formats, which are located in adjacent ranges.
        /// </summary>
        internal void Consolidate()
        {
            var formats = _conditionalFormats
                .Where(cf => cf.Ranges.Any())
                .ToList();
            _conditionalFormats.Clear();

            while (formats.Count > 0)
            {
                var item = formats.First();

                if (!_conditionalFormatTypesExcludedFromConsolidation.Contains(item.ConditionalFormatType))
                {
                    var rangesToJoin = new XLRanges();
                    item.Ranges.ForEach(r => rangesToJoin.Add(r));
                    var firstRange = item.Ranges.First();
                    var skippedRanges = new XLRanges();
                    Func<IXLConditionalFormat, bool> IsSameFormat = f =>
                        f != item && f.Ranges.First().Worksheet.Position == firstRange.Worksheet.Position &&
                        XLConditionalFormat.NoRangeComparer.Equals(f, item);

                    //Get the top left corner of the rectangle covering all the ranges
                    var baseAddress = new XLAddress(
                        item.Ranges.Select(r => r.RangeAddress.FirstAddress.RowNumber).Min(),
                        item.Ranges.Select(r => r.RangeAddress.FirstAddress.ColumnNumber).Min(),
                        false, false);
                    var baseCell = firstRange.Worksheet.Cell(baseAddress) as XLCell;

                    int i = 1;
                    bool stop = false;
                    List<IXLConditionalFormat> similarFormats = new List<IXLConditionalFormat>();
                    do
                    {
                        stop = (i >= formats.Count);

                        if (!stop)
                        {
                            var nextFormat = formats[i];

                            var intersectsSkipped =
                                skippedRanges.Any(left => nextFormat.Ranges.GetIntersectedRanges(left.RangeAddress).Any());

                            var isSameFormat = IsSameFormat(nextFormat);

                            if (isSameFormat && !intersectsSkipped)
                            {
                                similarFormats.Add(nextFormat);
                                nextFormat.Ranges.ForEach(r => rangesToJoin.Add(r));
                            }
                            else if (rangesToJoin.Any(left => nextFormat.Ranges.GetIntersectedRanges(left.RangeAddress).Any()) ||
                                     intersectsSkipped)
                            {
                                // if we reached the rule intersecting any of captured ranges stop for not breaking the priorities
                                stop = true;
                            }

                            if (!isSameFormat)
                                nextFormat.Ranges.ForEach(r => skippedRanges.Add(r));
                        }

                        i++;
                    } while (!stop);

                    var consRanges = rangesToJoin.Consolidate();
                    item.Ranges.RemoveAll();
                    consRanges.ForEach(r => item.Ranges.Add(r));

                    var targetCell = item.Ranges.First().FirstCell() as XLCell;
                    (item as XLConditionalFormat).AdjustFormulas(baseCell, targetCell);

                    similarFormats.ForEach(cf => formats.Remove(cf));
                }

                _conditionalFormats.Add(item);
                formats.Remove(item);
            }
        }

        public void RemoveAll()
        {
            _conditionalFormats.Clear();
        }

        /// <summary>
        /// Reorders the according to original priority. Done during load process
        /// </summary>
        public void ReorderAccordingToOriginalPriority()
        {
            var reorderedFormats = _conditionalFormats.OrderBy(cf => (cf as XLConditionalFormat).OriginalPriority).ToList();
            _conditionalFormats.Clear();
            _conditionalFormats.AddRange(reorderedFormats);
        }
    }
}


text:
import os

from oslo.config import cfg
from raksha import exception
from raksha.openstack.common import log as logging
from raksha import utils
from raksha.virt import images

libvirt_opts = [

    ]

CONF = cfg.CONF
CONF.register_opts(libvirt_opts)
LOG = logging.getLogger(__name__)

def get_disk_backing_file(path, basename=True):
    """Get the backing file of a disk image

    :param path: Path to the disk image
    :returns: a path to the image's backing store
    """
    backing_file = images.qemu_img_info(path).backing_file
    if backing_file and basename:
        backing_file = os.path.basename(backing_file)

    return backing_file


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rotate = void 0;
const RotateAnimation_1 = require("./RotateAnimation");
const Enums_1 = require("../../../../Enums");
class Rotate {
    constructor() {
        this.animation = new RotateAnimation_1.RotateAnimation();
        this.direction = Enums_1.RotateDirection.clockwise;
        this.path = false;
        this.random = false;
        this.value = 0;
    }
    load(data) {
        if (data === undefined) {
            return;
        }
        if (data.direction !== undefined) {
            this.direction = data.direction;
        }
        this.animation.load(data.animation);
        if (data.path !== undefined) {
            this.path = data.path;
        }
        if (data.random !== undefined) {
            this.random = data.random;
        }
        if (data.value !== undefined) {
            this.value = data.value;
        }
    }
}
exports.Rotate = Rotate;


text:
GENERATED_FILES = \
	bower.json \
	package.json \
	topojson.min.js \
	examples/us-10m.json \
	examples/world-50m.json \
	examples/world-110m.json

INTERMEDIATE_FILES = \
	node_modules/us-atlas/topo/us-*.json \
	node_modules/world-atlas/topo/world-*.json

.SECONDARY:

.PHONY: all clean test

all: $(GENERATED_FILES)

bower.json: bin/bower topojson.js
	@rm -f $@
	bin/bower > $@
	@chmod a-w $@

package.json: bin/package topojson.js
	@rm -f $@
	bin/package > $@
	@chmod a-w $@

topojson.min.js: topojson.js
	node_modules/.bin/uglifyjs $^ -c -m -o $@

examples/us-%.json: node_modules/us-atlas/topo/us-%.json
	cp $< $@

examples/world-%.json: node_modules/world-atlas/topo/world-%.json
	cp $< $@

node_modules/us-atlas/topo/%.json:
	make topo/$(notdir $@) -C node_modules/us-atlas

node_modules/world-atlas/topo/%.json:
	make topo/$(notdir $@) -C node_modules/world-atlas

test: all
	@npm test

clean:
	rm -f -- $(GENERATED_FILES) $(INTERMEDIATE_FILES)


text:
package org.jexif.tags.database.type;

import java.nio.ByteOrder;

public class JExifSRational extends AbstractJExifType {

    private static final String NAME = "SRATIONAL";
    private static final short ID = 10;
    private static final short BYTES_NO = 8;
    public static final JExifSRational instance = new JExifSRational();

    private JExifSRational() {
        super(ID, NAME, BYTES_NO);
    }

    @Override
    public String convert(byte[] value, ByteOrder bo) {
        return "SRational value should be here";
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Threading;
using Xunit;

namespace System.Linq.Parallel.Tests
{
    public static class ZipTests
    {
        //
        // Zip
        //

        // Get two ranges, where the right starts at the end of the left range.
        public static IEnumerable<object[]> ZipUnorderedData(int[] counts)
        {
            foreach (int leftCount in counts)
            {
                foreach (int rightCount in counts)
                {
                    yield return new object[] { leftCount, rightCount };
                }
            }
        }

        // Get two ranges, where the right starts and the end of the left range.
        // Either or both range will be ordered.
        public static IEnumerable<object[]> ZipData(int[] counts)
        {
            counts = counts.DefaultIfEmpty(Sources.OuterLoopCount / 8).ToArray();
            foreach (object[] parms in UnorderedSources.BinaryRanges(counts, (left, right) => left, counts))
            {
                yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
                yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
                yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
            }
        }

        // Get two ranges, both from 0 to each count, and having an extra parameter denoting the degree or parallelism to use.
        public static IEnumerable<object[]> ZipThreadedData(int[] counts, int[] degrees)
        {
            foreach (object[] left in Sources.Ranges(counts))
            {
                foreach (object[] right in Sources.Ranges(counts, x => degrees))
                {
                    yield return new object[] { left[0], left[1], right[0], right[1], right[2] };
                }
            }
        }

        [Theory]
        [MemberData(nameof(ZipUnorderedData), new[] { 0, 1, 2, 16 })]
        public static void Zip_Unordered(int leftCount, int rightCount)
        {
            ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
            ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
            IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
            foreach (var pair in leftQuery.Zip(rightQuery, (x, y) => KeyValuePair.Create(x, y)))
            {
                // For unordered collections the pairing isn't actually guaranteed, but an effect of the implementation.
                // If this test starts failing it should be updated, and possibly mentioned in release notes.
                Assert.Equal(pair.Key + leftCount, pair.Value);
                seen.Add(pair.Key);
            }
            seen.AssertComplete();
        }

        [Fact]
        [OuterLoop]
        public static void Zip_Unordered_Longrunning()
        {
            Zip_Unordered(Sources.OuterLoopCount / 4, Sources.OuterLoopCount / 4);
        }

        [Theory]
        [MemberData(nameof(ZipData), new[] { 0, 1, 2, 16 })]
        public static void Zip(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
        {
            // The ordering of Zip is only guaranteed when both operands are ordered,
            // however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
            // If this test starts failing, consider revising the operators and mention the change in release notes.
            ParallelQuery<int> leftQuery = left.Item;
            ParallelQuery<int> rightQuery = right.Item;
            int seen = 0;
            foreach (var pair in leftQuery.Zip(rightQuery, (x, y) => KeyValuePair.Create(x, y)))
            {
                Assert.Equal(seen++, pair.Key);
                Assert.Equal(pair.Key + leftCount, pair.Value);
            }
            Assert.Equal(Math.Min(leftCount, rightCount), seen);
        }

        [Theory]
        [OuterLoop]
        [MemberData(nameof(ZipData), new int[] { /* Sources.OuterLoopCount */ })]
        public static void Zip_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
        {
            Zip(left, leftCount, right, rightCount);
        }

        [Theory]
        [MemberData(nameof(ZipUnorderedData), new[] { 0, 1, 2, 16 })]
        public static void Zip_Unordered_NotPipelined(int leftCount, int rightCount)
        {
            ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
            ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
            IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
            Assert.All(leftQuery.Zip(rightQuery, (x, y) => KeyValuePair.Create(x, y)).ToList(),
                pair =>
                {
                    // For unordered collections the pairing isn't actually guaranteed, but an effect of the implementation.
                    // If this test starts failing it should be updated, and possibly mentioned in release notes.
                    Assert.Equal(pair.Key + leftCount, pair.Value);
                    seen.Add(pair.Key);
                });
            seen.AssertComplete();
        }

        [Fact]
        [OuterLoop]
        public static void Zip_Unordered_NotPipelined_Longrunning()
        {
            Zip_Unordered_NotPipelined(Sources.OuterLoopCount / 4, Sources.OuterLoopCount / 4);
        }

        [Theory]
        [MemberData(nameof(ZipData), new[] { 0, 1, 2, 16 })]
        public static void Zip_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
        {
            // The ordering of Zip is only guaranteed when both operands are ordered,
            // however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
            // If this test starts failing, consider revising the operators and mention the change in release notes.
            ParallelQuery<int> leftQuery = left.Item;
            ParallelQuery<int> rightQuery = right.Item;
            int seen = 0;
            Assert.All(leftQuery.Zip(rightQuery, (x, y) => KeyValuePair.Create(x, y)).ToList(),
                pair =>
                {
                    Assert.Equal(seen++, pair.Key);
                    Assert.Equal(pair.Key + leftCount, pair.Value);
                });
            Assert.Equal(Math.Min(leftCount, rightCount), seen);
        }

        [Theory]
        [OuterLoop]
        [MemberData(nameof(ZipData), new int[] { /* Sources.OuterLoopCount */ })]
        public static void Zip_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
        {
            Zip_NotPipelined(left, leftCount, right, rightCount);
        }

        // Zip with ordering on showed issues, but it was due to the ordering component.
        // This is included as a regression test for that particular repro.
        [Theory]
        [OuterLoop]
        [MemberData(nameof(ZipThreadedData), new[] { 1, 2, 16, 128, 1024 }, new[] { 1, 2, 4, 7, 8, 31, 32 })]
        public static void Zip_AsOrdered_ThreadedDeadlock(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int degree)
        {
            ParallelQuery<int> query = left.Item.WithDegreeOfParallelism(degree).Zip<int, int, int>(right.Item, (a, b) => { throw new DeliberateTestException(); });

            AssertThrows.Wrapped<DeliberateTestException>(() => query.ToArray());
        }

        [Fact]
        public static void Zip_NotSupportedException()
        {
#pragma warning disable 618
            Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Zip(Enumerable.Range(0, 1), (x, y) => x));
#pragma warning restore 618
        }

        [Fact]
        // Should not get the same setting from both operands.
        public static void Zip_NoDuplicateSettings()
        {
            CancellationToken t = new CancellationTokenSource().Token;
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Zip(ParallelEnumerable.Range(0, 1).WithCancellation(t), (l, r) => l));
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Zip(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), (l, r) => l));
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Zip(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), (l, r) => l));
            Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Zip(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), (l, r) => l));
        }

        [Fact]
        public static void Zip_ArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Zip(ParallelEnumerable.Range(0, 1), (x, y) => x));
            Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Zip(null, (Func<int, int, int>)((x, y) => x)));
            Assert.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Zip(ParallelEnumerable.Range(0, 1), (Func<int, int, int>)null));
        }
    }
}


text:
/*
 * This file contains a modified version of Ryan Juckett's Dragon4
 * implementation, which has been ported from C++ to C and which has
 * modifications specific to printing floats in numpy.
 */

#ifndef _NPY_DRAGON4_H_
#define _NPY_DRAGON4_H_

#include "Python.h"
#include "structmember.h"
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "npy_config.h"
#include "npy_pycompat.h"
#include "numpy/arrayscalars.h"

/* Half binary format */
#define NPY_HALF_BINFMT_NAME IEEE_binary16

/* Float binary format */
#if NPY_BITSOF_FLOAT == 32
    #define NPY_FLOAT_BINFMT_NAME IEEE_binary32
#elif NPY_BITSOF_FLOAT == 64
    #define NPY_FLOAT_BINFMT_NAME IEEE_binary64
#else
    #error No float representation defined
#endif

/* Double binary format */
#if NPY_BITSOF_DOUBLE == 32
    #define NPY_DOUBLE_BINFMT_NAME IEEE_binary32
#elif NPY_BITSOF_DOUBLE == 64
    #define NPY_DOUBLE_BINFMT_NAME IEEE_binary64
#else
    #error No double representation defined
#endif

/* LongDouble binary format */
#if defined(HAVE_LDOUBLE_IEEE_QUAD_BE)
    #define NPY_LONGDOUBLE_BINFMT_NAME IEEE_binary128_be
#elif defined(HAVE_LDOUBLE_IEEE_QUAD_LE)
    #define NPY_LONGDOUBLE_BINFMT_NAME IEEE_binary128_le
#elif (defined(HAVE_LDOUBLE_IEEE_DOUBLE_LE) || \
       defined(HAVE_LDOUBLE_IEEE_DOUBLE_BE))
    #define NPY_LONGDOUBLE_BINFMT_NAME IEEE_binary64
#elif defined(HAVE_LDOUBLE_INTEL_EXTENDED_12_BYTES_LE)
    #define NPY_LONGDOUBLE_BINFMT_NAME Intel_extended96
#elif defined(HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE)
    #define NPY_LONGDOUBLE_BINFMT_NAME Intel_extended128
#elif defined(HAVE_LDOUBLE_MOTOROLA_EXTENDED_12_BYTES_BE)
    #define NPY_LONGDOUBLE_BINFMT_NAME Motorola_extended96
#elif defined(HAVE_LDOUBLE_IBM_DOUBLE_DOUBLE_LE)
    #define NPY_LONGDOUBLE_BINFMT_NAME IBM_double_double_le
#elif defined(HAVE_LDOUBLE_IBM_DOUBLE_DOUBLE_BE)
    #define NPY_LONGDOUBLE_BINFMT_NAME IBM_double_double_be
#else
    #error No long double representation defined
#endif

typedef enum DigitMode
{
    /* Round digits to print shortest uniquely identifiable number. */
    DigitMode_Unique,
    /* Output the digits of the number as if with infinite precision */
    DigitMode_Exact,
} DigitMode;

typedef enum CutoffMode
{
    /* up to cutoffNumber significant digits */
    CutoffMode_TotalLength,
    /* up to cutoffNumber significant digits past the decimal point */
    CutoffMode_FractionLength,
} CutoffMode;

typedef enum TrimMode
{
    TrimMode_None,         /* don't trim zeros, always leave a decimal point */
    TrimMode_LeaveOneZero, /* trim all but the zero before the decimal point */
    TrimMode_Zeros,        /* trim all trailing zeros, leave decimal point */
    TrimMode_DptZeros,     /* trim trailing zeros & trailing decimal point */
} TrimMode;

#define make_dragon4_typedecl(Type, npy_type) \
    PyObject *\
    Dragon4_Positional_##Type(npy_type *val, DigitMode digit_mode,\
                              CutoffMode cutoff_mode, int precision,\
                              int sign, TrimMode trim, int pad_left,\
                              int pad_right);\
    PyObject *\
    Dragon4_Scientific_##Type(npy_type *val, DigitMode digit_mode,\
                              int precision, int sign, TrimMode trim,\
                              int pad_left, int exp_digits);

make_dragon4_typedecl(Half, npy_half)
make_dragon4_typedecl(Float, npy_float)
make_dragon4_typedecl(Double, npy_double)
make_dragon4_typedecl(LongDouble, npy_longdouble)

#undef make_dragon4_typedecl

PyObject *
Dragon4_Positional(PyObject *obj, DigitMode digit_mode, CutoffMode cutoff_mode,
                   int precision, int sign, TrimMode trim, int pad_left,
                   int pad_right);

PyObject *
Dragon4_Scientific(PyObject *obj, DigitMode digit_mode, int precision,
                   int sign, TrimMode trim, int pad_left, int exp_digits);

#endif


text:
'use strict';

var url = require('url');
var restifyClients = require('restify-clients');

var restify = require('../lib');

if (require.cache[__dirname + '/lib/helper.js']) {
    delete require.cache[__dirname + '/lib/helper.js'];
}
var helper = require('./lib/helper.js');

///--- Globals

var after = helper.after;
var before = helper.before;
var test = helper.test;

var PORT = process.env.UNIT_TEST_PORT || 0;
var CLIENT;
var SERVER;

var LOCALHOST;
var SLOCALHOST;

before(function (cb) {
    try {
        SERVER = restify.createServer({
            dtrace: helper.dtrace,
            log: helper.getLog('server'),
            version: ['2.0.0', '0.5.4', '1.4.3']
        });
        SERVER.use(restify.queryParser());
        SERVER.listen(PORT, '127.0.0.1', function () {
            PORT = SERVER.address().port;
            CLIENT = restifyClients.createJsonClient({
                url: 'http://127.0.0.1:' + PORT,
                dtrace: helper.dtrace,
                retry: false
            });
            LOCALHOST = 'http://' + '127.0.0.1:' + PORT;
            SLOCALHOST = 'https://' + '127.0.0.1:' + PORT;

            cb();
        });
    } catch (e) {
        console.error(e.stack);
        process.exit(1);
    }
});

after(function (cb) {
    try {
        CLIENT.close();
        SERVER.close(function () {
            CLIENT = null;
            SERVER = null;
            cb();
        });
    } catch (e) {
        console.error(e.stack);
        process.exit(1);
    }
});

// helper for joining array into strings
function join() {
    var args = [].slice.call(arguments, 0);
    return (args.join(''));
}

test('redirect to new string url as-is', function (t) {
    SERVER.get('/1', function (req, res, next) {
        res.redirect('www.foo.com', next);
    });

    CLIENT.get(join(LOCALHOST, '/1'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, 'www.foo.com');
        t.end();
    });
});

test('redirect to new relative string url as-is', function (t) {
    SERVER.get('/20', function (req, res, next) {
        res.redirect('/1', next);
    });

    CLIENT.get(join(LOCALHOST, '/20'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, '/1');
        t.end();
    });
});

test('redirect to current url (reload)', function (t) {
    SERVER.get('/2', function (req, res, next) {
        res.redirect({
            reload: true
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/2'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(LOCALHOST, '/2'));
        t.end();
    });
});

test('redirect to current url from http -> https', function (t) {
    SERVER.get('/3', function (req, res, next) {
        res.redirect({
            secure: true
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/3'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(SLOCALHOST, '/3'));
        t.end();
    });
});

test('redirect to current url from https -> http', function (t) {
    SERVER.get('/3', function (req, res, next) {
        res.redirect({
            reload: true,
            secure: false
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/3'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(LOCALHOST, '/3'));
        t.end();
    });
});

test('redirect by changing path', function (t) {
    SERVER.get('/4', function (req, res, next) {
        res.redirect({
            pathname: '1'
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/4'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(LOCALHOST, '/1'));
        t.end();
    });
});

test('redirect should add query params', function (t) {
    SERVER.get('/5', function (req, res, next) {
        res.redirect({
            query: {
                a: 1
            }
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/5'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(LOCALHOST, '/5?a=1'));
        t.end();
    });
});

test('redirect should extend existing query params', function (t) {
    SERVER.get('/6', function (req, res, next) {
        res.redirect({
            query: {
                b: 2
            }
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/6?a=1'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        var parsedUrl = url.parse(res.headers.location, true);
        t.deepEqual(parsedUrl.query, {
            a: 1,
            b: 2
        });
        t.equal(parsedUrl.query.b, 2);
        t.equal(parsedUrl.pathname, '/6');

        // t.equal(res.headers.location, join(LOCALHOST, '/6?a=1&b=2'));
        t.end();
    });
});

test('redirect should stomp over existing query params', function (t) {
    SERVER.get('/7', function (req, res, next) {
        res.redirect({
            overrideQuery: true,
            query: {
                b: 2
            }
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/7?a=1'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, join(LOCALHOST, '/7?b=2'));
        t.end();
    });
});

test('redirect with 301 status code', function (t) {
    SERVER.get('/8', function (req, res, next) {
        res.redirect({
            permanent: true
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/8'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 301);
        t.equal(res.headers.location, join(LOCALHOST, '/8'));
        t.end();
    });
});

test('redirect with 301 status code ising string url', function (t) {
    SERVER.get('/30', function (req, res, next) {
        res.redirect(301, '/foo', next);
    });

    CLIENT.get(join(LOCALHOST, '/30'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 301);
        t.equal(res.headers.location, '/foo');
        t.end();
    });
});

test('redirect using options.url', function (t) {
    SERVER.get('/8', function (req, res, next) {
        res.redirect({
            hostname: 'www.foo.com',
            pathname: '/8',
            query: {
                a: 1
            }
        }, next);
    });

    CLIENT.get(join(LOCALHOST, '/8'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, 'http://www.foo.com/8?a=1');
        t.end();
    });
});

// jscs:disable maximumLineLength
test('redirect should cause InternalError when invoked without next', function (t) {

    SERVER.get('/9', function (req, res, next) {
        res.redirect();
    });

    CLIENT.get(join(LOCALHOST, '/9'), function (err, _, res) {
        t.equal(res.statusCode, 500);

        // json parse the response
        var msg = JSON.parse(res.body);
        t.equal(msg.code, 'Internal');
        t.end();
    });
});

// jscs:enable maximumLineLength

test('redirect should call next with false to stop ' +
      'handler stack execution', function (t) {
    var wasRun = false;

    function A(req, res, next) {
        req.a = 1;
        next();
    }
    function B(req, res, next) {
        req.b = 2;
        wasRun = true;
        next();
    }
    function redirect(req, res, next) {
        res.redirect('/10', next);
    }

    SERVER.get('/10', [A, redirect, B]);

    CLIENT.get(join(LOCALHOST, '/10'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, '/10');

        // handler B should not be executed
        t.equal(wasRun, false);
        t.end();
    });
});

test('redirect should emit a redirect event', function (t) {
    var wasEmitted = false;
    var redirectLocation;

    function preRedirectHandler(req, res, next) {
        res.on('redirect', function (payload) {
            wasEmitted = true;
            redirectLocation = payload;
        });
        console.log('about to call next');
        next();
    }
    function redirect(req, res, next) {
        res.redirect('/10', next);
    }

    SERVER.get('/10', [preRedirectHandler, redirect]);

    CLIENT.get(join(LOCALHOST, '/10'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);
        t.equal(res.headers.location, '/10');

        // event 'redirect' should have been emitted
        t.equal(wasEmitted, true);
        t.equal(redirectLocation, '/10');
        t.end();
    });
});

test('writeHead should emit a header event', function (t) {
    var wasEmitted = false;
    var payloadPlaceholder;

    // writeHead is called on each request
    function handler(req, res, next) {
        res.on('header', function (payload) {
            wasEmitted = true;
            payloadPlaceholder = payload;
        });
        res.send(302);
        next();
    }

    SERVER.get('/10', [handler]);

    CLIENT.get(join(LOCALHOST, '/10'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 302);

        // event 'header' should have been emitted
        t.equal(wasEmitted, true);
        t.equal(payloadPlaceholder, undefined);
        t.end();
    });
});

test('should fail to set header due to missing formatter', function (t) {

    // when a formatter is not set up for a specific content-type, restify will
    // default to octet-stream.

    SERVER.get('/11', function handle(req, res, next) {
        res.header('content-type', 'application/hal+json');
        res.send(200, JSON.stringify({ hello: 'world' }));
        return next();
    });

    CLIENT.get(join(LOCALHOST, '/11'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        t.equal(res.headers['content-type'], 'application/octet-stream');
        t.end();
    });
});

test('should not fail to send null as body', function (t) {

    SERVER.get('/12', function handle(req, res, next) {
        res.send(200, null);
        return next();
    });

    CLIENT.get(join(LOCALHOST, '/12'), function (err, _, res) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        t.end();
    });
});


text:
layout: article
title: "Integração Contínua com Jenkins"
categories: materiais
author: sakurai
date: 2011-03-22 16:00:00
tags: [jenkins, maven, subversion, integração]
published: true
excerpt: Exemplo de uso de repositório de fontes com Subversion, integração continua com Jenkins CI e analise de código com o Sonar.
comments: true
image:
  teaser: 2011-03-22-teaser-ic-jenkins-maven-subversion-sonar.png
ads: true
---

Neste exemplo vamos criar uma aplicação Java bem simples com apenas uma classe e usando o JUnit para testar esta classe, iremos versionar o projeto no Subversion para controlar as alterações, depois vamos configurar o Jenkins CI para ele gerar o build da aplicação a partir do repositório do Subversion, feito isso adicionamos o plugin do Sonar que irá verificar a qualidade do código-fonte.

## Integração Contínua

"Integração Contínua é uma pratica de desenvolvimento de software onde os membros de um time integram seu trabalho frequentemente, geralmente cada pessoa integra pelo menos diariamente – podendo haver múltiplas integrações por dia. Cada integração é verificada por um build automatizado (incluindo testes) para detectar erros de integração o mais rápido possível. Muitos times acham que essa abordagem leva a uma significante redução nos problemas de integração e permite que um time desenvolva software coeso mais rapidamente." [Martin Fowler]

### Ciclo do desenvolvimento com Integração Continua [FOWLER, M.]

* Fazer uma cópia local do repositório (checkout).
* Desenvolver sua tarefa com testes unitários.
* Montar uma build do projeto e passar por todos os testes.
* Atualizar a cópia local com a versão do repositório.
* Montar uma build do projeto e passar por todos os testes (se algo de errado nos testes é preciso corrigir até que a versão esteja sincronizada com a versão principal).
* Guardar suas alterações no repositório (commit).
* Montar um build a partir de uma maquina de integração (garantindo que todas as novas alterações foram submetidas corretamente) de preferencia de forma automática com algum programa de integração continua.

## Criando um repositório no Subversion

Download do Subversion em [http://subversion.apache.org](http://subversion.apache.org)

O Subversion é um sistema de controle de versão centralizado, usando como base um repositório onde todos os códigos-fontes (na verdade você pode guardar tudo que for importante) são versionados gerando históricos de alterações,

Crie um novo repositório:

{% highlight xml %}
 $ svnadmin create /caminho/do/repositório
{% endhighlight %}

Exemplo:

{% highlight xml %}
 $ svnadmin create /Users/sakurai/Desktop/IC/Repositorio
{% endhighlight %}

## Criando um projeto Java no NetBeans com Maven

Download do NetBeans em [http://netbeans.org/](http://netbeans.org/)

> Neste exemplo estou usando o NetBeans, mas se preferir pode fazer o projeto em outra IDE ou manualmente.

Exemplo de Projeto Java:

Crie uma classe que retorna o ano do veículo, dado o chassi e a posição que informa o ano do veículo.

### Criando o projeto Java com Maven

No NetBeans crie um novo **Projeto Maven - Aplicativo Java**.

#### pom.xml

Alterei o pom.xml para informar a versão 4.8.2 do JUnit que estou usando e informar onde fica no build as classes .java e .class da aplicação:

{% highlight xml %}
<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>tdd</groupId>
  <artifactId>Chassi</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Chassi</name>
  <url>http://www.universidadejava.com.br</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>
      ${project.basedir}/src/main/java
    </sourceDirectory>
    <testSourceDirectory>
      ${project.basedir}/src/test/java
    </testSourceDirectory>
    <resources>
      <resource>
        <directory>
          ${project.basedir}/src/main/java
        </directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>
          ${project.basedir}/src/test/java
        </directory>
      </testResource>
    </testResources>
  </build>
</project>
{% endhighlight %}

Crie uma classe de teste:

> O ideal é desenvolver seguindo as práticas do TDD.

{% highlight java %}
package br.universidadejava.ic.util;

import static org.junit.Assert.*;
import org.junit.Test;

public class ValidarChassiTest {
    ValidarChassi util = new ValidarChassi();

    @Test
    public void validarAnoANoChassi() {
        assertEquals(2010, util.validar("9BP17164GA000001", 10));
    }

    @Test
    public void validarAno9NoChassi() {
        assertEquals(2009, util.validar("9BP17164G9000002", 10));
    }

    @Test
    public void validarAnoBNoChassi() {
        assertEquals(2011, util.validar("9BP17164GB000003", 10));
    }

    @Test
    public void validarAnoAMinusculoNoChassi() {
        assertEquals(2010, util.validar("9bp17164ga000001", 10));
    }

    @Test(expected=IllegalArgumentException.class)
    public void validarAnoIncorreto() {
        assertEquals(2020, util.validar("9bp17164gz000004", 10));
    }
}
{% endhighlight %}

Crie a classe com a implementação:

{% highlight java %}
package br.universidadejava.ic.util;

public class ValidarChassi {
    public int validar(String chassi, int posicao) {
        if(chassi.charAt(posicao - 1) == '9') {
            return 2009;
        } else if(chassi.toUpperCase().charAt(posicao - 1) == 'A') {
          return 2010;
        } else if(chassi.toUpperCase().charAt(posicao - 1) == 'B') {
          return 2011;
        }

        throw new IllegalArgumentException("Valores incorretos!!!");
    }
}
{% endhighlight %}

> Se você acha que este código está bem escrito, vai gostar de ver a opinião do Sonar.

### Importe o projeto Java do Netbeans para o repositório do SubVersion

Com o botão direito em cima do projeto selecione **Versionamento -> Importar no repositório Subversion…**

Na tela do Repositório do Subversion informe a URL do repositório.

Exemplo de URL:

{% highlight xml %}
file:///Users/sakurai/Desktop/IC/Repositorio
{% endhighlight %}

Clique em **Avançar**.

Especifique uma mensagem.

Clique em **Finalizar**.

### Iniciar o Jenkins CI

Download do Jenkins CI em [http://jenkins-ci.org](http://jenkins-ci.org)

O Jenkins CI é uma aplicação de Integração Continua, nela podemos

#### Iniciar o Jenkins:

{% highlight java %}
java -jar jenkins.war
{% endhighlight %}

Para acessar o Jenkins CI abra a URL: [http://localhost:8080/](http://localhost:8080/)

#### Configurando o Jenkins CI

No menu Gerenciar Jenkins entre em Configurar sistema:

Informe o local de instalação do JDK.

Informe a versão do Maven.

Informe o local do repositório do Subversion.

Criar uma tarefa no Jenkins CI:

* Informe o nome da tarefa, selecione Construir com Maven 2/3 e clique em OK
* Informar o caminho do repositório.
* Informar o local do pom.xml dentro do projeto.

### Instalando o Sonar

Download do Sonar [http://www.sonarsource.org](http://www.sonarsource.org)
Descompactar o arquivo sonar-x.x.zip.
Escolhar dentro do diretório bin a versão de SO.

Iniciar o Sonar:

{% highlight java %}
$ ./sonar.sh start
{% endhighlight %}

Para acessar o Sonar abra a URL: [http://localhost:9000](http://localhost:9000)

### Adicionar o plugin do Sonar no Jenkins CI

No menu Gerenciar Jenkins entre em Gerenciar Plugins selecione na categoria Disponíveis o plugin do Sonar e clique no botão instalar.

No menu Gerenciar Jenkins:

Configurar sistema informe que irá usar o Sonar.

Na tarefa entre no menu Configurar informe que está usando o Sonar:

Entre na tarefa e clique em Construir Agora

Durante a construção do Projeto é possível acompanhar o andamento através da Saída do Console.

Após terminar a construção, podemos visualizar:

* Se aconteceu algum erro ao montar o build.
* Verificar as mudanças no código.
* Se executou todos os testes.

* Podemos acessar o Sonar e visualizar a qualidade do código.

Note que temos apenas 13 linhas de código e o Sonar já registrou 4 violações de categoria Minor (menor).

Se clicar em cima do item Minor o Sonar vai detalhar as violações e as classes que elas ocorrem:

## Referências

* [FOWLER, M.] **Continuous Integration** - Disponível em: http://martinfowler.com/articles/continuousIntegration.html
* [FOWLER, M. 04] **Refatoração: Aperfeiçoando o Projeto de Código Existente.** Porto Alegre: Bookman, 2004. 366 p.
* [FREEMAN, S.; PRYCE, N.] **Growing Object-Oriented Software, Guided By Tests.** Boston: Person, 2010. 358 p.
* [JENKINS CI] **Jenkins Continuous Integration** - Disponível em: http://jenkins-ci.org/
* [SONAR] **Sonar** - Disponível em: http://www.sonarsource.org/
* [SUBVERSION] **Subversion** - Disponível em: http://subversion.apache.org/


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>osclient2.keystone.v2.user.Manager</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package osclient2 ::
        Package keystone ::
        Package v2 ::
        Module user ::
        Class Manager

[hide private]

[frames] | no frames]

Class Manager

source code

  object --+
           |
base.Manager --+
               |
              Manager

manager class for users on Identity V2 API

        Nested Classes
        [hide private]

        resource_class

      resource class for users on Identity V2 API

        Instance Methods
        [hide private]

      osclient2.keystone.v2.user.Resource

          create(self,
        name=None,
        username=None,
        password=None,
        email=None,
        project=None,
        is_enabled=None)

      Register a user

            source code

Inherited from base.Manager:
      __init__,
      find,
      find_one,
      get,
      get_empty,
      list

Inherited from base.Manager (private):
      _attr2json,
      _find_gen,
      _json2attr,
      _no_such_api

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Class Variables
        [hide private]

        service_type = 'identity'

        _attr_mapping = [('id', 'id', <osclient2.mapper.NoopClass obje...

        _json_resource_key = 'user'

        _json_resources_key = 'users'

        _url_resource_path = '/users'

Inherited from base.Manager (private):
      _has_detail,
      _has_extra_attr,
      _hidden_methods,
      _id_attr,
      _update_method,
      _url_resource_list_path

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

create(self,
        name=None,
        username=None,
        password=None,
        email=None,
        project=None,
        is_enabled=None)

  	source code

Register a user

Parameters:

name (str) - User account

username (str) - Full name

password (str) - Password

email (str) - E-mail address

project (osclient2.keystone.v2.project.Resource) - Project

is_enabled (str) - Whether the user is enabled or not

Returns: osclient2.keystone.v2.user.Resource

Created user

Overrides:
        base.Manager.create

        Class Variable Details
        [hide private]

_attr_mapping

Value:

[('id', 'id', mapper.Noop), ('name', 'name', mapper.Noop), ('username'
, 'username', mapper.Noop), ('password', 'password', mapper.Noop), ('e
mail', 'email', mapper.Noop), ('project', 'project_id', mapper.Resourc
e('keystone.project')), ('is_enabled', 'enabled', mapper.Noop),]

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Mon Feb 20 20:49:21 2017

      http://epydoc.sourceforge.net


text:
from m5.objects import *

# Simple ALU Instructions have a latency of 1
class O3_ARM_v7a_Simple_Int(FUDesc):
    opList = [ OpDesc(opClass='IntAlu', opLat=1) ]
    count = 2

# Complex ALU instructions have a variable latencies
class O3_ARM_v7a_Complex_Int(FUDesc):
    opList = [ OpDesc(opClass='IntMult', opLat=3, pipelined=True),
               OpDesc(opClass='IntDiv', opLat=12, pipelined=False),
               OpDesc(opClass='IprAccess', opLat=3, pipelined=True) ]
    count = 1

# Floating point and SIMD instructions
class O3_ARM_v7a_FP(FUDesc):
    opList = [ OpDesc(opClass='SimdAdd', opLat=4),
               OpDesc(opClass='SimdAddAcc', opLat=4),
               OpDesc(opClass='SimdAlu', opLat=4),
               OpDesc(opClass='SimdCmp', opLat=4),
               OpDesc(opClass='SimdCvt', opLat=3),
               OpDesc(opClass='SimdMisc', opLat=3),
               OpDesc(opClass='SimdMult',opLat=5),
               OpDesc(opClass='SimdMultAcc',opLat=5),
               OpDesc(opClass='SimdShift',opLat=3),
               OpDesc(opClass='SimdShiftAcc', opLat=3),
               OpDesc(opClass='SimdSqrt', opLat=9),
               OpDesc(opClass='SimdFloatAdd',opLat=5),
               OpDesc(opClass='SimdFloatAlu',opLat=5),
               OpDesc(opClass='SimdFloatCmp', opLat=3),
               OpDesc(opClass='SimdFloatCvt', opLat=3),
               OpDesc(opClass='SimdFloatDiv', opLat=3),
               OpDesc(opClass='SimdFloatMisc', opLat=3),
               OpDesc(opClass='SimdFloatMult', opLat=3),
               OpDesc(opClass='SimdFloatMultAcc',opLat=1),
               OpDesc(opClass='SimdFloatSqrt', opLat=9),
               OpDesc(opClass='FloatAdd', opLat=5),
               OpDesc(opClass='FloatCmp', opLat=5),
               OpDesc(opClass='FloatCvt', opLat=5),
               OpDesc(opClass='FloatDiv', opLat=9, pipelined=False),
               OpDesc(opClass='FloatSqrt', opLat=33, pipelined=False),
               OpDesc(opClass='FloatMult', opLat=4) ]
    count = 2

# Load/Store Units
class O3_ARM_v7a_Load(FUDesc):
    opList = [ OpDesc(opClass='MemRead',opLat=2) ]
    count = 1

class O3_ARM_v7a_Store(FUDesc):
    opList = [OpDesc(opClass='MemWrite',opLat=2) ]
    count = 1

# Functional Units for this CPU
class O3_ARM_v7a_FUP(FUPool):
    FUList = [O3_ARM_v7a_Simple_Int(), O3_ARM_v7a_Complex_Int(),
              O3_ARM_v7a_Load(), O3_ARM_v7a_Store(), O3_ARM_v7a_FP()]

# Bi-Mode Branch Predictor
class O3_ARM_v7a_BP(BiModeBP):
    globalPredictorSize = 8192
    globalCtrBits = 2
    choicePredictorSize = 8192
    choiceCtrBits = 2
    BTBEntries = 2048
    BTBTagSize = 18
    RASSize = 16
    instShiftAmt = 2

class O3_ARM_v7a_3(DerivO3CPU):
    LQEntries = 16
    SQEntries = 16
    LSQDepCheckShift = 0
    LFSTSize = 1024
    SSITSize = 1024
    decodeToFetchDelay = 1
    renameToFetchDelay = 1
    iewToFetchDelay = 1
    commitToFetchDelay = 1
    renameToDecodeDelay = 1
    iewToDecodeDelay = 1
    commitToDecodeDelay = 1
    iewToRenameDelay = 1
    commitToRenameDelay = 1
    commitToIEWDelay = 1
    fetchWidth = 3
    fetchBufferSize = 16
    fetchToDecodeDelay = 3
    decodeWidth = 3
    decodeToRenameDelay = 2
    renameWidth = 3
    renameToIEWDelay = 1
    issueToExecuteDelay = 1
    dispatchWidth = 6
    issueWidth = 8
    wbWidth = 8
    fuPool = O3_ARM_v7a_FUP()
    iewToCommitDelay = 1
    renameToROBDelay = 1
    commitWidth = 8
    squashWidth = 8
    trapLatency = 13
    backComSize = 5
    forwardComSize = 5
    numPhysIntRegs = 128
    numPhysFloatRegs = 192
    numIQEntries = 32
    numROBEntries = 40

    switched_out = False
    branchPred = O3_ARM_v7a_BP()

# Instruction Cache
class O3_ARM_v7a_ICache(BaseCache):
    hit_latency = 1
    response_latency = 1
    mshrs = 2
    tgts_per_mshr = 8
    size = '32kB'
    assoc = 2
    is_top_level = True
    forward_snoops = False

# Data Cache
class O3_ARM_v7a_DCache(BaseCache):
    hit_latency = 2
    response_latency = 2
    mshrs = 6
    tgts_per_mshr = 8
    size = '32kB'
    assoc = 2
    write_buffers = 16
    is_top_level = True

# TLB Cache
# Use a cache as a L2 TLB
class O3_ARM_v7aWalkCache(BaseCache):
    hit_latency = 4
    response_latency = 4
    mshrs = 6
    tgts_per_mshr = 8
    size = '1kB'
    assoc = 8
    write_buffers = 16
    is_top_level = True
    forward_snoops = False

# L2 Cache
class O3_ARM_v7aL2(BaseCache):
    hit_latency = 12
    response_latency = 12
    mshrs = 16
    tgts_per_mshr = 8
    size = '1MB'
    assoc = 16
    write_buffers = 8
    prefetch_on_access = True
    # Simple stride prefetcher
    prefetcher = StridePrefetcher(degree=8, latency = 1)
    tags = RandomRepl()


text:
#ifndef __SSP_SPI_H__
#define __SSP_SPI_H__

#include "ssp.h"

/* ssp_msg options bit*/
#define SSP_SPI		0       /* read write mask */
#define SSP_RETURN	2       /* write and read option */
#define SSP_GYRO_DPS	3       /* gyro dps mask */
#define SSP_INDEX	3       /* data index mask */
#define SSP_SPI_MASK	(3 << SSP_SPI)  /* read write mask */

struct ssp_data;
struct ssp_msg;

int ssp_spi_async(struct ssp_data *data, struct ssp_msg *msg);
int ssp_spi_sync(struct ssp_data *data, struct ssp_msg *msg, int timeout);
int select_irq_msg(struct ssp_data *data);
void clean_pending_list(struct ssp_data *data);
int ssp_send_cmd(struct ssp_data *data, char command, int arg);
int send_instruction(struct ssp_data *data, u8 uInst,
	u8 uSensorType, u8 *uSendBuf, u16 uLength);
int send_instruction_sync(struct ssp_data *data, u8 uInst,
	u8 uSensorType, u8 *uSendBuf, u16 uLength);
int flush(struct ssp_data *data, u8 uSensorType);
int get_batch_count(struct ssp_data *data, u8 uSensorType);
int get_chipid(struct ssp_data *data);
int set_sensor_position(struct ssp_data *data);
void set_proximity_threshold(struct ssp_data *data,
	unsigned int uData1, unsigned int uData2);
#ifdef CONFIG_SENSORS_MULTIPLE_GLASS_TYPE
int set_glass_type(struct ssp_data *);
#endif
void set_proximity_barcode_enable(struct ssp_data *data, bool bEnable);
void set_gesture_current(struct ssp_data *data, unsigned char uData1);
int get_6axis_type(struct ssp_data *data);
int set_6axis_dot(struct ssp_data *data);
int set_hall_threshold(struct ssp_data *data);
uint64_t get_sensor_scanning_info(struct ssp_data *data);
unsigned int get_firmware_rev(struct ssp_data *data);
int set_big_data_start(struct ssp_data *data, u8 type, u32 length);
int set_time(struct ssp_data *data);
int get_time(struct ssp_data *data);
void set_gyro_cal_lib_enable(struct ssp_data *, bool);
#endif


text:
<?php

class aPageSettingsForm extends BaseaPageSettingsForm
{
  // You can override me with a project-level version that also extends BaseaPageSettingsForm
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type (jackson-databind 2.14.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type

Packages that use AnnotationIntrospector.ReferenceProperty.Type

Package
Description

com.fasterxml.jackson.databind

Basic data binding (mapping) functionality that
allows for reading JSON content into Java Objects (POJOs)
and JSON Trees (JsonNode), as well as
writing Java Objects and trees as JSON.

Uses of AnnotationIntrospector.ReferenceProperty.Type in com.fasterxml.jackson.databind

Methods in com.fasterxml.jackson.databind that return AnnotationIntrospector.ReferenceProperty.Type

Modifier and Type
Method and Description

AnnotationIntrospector.ReferenceProperty.Type
AnnotationIntrospector.ReferenceProperty.getType()

static AnnotationIntrospector.ReferenceProperty.Type
AnnotationIntrospector.ReferenceProperty.Type.valueOf(String name)

Returns the enum constant of this type with the specified name.

static AnnotationIntrospector.ReferenceProperty.Type[]
AnnotationIntrospector.ReferenceProperty.Type.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Constructors in com.fasterxml.jackson.databind with parameters of type AnnotationIntrospector.ReferenceProperty.Type

Constructor and Description

ReferenceProperty(AnnotationIntrospector.ReferenceProperty.Type t,
                 String n)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2008–2022 FasterXML. All rights reserved.


text:
from __future__ import unicode_literals

from django.db import migrations, models
import fb_github.models

class Migration(migrations.Migration):

    dependencies = [
        ('fb_github', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='repository',
            name='email_slug',
            field=models.SlugField(default=fb_github.models.email_slug_default, unique=True),
        ),
    ]


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SF.Sys.Services.Management.Models;
using SF.Sys.Comments;
using SF.Sys.Reflection;
using SF.Sys.Entities;
using SF.Sys.Collections.Generic;
using SF.Sys.Linq;

namespace SF.Sys.Services.Management
{
	/// <summary>
	/// ĬÈÏ·þÎñ¶¨Òå¹ÜÀí
	/// </summary>
	public class ServiceDeclarationManager :
		IServiceDeclarationManager
	{
		public Dictionary<string,ServiceDeclaration> Items { get; }

		public long? ServiceInstanceId => null;

		public ServiceDeclarationManager(IServiceMetadata ServiceMetadata)
		{
			this.Items = (from pair in ServiceMetadata.ServicesById
						  let type=pair.Value.ServiceType
						  let comment = type.Comment()
						  select new ServiceDeclaration
						  {
							  Id = pair.Key,
							  Type=type.GetFullName(),
							  Description = comment?.Summary,
							  Name = type.FriendlyName(),
							  Group = comment?.Group
						  }).ToDictionary(t=>t.Id);
		}

		public Task<ServiceDeclaration[]> BatchGetAsync(ObjectKey<string>[] Ids,string[] Properties)
		{
			return Task.FromResult(
				Ids
				.Select(id => Items.Get(id.Id))
				.Where(i => i != null)
				.ToArray()
				);
		}

		public Task<ServiceDeclaration> GetAsync(ObjectKey<string> Id,string[] Fields=null)
		{
			return Task.FromResult(Items.Get(Id.Id));
		}

		public Task<QueryResult<ServiceDeclaration>> QueryAsync(ServiceDeclarationQueryArgument Arg)
		{
			var q = Items.Values.AsQueryable();
			if (Arg.Id!=null)
				q = q.Where(i => i.Id == Arg.Id.Id);
			else
				q = q.Filter(Arg.Name, i => i.Name)
					.Filter(Arg.Group, i => i.Group)
					;
			return Task.FromResult(
				q.ToQueryResult(
					qi => qi,
					r => r,
					PagingQueryBuilder<ServiceDeclaration>.Simple("name",e=>e.Name),
					Arg.Paging
					)
					);
		}

		public async Task<QueryResult<ObjectKey<string>>> QueryIdentsAsync(ServiceDeclarationQueryArgument Arg)
		{
			var re = await QueryAsync(Arg);
			return re.Select(i =>new ObjectKey<string> { Id = i.Id });
		}
	}
}


text:
var game = this.game || {};

(function(module){
    // =================================================================
    // VARIABLES
    // =================================================================

    // Constants
    var FRAME_RATE = 60;

    var STAGE_WIDTH = 1366;
    var STAGE_HEIGHT = 768;
    var STAGE_PADDING = 50;

    var PADDLE_WIDTH = 120;
    var PADDLE_HEIGHT = 20;
    var PADDLE_SPEED = STAGE_WIDTH / 2;

    var BALL_SIZE = 10;
    var BALL_SPEED = STAGE_HEIGHT / 2;

    var BLOCK_WIDTH = 100;
    var BLOCK_HEIGHT = 25;
    var BLOCK_PADDING = 5;

    var SCORE_INCREMENT = 100;

    // Game Objects
    var stage = {};
    var paddle = {};
    var ball = {};
    var blocks = [];

    // Key States
    var leftDown = false;
    var rightDown = false;

    // Mouse States
    var dragging = false;
    var prevMouseX = 0;
    var currMouseX = 0;

    // Game State
    var STATE = { START: 0, PLAYING: 1, GAME_OVER: 2 };
    var currState = STATE.START;

    // Score
    var score = 0;
    var scoreText = {};

    // Timer
    var timerId = 0;
    var timerInterval = 10000;

    // Buttons
    var playButton = {};
    var retryButton = {};

    // =================================================================
    // INITIALIZATION
    // =================================================================

    module.init = function() {
        stage = new createjs.Stage("js-canvas");

        playButton = new createjs.Text("play", "bold 250px Arial", "white");
        playButton.x = STAGE_WIDTH / 2 - 275;
        playButton.y = STAGE_HEIGHT / 2 - 125;
        playButton.addEventListener("click", function() {
            createjs.Tween.get(playButton).to({y: 1000}, 1000, createjs.Ease.quadInOut).call(startGame);
        });
        stage.addChild(playButton);

        initPaddle();
        initScore();
        initEvents();
    }

    function initPaddle() {
        paddle = new createjs.Shape();
        paddle.graphics.beginFill("white").drawRect(0, 0, PADDLE_WIDTH, PADDLE_HEIGHT);
        paddle.x = STAGE_WIDTH/2 - PADDLE_WIDTH/2;
        paddle.y = STAGE_HEIGHT - PADDLE_HEIGHT;
        stage.addChild(paddle);
    }

    function initBall() {
        ball = new createjs.Shape();
        ball.graphics.beginFill("white").drawRect(0, 0, BALL_SIZE * 2, BALL_SIZE * 2);
        ball.regX = BALL_SIZE;
        ball.regY = BALL_SIZE;
        ball.x = paddle.x + PADDLE_WIDTH/2;
        ball.y = paddle.y - BALL_SIZE;
        var theta = -(Math.random() * (Math.PI/2) + (Math.PI/4));
        ball.vx = Math.cos(theta) * BALL_SPEED;
        ball.vy = Math.sin(theta) * BALL_SPEED;
        stage.addChild(ball);
    }

    function initBlocks() {
        var numRows = Math.floor((STAGE_HEIGHT * (2/3) - STAGE_PADDING * 2) / (BLOCK_HEIGHT + BLOCK_PADDING));
        for (var row = 0; row < numRows; row++) {
            addRow();
        }
    }

    function initScore() {
        scoreText = new createjs.Text("0", "bold 250px Arial", "white");
        scoreText.x = STAGE_PADDING;
        scoreText.y = STAGE_HEIGHT - 250 - STAGE_PADDING;
        scoreText.alpha = 0;
        stage.addChild(scoreText);
    }

    function initEvents() {
        window.onkeydown = keyDown;
        window.onkeyup = keyUp;
        window.onmousedown = mouseDown;
        window.onmouseup = mouseUp;
        createjs.Ticker.setFPS(FRAME_RATE);
        createjs.Ticker.useRAF = true;
        createjs.Ticker.addEventListener("tick", tick);
    }

    // =================================================================
    // EVENTS
    // =================================================================

    function keyDown(e) {
        var key = e.keyCode ? e.keyCode : e.which;

        if (key === 37 || key === 65)
            leftDown = true;
        else if (key === 39 || key === 68)
            rightDown = true;
    }

    function keyUp(e) {
        var key = e.keyCode ? e.keyCode : e.which;

        if (key === 37 || key === 65)
            leftDown = false;
        else if (key === 39 || key === 68)
            rightDown = false;
    }

    function mouseDown(e) {
        if (stage.mouseX > STAGE_HEIGHT * .75) {
            dragging = true;
            prevMouseX = currMouseX = stage.mouseX;
        }
        else {
            dragging = false;
        }
    }

    function mouseUp(e) {
        dragging = false;
    }

    function tick(e) {
        if (currState !== STATE.PLAYING) {
            stage.update();
            return;
        }
        // Convert the delta to seconds, which is much more useful
        var delta = e.delta/1000;

        // Run update routines
        moveBall(delta);
        movePaddle(delta);
        checkCollisions();

        // Update score
        scoreText.text = score;

        // Draw
        stage.update();
    }

    function timerEvent() {
        addRow();
    }

    function addRow() {
        // Shift exisiting rows down
        for (var i = 0; i < blocks.length; i++) {
            blocks[i].y += BLOCK_HEIGHT + BLOCK_PADDING;
        }

        // Get number of blocks
        var numCols = Math.floor((STAGE_WIDTH - STAGE_PADDING * 2) / (BLOCK_WIDTH + BLOCK_PADDING));
        var leftMargin = (STAGE_WIDTH - (numCols * (BLOCK_WIDTH + BLOCK_PADDING))) / 2;

        // Draw a row of blocks
        for (var col = 0; col < numCols; col++) {
            var x = col * (BLOCK_WIDTH + BLOCK_PADDING) + BLOCK_PADDING + leftMargin;
            var y = 0;
            drawBlock(x, y);
        }

        // Check to see if one of the blocks spills over
        for (var i = 0; i < blocks.length; i++) {
            if (blocks[i].y + BLOCK_HEIGHT > STAGE_HEIGHT)
                gameOver();
        }
    }

    // =================================================================
    // HELPERS
    // =================================================================

    function drawBlock(x, y) {
        var block = new createjs.Shape();
        block.graphics.beginFill("white").drawRect(0, 0, BLOCK_WIDTH, BLOCK_HEIGHT);
        block.x = x;
        block.y = y;
        block.cache(0, 0, BLOCK_WIDTH, BLOCK_HEIGHT);
        stage.addChild(block);
        blocks.push(block);
    }

    function moveBall(delta) {
        ball.x += delta * ball.vx;
        ball.y += delta * ball.vy;
    }

    function movePaddle(delta) {
        if (!dragging) {
            if (leftDown)
                paddle.x -= delta * PADDLE_SPEED;
            if (rightDown)
                paddle.x += delta * PADDLE_SPEED;
        }
        else {
            currMouseX = stage.mouseX;
            paddle.x += currMouseX - prevMouseX;
            prevMouseX = currMouseX;
        }

        if (paddle.x < 0) {
            paddle.x = 0;
        }
        else if (paddle.x + PADDLE_WIDTH > STAGE_WIDTH) {
            paddle.x = STAGE_WIDTH - PADDLE_WIDTH;
        }

    }

    function checkCollisions() {
        // Check collision with paddle
        if (isBallTouchingBlock(paddle) && ball.y + BALL_SIZE > paddle.y) {
            bounceOffPaddle();
        }

        // Check collisions with blocks
        for (var i = blocks.length - 1; i >= 0; i--) {
            if (checkCollisionWithBlock(blocks[i])) {
                stage.removeChild(blocks[i]);
                score += SCORE_INCREMENT;
                blocks.splice(i, 1);
            }
        }

        // Keep in the bounds of the stage
        if (ball.x + BALL_SIZE > STAGE_WIDTH) {
            ball.x = STAGE_WIDTH - BALL_SIZE;
            ball.vx = ball.vx * -1;
        }
        if (ball.x - BALL_SIZE < 0) {
            ball.x = BALL_SIZE;
            ball.vx = ball.vx * -1;
        }
        if (ball.y - BALL_SIZE < 0) {
            ball.y = BALL_SIZE;
            ball.vy = ball.vy * -1;
        }
        if (ball.y + BALL_SIZE > STAGE_HEIGHT) {
            ball.y = STAGE_HEIGHT - BALL_SIZE;
            ball.vy = ball.vy * -1;
            gameOver();
        }
    }

    function checkCollisionWithBlock(block) {
        if (!isBallTouchingBlock(block))
            return false;

        if (ball.x < block.x) {
            ball.x = block.x - BALL_SIZE;
            ball.vx = ball.vx * -1;
        }
        else if (ball.x > (block.x + BLOCK_WIDTH)) {
            ball.x = block.x + BLOCK_WIDTH + BALL_SIZE;
            ball.vx = ball.vx * -1;
        }
        else if (ball.vy > 0) {
            ball.y = block.y - BALL_SIZE;
            ball.vy = ball.vy * -1;
        } else if (ball.vy <= 0) {
            ball.y = block.y + BLOCK_HEIGHT + BALL_SIZE;
            ball.vy = ball.vy *  -1;
        }

        return true;
    }

    function bounceOffPaddle() {
        // Reverse y direction
        ball.y = paddle.y - BALL_SIZE;
        ball.vy = ball.vy * -1;

        // Edit the x velocity depending on where we hit the paddle
        var thetas = [Math.PI * 0.8, Math.PI * .6, Math.PI * 0.5, Math.PI * 0.4, Math.PI * 0.2];
        var breaks = [PADDLE_WIDTH * 0.2, PADDLE_WIDTH* 0.4, PADDLE_WIDTH * 0.6, PADDLE_WIDTH * 0.8, PADDLE_WIDTH];
        var midpoint = paddle.x + PADDLE_WIDTH / 2;

        var i = 0;
        while (ball.x > paddle.x + breaks[i] && i < breaks.length)
            i++;
        if (i >= breaks.length) i = breaks.length - 1;

        var theta = -1 * thetas[i];
        ball.vx = Math.cos(theta) * BALL_SPEED;
    }

    function isBallTouchingBlock(block) {
        if (Math.abs(block.x - ball.x) > 200 || Math.abs(block.y - ball.y) > 100)
            return false;

        var tl = block.globalToLocal(ball.x - BALL_SIZE, ball.y - BALL_SIZE);
        var tr = block.globalToLocal(ball.x + BALL_SIZE, ball.y - BALL_SIZE);
        var bl = block.globalToLocal(ball.x - BALL_SIZE, ball.y + BALL_SIZE);
        var br = block.globalToLocal(ball.x + BALL_SIZE, ball.y + BALL_SIZE);

        if (block.hitTest(tl.x, tl.y))
            return true;
        else if (block.hitTest(tr.x, tr.y))
            return true;
        else if (block.hitTest(bl.x, bl.y))
            return true;
        else if (block.hitTest(br.x, br.y))
            return true;

        return false;
    }

    function startGame() {
        currState = STATE.PLAYING;
        scoreText.alpha = 0.25;
        score = 0;
        paddle.x = STAGE_WIDTH/2 - PADDLE_WIDTH/2;
        initBall();
        initBlocks();

        timerId = setInterval(timerEvent, timerInterval);

        stage.removeChild(playButton);
    }

    function restartGame() {
        createjs.Tween.get(retryButton).to({y: 1000}, 1000, createjs.Ease.quadInOut).call(function() {
            stage.removeChild(retryButton);
            startGame();
        });
    }

    function gameOver() {
        currState = STATE.GAME_OVER;

        // Stop timer
        clearInterval(timerId);

        // Remove blocks
        for (var i = 0; i < blocks.length; i++) {
            var block = blocks[i];
            (function(locked){
                createjs.Tween.get(locked).to({y: locked.y - 700}, 1000, createjs.Ease.quadInOut).call(function() {
                    stage.removeChild(locked);
                    blocks = [];
                });
            })(block);
        }

        retryButton = new createjs.Text("retry", "bold 250px Arial", "white");
        retryButton.x = STAGE_WIDTH / 2 - 300;
        retryButton.y = 1000;
        retryButton.addEventListener("click", restartGame);
        stage.addChild(retryButton);
        createjs.Tween.get(retryButton).to({y: STAGE_HEIGHT / 2 - 125}, 1000, createjs.Ease.quadInOut)

        // Remove ball
        stage.removeChild(ball);
    }

})(game);

window.onload = function() {
    game.init();
}


text:
//
// KeyboardUtil.cs
//
// Author:
//       Carlos Alberto Cortez <calberto.cortez@gmail.com>
//
// Copyright (c) 2011 Carlos Alberto Cortez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

using WpfKey = System.Windows.Input.Key;

namespace Xwt.WPFBackend
{
	using Keyboard = System.Windows.Input.Keyboard;

	public static class KeyboardUtil
	{
		public static ModifierKeys GetModifiers ()
		{
			var modifiers = ModifierKeys.None;
			var wpfModifiers = Keyboard.Modifiers;
			if ((wpfModifiers & System.Windows.Input.ModifierKeys.Alt) > 0)
				modifiers |= ModifierKeys.Alt;
			if ((wpfModifiers & System.Windows.Input.ModifierKeys.Control) > 0)
				modifiers |= ModifierKeys.Control;
			if ((wpfModifiers & System.Windows.Input.ModifierKeys.Shift) > 0)
				modifiers |= ModifierKeys.Shift;

			return modifiers;
		}

		const int D_Pos = (int)Key.K0 - (int)WpfKey.D0;
		const int U_Pos = (int)Key.A - (int)WpfKey.A;
		const int L_Pos = (int)Key.a - (int)WpfKey.A;
		const int N_Pos = (int)Key.NumPad0 - (int)WpfKey.NumPad0;
		const int F_Pos = (int)Key.F1 - (int)WpfKey.F1;

		// Missing key translations:
		// * NumPad keys other than 1-9
		// * SysReq, Undo, Redo, Menu, Find, Break, Equal
		// * ShiftLock, MetaLeft, MetaRight
		// * SuperLeft, SuperRight (likely not mappeable for Windows)
		// * Less, Greater, Question, At
		public static Key TranslateToXwtKey (WpfKey key)
		{
			// Letter keys
			if (key >= WpfKey.A && key <= WpfKey.Z) {
				bool upperCase = Keyboard.IsKeyToggled (WpfKey.CapsLock);
				if ((Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Shift) > 0)
					upperCase = !upperCase;
				return upperCase ? (Key)(key + U_Pos) : (Key)(key + L_Pos);
			}

			if (key >= WpfKey.D0 && key <= WpfKey.D9)
				return (Key)(key + D_Pos);

			// Numpad- keys
			if (key >= WpfKey.NumPad0 && key <= WpfKey.NumPad9)
				return (Key)(key + N_Pos);

			// F- keys
			if (key >= WpfKey.F1 && key <= WpfKey.F10)
				return (Key)(key + F_Pos);

			bool isShiftToggled = Keyboard.IsKeyToggled (WpfKey.LeftShift) || Keyboard.IsKeyToggled (WpfKey.RightShift);
			switch (key) {
				case WpfKey.Cancel: return Key.Cancel;
				case WpfKey.Back: return Key.BackSpace;
				case WpfKey.Tab: return Key.Tab;
				case WpfKey.LineFeed: return Key.LineFeed;
				case WpfKey.Clear: return Key.Clear;
				case WpfKey.Return: return Key.Return;
				case WpfKey.Pause: return Key.Pause;
				case WpfKey.CapsLock: return Key.CapsLock;
				case WpfKey.Space: return Key.Space;
				case WpfKey.Escape: return Key.Escape;
				case WpfKey.PageDown: return Key.PageDown;
				case WpfKey.PageUp: return Key.PageUp;
				case WpfKey.End: return Key.End;
				case WpfKey.Home: return Key.Home;
				case WpfKey.Left: return Key.Left;
				case WpfKey.Up: return Key.Up;
				case WpfKey.Right: return Key.Right;
				case WpfKey.Down: return Key.Down;
				case WpfKey.Select: return Key.Select;
				case WpfKey.Print: return Key.Print;
				case WpfKey.Execute: return Key.Execute;
				case WpfKey.Delete: return Key.Delete;
				case WpfKey.Help: return Key.Help;
				case WpfKey.Insert: return Key.Insert;
				case WpfKey.Scroll: return Key.ScrollLock;
				case WpfKey.NumLock: return Key.NumLock;
				case WpfKey.LeftShift: return Key.ShiftLeft;
				case WpfKey.RightShift: return Key.ShiftRight;
				case WpfKey.LeftCtrl: return Key.ControlLeft;
				case WpfKey.RightCtrl: return Key.ControlRight;
				case WpfKey.LeftAlt: return Key.AltLeft;
				case WpfKey.RightAlt: return Key.AltRight;
				case WpfKey.Multiply: return Key.Asterisk;
				case WpfKey.Add: return Key.Plus;
				case WpfKey.OemComma: return isShiftToggled ? Key.Semicolon : Key.Comma;
				case WpfKey.Subtract: return Key.Minus;
				case WpfKey.Divide: return Key.Slash;
				case WpfKey.OemPeriod: return isShiftToggled ? Key.Colon : Key.Period;
				case WpfKey.Oem5: return Key.Caret;
			}

			return (Key)0;
		}
	}
}