text:
import os, chardet
import unittest
from transifex.txcommon.tests.base import BaseTestCase
from transifex.languages.models import Language
from transifex.resources.models import *
from transifex.resources.formats.mozillaproperties import  MozillaPropertiesHandler

from transifex.addons.suggestions.models import Suggestion

class TestMozillaProperties(BaseTestCase):
    """Suite of tests for the propertiesfile lib."""

    def setUp(self):
        super(TestMozillaProperties, self).setUp()
        self.resource.i18n_method = 'MOZILLA_PROPERTIES'
        self.resource.save()

    def test_escaped(self):
        j = MozillaPropertiesHandler()
        self.assertFalse(j._is_escaped(r"es blah", 2))
        self.assertTrue(j._is_escaped(r"e\ blah", 2))
        self.assertFalse(j._is_escaped(r"\\ blah", 2))
        self.assertTrue(j._is_escaped(r"e\\\ blah", 4))

    def test_accept(self):
        parser = MozillaPropertiesHandler()
        self.assertTrue(parser.accepts('MOZILLAPROPERTIES'))

    def test_split(self):
        j = MozillaPropertiesHandler()
        res = j._split("asd sadsf")
        self.assertEqual(res[0], "asd")
        self.assertEqual(res[1], "sadsf")
        res = j._split("asd=sadsf")
        self.assertEqual(res[0], "asd")
        self.assertEqual(res[1], "sadsf")
        res = j._split("asd:sadsf")
        self.assertEqual(res[0], "asd")
        self.assertEqual(res[1], "sadsf")
        res = j._split("asd\tsadsf")
        self.assertEqual(res[0], "asd")
        self.assertEqual(res[1], "sadsf")
        res = j._split(r"asd\ =sadsf")
        self.assertEqual(res[0], "asd\ ")
        self.assertEqual(res[1], "sadsf")
        res = j._split(r"asd = sadsf")
        self.assertEqual(res[0], "asd")
        self.assertEqual(res[1], "sadsf")
        res = j._split(r"asd\\=sadsf")
        self.assertEqual(res[0], r"asd\\")
        self.assertEqual(res[1], "sadsf")
        res = j._split(r"asd\\\=sadsf")
        self.assertEqual(res[0], r"asd\\\=sadsf")
        self.assertEqual(res[1], None)
        res = j._split(r"asd\\\\=sadsf")
        self.assertEqual(res[0], r"asd\\\\")
        self.assertEqual(res[1], "sadsf")
        res = j._split(r"Key21\:WithColon : Value21")
        self.assertEqual(res[0], r"Key21\:WithColon")
        self.assertEqual(res[1], "Value21")

    def test_properties_parser(self):
        """PROPERTIES file tests."""
        # Parsing PROPERTIES file
        handler = MozillaPropertiesHandler(
            os.path.join(os.path.dirname(__file__), 'complex.properties')
        )

        handler.set_language(self.resource.source_language)
        handler.parse_file(is_source=True)
        self.stringset = handler.stringset
        entities = 0
        translations = 0
        for s in self.stringset.strings:
            entities += 1
            if s.translation.strip() != '':
                translations += 1

        # Asserting number of entities - PROPERTIES file has 25 entries.
        # we ignore keys without a value
        self.assertEqual(entities, 25)
        self.assertEqual(translations, 25)

    def test_properties_save2db(self, delete=True):
        """Test creating source strings from a PROPERTIES file works"""
        handler = MozillaPropertiesHandler(
            os.path.join(os.path.dirname(__file__), 'complex.properties')
        )

        handler.set_language(self.resource.source_language)
        handler.parse_file(is_source=True)

        r = self.resource
        l = self.resource.source_language

        handler.bind_resource(r)

        handler.save2db(is_source=True)

        # Check that all 25 entities are created in the db
        self.assertEqual( SourceEntity.objects.filter(resource=r).count(), 25)

        # Check that all source translations are there
        self.assertEqual(
            len(Translation.objects.filter(source_entity__resource=r, language=l)), 25
        )

        # Import and save the finish translation
        handler.bind_file(os.path.join(os.path.dirname(__file__),'complex_hi_IN.properties'))
        l = Language.objects.get(code='hi_IN')
        handler.set_language(l)
        handler.parse_file()

        entities = 0
        translations = 0
        for s in handler.stringset.strings:
            entities += 1
            if s.translation.strip() != '':
                translations += 1

        self.assertEqual(entities, 23)
        self.assertEqual(translations, 23)

        handler.save2db()
        # Check if all Source strings are untouched
        self.assertEqual(SourceEntity.objects.filter(resource=r).count(), 25)
        # Check that all translations are there
        self.assertEqual(len(Translation.objects.filter(source_entity__resource=r,
            language=l)), 23)

        if delete:
            r.delete()
        else:
            return r

    def test_properties_compile(self):
        """Test compiling translations for PROPERTIES files"""

        self.test_properties_save2db(delete=False)
        handler = MozillaPropertiesHandler()
        handler.bind_resource(self.resource)
        handler.set_language(self.resource.source_language)
        old_template = handler.compiled_template
        handler.compile()
        self.assertNotEqual(old_template, handler.compiled_template)

        handler.set_language(Language.objects.get(code='hi_IN'))
        old_template = handler.compiled_template
        handler.compile()
        self.assertNotEqual(old_template, handler.compiled_template)

        #Cleanup
        self.resource.delete()


text:
drop table user_role;
drop table "user";
drop table role_permission;
drop table role;
drop table permission;
drop table menu;
drop table resource;

redpajama_set_name: RedPajamaGithub


text:
/**
 * Organizations Component
 *
 * @class Organizations
 */
class organizations {

  /**
   * @constructor
   *
   * @param {User}         user    User
   * @param {App}          app     Organizations App
   * @param {Object}       options Component options
   */
  constructor (user, app, options = {}) {
    this._user = user;
    this._app = app;
    this._options = options;
  }

  /**
   * Get all the User' Organizations
   *
   * @param  {Array} options Query options
   * @return {Array}         Organizations
   */
  getAll (options = {}) {
    let organizationIds = _.pluck(this._user._data.organizations, '_id');

    let organizations = this._app.collections.organizations.find({
      '_id': { '$in': organizationIds }
    }, options).fetch();

    if (organizations.length)
      return this._app.organizations.getOrganizations(organizations);
    else
      return [];
  }
}

Organizations.components.user.Organizations = organizations;


text:
namespace content {
class NavigationHandle;
class WebContents;
}  // namespace content

namespace subresource_redirect {

class OriginRobotsRulesCache;

// Returns whether LiteMode is enabled for the profile associated with the
// |web_contents|.
bool IsLiteModeEnabled(content::WebContents* web_contents);

// Returns whether image compression should be applied for this web_contents.
// Also shows an one-time InfoBar on Android if needed.
bool ShowInfoBarAndGetImageCompressionState(
    content::WebContents* web_contents,
    content::NavigationHandle* navigation_handle);

// Notifies to LiteMode that image compression fetch had failed.
void NotifyCompressedImageFetchFailed(content::WebContents* web_contents,
                                      base::TimeDelta retry_after);

// Returns the LitePages robots rules server endpoint URL to fetch for the given
// |origin|.
GURL GetRobotsServerURL(const url::Origin& origin);

// Returns the robots rules cache for the profile of |web_contents|.
OriginRobotsRulesCache* GetOriginRobotsRulesCache(
    content::WebContents* web_contents);

// Returns the maximum number of origin robots rules the browser should cache
// in-memory to be sent to the renderers immediately.
int MaxOriginRobotsRulesCacheSize();

// Returns a random duration LitePages service should bypass for, when a
// LitePages response fails without RetryAfter header.
base::TimeDelta GetLitePagesBypassRandomDuration();

// Returns the maximum duration LitePages service should be bypassed.
base::TimeDelta GetLitePagesBypassMaxDuration();

}  // namespace subresource_redirect

#endif  // CHROME_BROWSER_SUBRESOURCE_REDIRECT_SUBRESOURCE_REDIRECT_UTIL_H_


text:
import { EventsKey } from '../events';
import Event from '../events/Event';
import { ObjectEvent } from '../Object';
import { LoadFunction } from '../Tile';
import { AttributionLike } from './Source';
import { TileSourceEvent } from './Tile';
import XYZ from './XYZ';

export interface Options {
    attributions?: AttributionLike | undefined;
    cacheSize?: number | undefined;
    crossOrigin?: string | undefined;
    maxZoom?: number | undefined;
    opaque?: boolean | undefined;
    reprojectionErrorThreshold?: number | undefined;
    tileLoadFunction?: LoadFunction | undefined;
    url?: string | undefined;
    wrapX?: boolean | undefined;
}
export const ATTRIBUTION: string;
export default class OSM extends XYZ {
    constructor(opt_options?: Options);
    on(type: string | string[], listener: (p0: any) => void): EventsKey | EventsKey[];
    once(type: string | string[], listener: (p0: any) => void): EventsKey | EventsKey[];
    un(type: string | string[], listener: (p0: any) => void): void;
    on(type: 'change', listener: (evt: Event) => void): EventsKey;
    once(type: 'change', listener: (evt: Event) => void): EventsKey;
    un(type: 'change', listener: (evt: Event) => void): void;
    on(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'propertychange', listener: (evt: ObjectEvent) => void): void;
    on(type: 'tileloadend', listener: (evt: TileSourceEvent) => void): EventsKey;
    once(type: 'tileloadend', listener: (evt: TileSourceEvent) => void): EventsKey;
    un(type: 'tileloadend', listener: (evt: TileSourceEvent) => void): void;
    on(type: 'tileloaderror', listener: (evt: TileSourceEvent) => void): EventsKey;
    once(type: 'tileloaderror', listener: (evt: TileSourceEvent) => void): EventsKey;
    un(type: 'tileloaderror', listener: (evt: TileSourceEvent) => void): void;
    on(type: 'tileloadstart', listener: (evt: TileSourceEvent) => void): EventsKey;
    once(type: 'tileloadstart', listener: (evt: TileSourceEvent) => void): EventsKey;
    un(type: 'tileloadstart', listener: (evt: TileSourceEvent) => void): void;
}


text:
@protocol IPlayer;
@protocol IRender;
@class Workspace;
@class Interview;
@class Handler;

@interface InterviewSession : NSObject {

  NSString *__project_;
  NSString *__SessionId_;
  NSString* projectName;
    id<IPlayer> __player_;
    int __SurveyId;
    Workspace *environment;
    Handler *__handler;

}

- (id)initWithIPlayer:(id<IPlayer>)player
        withInterview:(Interview *)interview
             withType:(int)renderType;
- (id)initWithIPlayer:(id<IPlayer>)player
          withIrender:(id<IRender>)render
        withInterview:(Interview *)interview
             withType:(int)renderType;
- (id)initWithNSData:(NSData*)classFile withNSData:(NSData*)stringFile
         withIPlayer:(id<IPlayer>)player
       withInterview:(Interview *)interview
            withType:(int)renderType;
- (id)initWithIPlayer:(id<IPlayer>)player withInterview:(Interview *)interview withType:(int)renderType withSurveyId:(NSString *)surveyId withZipFile:(Byte*)zipFile;
- (id)initWithIPlayer:(id<IPlayer>)player withInterview:(Interview *)interview withType:(int)renderType loadStream:(Byte *)byteStream withLength:(int)length withLongStingByteArray:(Byte *)longByte withLongStrLength:(int)longStrLength;

- (id)initWithIPlayer:(id<IPlayer>)player withInterview:(Interview *)interview withType:(int)renderType loadStream:(Byte *)byteStream withLength:(int)length withLongStingByteArray:(Byte *)longByte withLongStrLength:(int)longStrLength withZipFile:(Byte*)zipFile;

-(int) getSurveyId;
-(void)setSurveyId:(int) value;
-(Handler*) getHandler;
-(void)setHandler:(Handler*) value;
- (NSString *)getSessionId;
- (void)setSessionId:(NSString *)value;
- (NSString *)getCompiledFile;
- (void)execute;
- (BOOL)validate;
-(void)updatePlayer:(id)context;
-(Interview *)load;
@end


text:
//-----------------------------------------------------------------------
// <copyright file="ThreadPoolDispatcherThroughputSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using Akka.Configuration;
using Akka.Dispatch;

namespace Akka.Tests.Performance.Dispatch
{
    public class ThreadPoolDispatcherColdThroughputSpec : ColdDispatcherThroughputSpecBase
    {
        protected override MessageDispatcherConfigurator Configurator()
        {
            return new ThreadPoolDispatcherConfigurator(ConfigurationFactory.Empty, null);
        }
    }

    public class ThreadPoolDispatcherWarmThroughputSpec : WarmDispatcherThroughputSpecBase
    {
        protected override MessageDispatcherConfigurator Configurator()
        {
            return new ThreadPoolDispatcherConfigurator(ConfigurationFactory.Empty, null);
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>PaasACL: Manager Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

PaasACL
    1.0.0-Alpha

Provides Single or Multi-tenant Access Control for a Laravel 4+ webapplication that functions as a Platform As A Service.

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

 All Data Structures Functions Pages

Public Member Functions |
Protected Member Functions |
Protected Attributes

Manager Class Reference

Public Member Functions

 	__construct ($app)

 	driver ($driver=null)

 	extend ($driver, Closure $callback)

 	getDrivers ()

 	__call ($method, $parameters)

Protected Member Functions

 	createDriver ($driver)

 	callCustomCreator ($driver)

Protected Attributes

 	$app

 	$customCreators = array()

 	$drivers = array()

Detailed Description

Definition at line 5 of file Manager.php.

Constructor & Destructor Documentation

          __construct
          (

          $app	)

Create a new manager instance.

Parameters

\Illuminate\Foundation\Application	$app

Returns

void

Definition at line 34 of file Manager.php.

Member Function Documentation

          __call
          (

          $method,

          $parameters

          )

Dynamically call the default driver instance.

Parameters

string	$method

array	$parameters

Returns

mixed

Definition at line 129 of file Manager.php.

          callCustomCreator
          (

          $driver	)

protected

Call a custom driver creator.

Parameters

string	$driver

Returns

mixed

Definition at line 93 of file Manager.php.

          createDriver
          (

          $driver	)

protected

Create a new driver instance.

Parameters

string	$driver

Returns

mixed

Exceptions

\InvalidArgumentException

Definition at line 68 of file Manager.php.

          driver
          (

          $driver = null	)

Get a driver instance.

Parameters

string	$driver

Returns

mixed

Definition at line 45 of file Manager.php.

          extend
          (

          $driver,

          Closure
          $callback

          )

Register a custom driver creator Closure.

Parameters

string	$driver

Closure	$callback

Returns

|static

Definition at line 105 of file Manager.php.

          getDrivers
          (
          	)

Get all of the created "drivers".

Returns

array

Definition at line 117 of file Manager.php.

The documentation for this class was generated from the following file:

Y:/cms/workbench/eig/paasacl/vendor/illuminate/support/Illuminate/Support/Manager.php

Illuminate

Support

Manager

Generated on Thu Jan 9 2014 11:06:33 for PaasACL by

     1.8.6


text:
service crond start

# 关闭服务
service crond stop

# 重启服务
service crond restart

# 重新载入配置
service crond reload


text:
\h1{los coeficientes binomiales también}

Биномиальным una tasa de $C_n^k$ se refiere al número de maneras de seleccionar el conjunto de $k$ artículos $n$ de diversos artículos sin tener en cuenta el orden de aparición de estos elementos (es decir, el número de conjuntos desordenados).

También los coeficientes binomiales también es коффициенты en la descomposición de $(a+b)^n$ (lo que se conoce como el binomio de newton):

$$ (a+b)^n = C_n^0 a^n + C_n^1 a^{n-1} b + C_n^2 a^{n-2} b^2 + \ldots + C_n^k a^{n-k} b^k + \ldots + C_n^n b^n $$

Se considera que esta fórmula, como el triángulo, que efectivamente encontrar los factores, abrió blaise pascal (Blaise Pascal), que vivió en el siglo 17 s. sin Embargo, se ha conocido aún chino matemáticas jan Хуэю (Yang Hui), que estaba en el 13 siglo Posible, que abrió el científico persa omar jayyam (Omar Khayyam). Además, el matemático indio pingala (Pingala), que vivía aún en 3 s. adc, recibió cercanos de los resultados. El mérito de la misma de newton es que él resumió esta fórmula para los grados que no son naturales.

\h2{Cálculo}

\bf{Análisis de la fórmula} para calcular:

$$ C_n^k = \frac{n!}{k! (n-k)!} $$

Esta fórmula es fácil de deducir a partir de la tarea de trastornos de la muestra (número de formas de seleccionar imágenes de $k$ elementos $n$ de los elementos). Primero calcular el número de muestras ordenadas. Seleccionar el primer elemento es $n$ maneras, la segunda --- $n-1$, tercer --- $n-2$, y así sucesivamente. En consecuencia, para el número de clasificados de muestras obtenemos la fórmula: $ n (n-1) (n-2) \ldots (n-k+1) = \frac{n!}{(n-k)!} $. El desordenado muestras de pasar fácilmente, si se observar que de cada confuso de la muestra coincide exactamente con $k!$ ordenados (porque es la cantidad de permutaciones de $k$ elemento). En consecuencia, compartiendo $\frac{n!}{(n-k)!}$ $k!$, tenemos lo que busca la fórmula.

\bf{la esquizofrenia recurrente fórmula} (con la que está asociado el famoso "triángulo de pascal"):

$$ C_n^k = C_{n-1}^{k-1} + C_{n-1}^k $$

Fácil de mostrar a través de la fórmula anterior.

Vale la pena señalar, especialmente cuando $n<k$ es $C_n^k$ siempre depende de cero.

\h2{Propiedades}

Los coeficientes binomiales también poseen muchas propiedades diferentes, pondremos el más simple de ellos:

\ul{
\li Regla de la simetría:
$$ C_n^k = C_n^{n-k} $$
\li Realizar es la separación:
$$ C_n^k = \frac{n}{k} C_{n-1}^{k-1} $$
\li Suma de $k$:
$$ \sum_{k=0}^n C_n^k = 2^n $$
\li Suma de $n$:
$$ \sum_{m=0}^n C_m^k = C_{n+1}^{k+1} $$
\li Suma de $n$ y $k$:
$$ \sum_{k=0}^{m} C_{n+k}^k = C_{n+m+1}^m $$
\li Suma de los cuadrados:
$$ (C_n^0)^2 + (C_n^1)^2 + \ldots + (C_n^n)^2 = C_{2n}^n $$
\li Ponderado de la suma de:
$$ 1 C_n^1 + 2 C_n^2 + \ldots + n C_n^n = n 2^{n-1} $$
\li Relación con \algohref=fibonacci_numbers{los números de fibonacci}:
$$ C_n^0 + C_{n-1}^1 + \ldots + C_{n-k}^k + \ldots + C_0^n = F_{n+1} $$
}

\h2{ Cálculo en el programa }

\h3{ Directos de cálculo analítico de la fórmula }

El cálculo de la primera, estará fórmula, muy fáciles de programar, sin embargo, este método es susceptible переполнениям incluso cuando relativamente pequeños valores de $n$ y $k$ (incluso si la respuesta es colocado en algún tipo de datos, el cálculo de los intermedios factorial puede provocar un desbordamiento). Por lo tanto, muy a menudo, este método sólo se puede aplicar junto con [[Larga aritmética|Larga aritmética]]:

\code

int C (int n, int k) {
int res = 1;
for (int i=n-k+1; i<=n; ++i)
res *= i;
for (int i=2; i<=k; i++)
res /= i;
}
\endcode

\h3{ Mejora de la implementación }

Se puede observar que en la anterior aplicación en el numerador y el denominador de la cuesta la misma cantidad de cofactores ($k$), cada uno de los cuales no es menor que la unidad. Por lo tanto, se puede sustituir nuestra fracción en la obra de $k$ fracciones, cada una de las cuales es вещественнозначной. Sin embargo, se puede observar que, después de домножения actual de la respuesta a cada una de la siguiente fracción de todos modos salga un número entero (esto es, por ejemplo, de las propiedades de realizar-la imposición"). Por lo tanto, nos encontramos con esta aplicación:

\code

int C (int n, int k) {
double res = 1;
for (int i=1; i<=k; i++)
res = res * (n-k+i) / i;
return (int) (res + 0.01);
}
\endcode

Aquí estamos con cuidado proporcionamos un número fraccionario de un todo, teniendo en cuenta, que debido a que se acumulan de los sesgos que puede ser un poco menos del valor verdadero (por ejemplo, $2.99999$ en lugar de tres).

\h3{ Triángulo de pascal }

Con el uso de la misma рекуррентного una relación se puede construir la tabla binomial de los factores (de hecho, el triángulo de pascal), y de ella sacar el resultado. La ventaja de este método es que los resultados intermedios nunca superan a la respuesta, y para el cálculo de cada nuevo elemento de la tabla es tan sólo una suma. La desventaja es que el trabajo lento para grandes de N y K, si en realidad, el cuadro no es necesario, sino más bien de un valor único (ya que para el cálculo de $C_n^k$ necesitará construir una tabla para todos los $C_i^j,\ \ 1 \le i \le n,\ \ 1 \le j \le n$, o, al menos, hasta $1 \le j \le \min(i,2k)$).

\code

const int maxn = ...;
int C[maxn+1][maxn+1];
for (int n=0; n<=maxn; ++n) {
C[n][0] = C[n][n] = 1;
for (int k=1; k<n; k++)
C[n][k] = C[n-1][k-1] + C[n-1][k];
}
\endcode

Si toda la tabla de valores no es necesario, entonces, como puedes ver, la suficiente para almacenar de ella solamente dos líneas (actual --- $n$n la línea y la anterior --- $n-1$-ésimo).

\h3{ Cálculo de O(1) }

Por último, en algunas situaciones resulta beneficioso предпосчитать de antemano el valor de todos los factorial, para posteriormente considerar necesarios биномиальный factor, produciendo sólo dos de la división. Esto puede ser beneficioso cuando se utiliza \algohref=big_integer{Larga de la aritmética}, si la memoria no permite предпосчитать todo el triángulo de pascal, o cuando desea realizar cálculos de un simple módulo (si el módulo no es fácil, lo difícil al dividir el numerador de la fracción por el denominador; puede superar, si факторизовать módulo y almacenar todos los números en forma de vectores de grados de estos sencillos; cm \algohref=big_integer{la sección Larga de la aritmética en факторизованном forma"}).


text:
'use strict';

var Promise = require('pinkie-promise');

var toString = Object.prototype.toString;

/**
 * Array.isArray polyfyll
 *     https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#Polyfill
 *
 * @param  {Object} obj
 * @return {Boolean}
 */
function arrayIsArray(obj) {
	return toString.call(obj) === '[object Array]';
}

/**
 * Async
 *
 * @param  {Any}       value
 * @return {Functions} Promise [Boolean]
 */
module.exports = function (value) {
	return new Promise(function (resolve) {
		resolve(arrayIsArray(value));
	});
};

/**
 * Sync
 *
 * @param  {Any}     value
 * @return {Boolean}
 */
module.exports.sync = function (value) {
	return arrayIsArray(value);
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.global.canvas.services.api;

import com.grogdj.grogshop.core.model.DrawEvent;

/**
 *
 * @author salaboy
 * All of these service needs to provide async implementations
 */
public interface DrawService {
    void draw(DrawEvent event);

    void export();

    public void dispose();
}


text:
package org.kuali.kra.committee.rule.event;

import org.kuali.kra.committee.bo.CommitteeMembership;
import org.kuali.kra.rule.BusinessRuleInterface;
import org.kuali.kra.rule.event.KraDocumentEventBaseExtension;
import org.kuali.rice.krad.document.Document;

import java.util.List;

/**
 *
 * This class is using the new rule framework.  The old framework is using CommitteeMembershipRuleEventBase
 */
public abstract class CommitteeMemberEventBase <Z extends BusinessRuleInterface> extends KraDocumentEventBaseExtension {

    /**
     * Enum helps identify type of error to respond.
     */
    public enum ErrorType {HARDERROR, SOFTERROR};

    private List<CommitteeMembership> committeeMemberships;

    private ErrorType type;

    /**
     *
     * Constructs a CommitteeMemberEventBase.java.
     * @param description
     * @param errorPathPrefix
     * @param document
     * @param committeeMemberships
     * @param type
     */
    public CommitteeMemberEventBase(String description, String errorPathPrefix, Document document, List<CommitteeMembership> committeeMemberships, ErrorType type) {
        super(description, errorPathPrefix, document);
        this.committeeMemberships = committeeMemberships;
        this.type = type;
    }

    public ErrorType getType() {
        return this.type;
    }

    public List<CommitteeMembership> getCommitteeMemberships() {
        return committeeMemberships;
    }

    public void setCommitteeMemberships(List<CommitteeMembership> committeeMemberships) {
        this.committeeMemberships = committeeMemberships;
    }
}


text:
class AddPointsToMemberships < ActiveRecord::Migration
  def change
    add_column :memberships, :points, :integer
  end
end


text:
<?php
session_start();
class UserInfo {
    var $login_error = "NONE";
    var $fields = [];
    var $values = [];
    var $assignment_id;
    var $priv_level = 1;
    var $students = [];
}

$res = new UserInfo();

$_POST = json_decode(file_get_contents("php://input"), true);
if (isset($_SESSION['assignment_id'])) {
    include("advanced_user_oo.php");
    Define('DATABASE_SERVER', $hostname);
    Define('DATABASE_USERNAME', $username);
    Define('DATABASE_PASSWORD', $password);
    Define('DATABASE_NAME', 'individualizer');

    $mysqli = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);

    $assignment_id = $_SESSION['assignment_id'];
    $res->priv_level = $_SESSION['priv_level'];
    $res->assignment_id = $assignment_id;

    $query = "SELECT field_1, field_2, field_3, field_4, field_5, field_6
        FROM fields
        WHERE assignment_id='$assignment_id'";

    $result = $mysqli->query($query);
    $json = array();
    while ($row = $result->fetch_assoc()) {
        $json[] = $row;
    }
    $res->fields = $json;

    if ($res->priv_level==1) {
        $net_id = $_SESSION['net_id'];
        $query = "SELECT field_1, field_2, field_3, field_4, field_5, field_6
        FROM students
        WHERE net_id='$net_id' AND assignment_id='$assignment_id'";

        $result = $mysqli->query($query);
        $json = array();
        while ($row = $result->fetch_assoc()) {
            $json[] = $row;
        }
        $res->values = $json;
    } else {
        $query = "SELECT net_id, family_name, given_name, field_1, field_2, field_3, field_4, field_5, field_6
        FROM students
        WHERE assignment_id='$assignment_id'";

        $result = $mysqli->query($query);
        $json = array();
        while ($row = $result->fetch_assoc()) {
            $json[] = $row;
        }
        $res->students = $json;
    }

    $mysqli->close();
    echo json_encode($res);

} else {
    $res->login_error = "Authentication error.";
    echo json_encode($res);
}

?>


text:
layout: template
title: Login
---

Please login

		<form action="#">

					<input class="c-field" placeholder="Email address">
					<input class="c-field" placeholder="Password" type="password">

				<input type="checkbox">
				Remember me

				<button class="c-button c-button--primary c-button--block" type="submit">Login</button>

		</form>


text:
import * as nls from 'vs/nls';
import * as path from 'vs/base/common/path';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IStorageKeysSyncRegistryService } from 'vs/platform/userDataSync/common/storageKeys';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';

/**
 * Shows a message when semantic tokens are shown the first time.
 */
export class SemanticTokensHelp extends Disposable implements IEditorContribution {

	public static readonly ID = 'editor.contrib.semanticHighlightHelp';

	constructor(
		_editor: ICodeEditor,
		@INotificationService _notificationService: INotificationService,
		@IOpenerService _openerService: IOpenerService,
		@IWorkbenchThemeService _themeService: IWorkbenchThemeService,
		@IEditorService _editorService: IEditorService,
		@IStorageService _storageService: IStorageService,
		@IStorageKeysSyncRegistryService storageKeysSyncRegistryService: IStorageKeysSyncRegistryService
	) {
		super();
		// opt-in to syncing
		const neverShowAgainId = 'editor.contrib.semanticTokensHelp';

		if (_storageService.getBoolean(neverShowAgainId, StorageScope.GLOBAL)) {
			return;
		}

		storageKeysSyncRegistryService.registerStorageKey({ key: neverShowAgainId, version: 1 });

		const toDispose = this._register(new DisposableStore());
		const localToDispose = toDispose.add(new DisposableStore());
		const installChangeTokenListener = (model: ITextModel) => {
			localToDispose.add(model.onDidChangeTokens((e) => {
				if (!e.semanticTokensApplied) {
					return;
				}
				if (_storageService.getBoolean(neverShowAgainId, StorageScope.GLOBAL)) {
					toDispose.dispose();
					return;
				}
				const activeEditorControl = _editorService.activeTextEditorControl;
				if (!isCodeEditor(activeEditorControl) || activeEditorControl.getModel() !== model) {
					return; // only show if model is in the active code editor
				}

				toDispose.dispose(); // uninstall all listeners, make sure the notification is only shown once per window
				_storageService.store(neverShowAgainId, true, StorageScope.GLOBAL); // never show again

				const message = nls.localize(
					{
						key: 'semanticTokensHelp',
						comment: [
							'Variable 0 will be a file name.',
							'Variable 1 will be a theme name.'
						]
					},
					"Code coloring of '{0}' has been updated as the theme '{1}' has [semantic highlighting](https://go.microsoft.com/fwlink/?linkid=2122588) enabled.",
					path.basename(model.uri.path), _themeService.getColorTheme().label
				);

				_notificationService.prompt(Severity.Info, message, [
					{
						label: nls.localize('learnMoreButton', "Learn More"),
						run: () => {
							const url = 'https://go.microsoft.com/fwlink/?linkid=2122588';

							_openerService.open(URI.parse(url));
						}
					}
				]);
			}));
		};

		const model = _editor.getModel();
		if (model !== null) {
			installChangeTokenListener(model);
		}

		toDispose.add(_editor.onDidChangeModel((e) => {
			localToDispose.clear();

			const model = _editor.getModel();
			if (!model) {
				return;
			}
			installChangeTokenListener(model);
		}));
	}
}

registerEditorContribution(SemanticTokensHelp.ID, SemanticTokensHelp);


text:
require 'spec_helper'
require 'dystio/etcd/provider'

describe Dystio::Etcd::Provider do
end


text:
package com.zang.api.connectors;

import com.zang.api.configuration.ZangConfiguration;
import com.zang.api.domain.AccessControlList;
import com.zang.api.domain.IpAddress;
import com.zang.api.domain.list.AccessControlListsList;
import com.zang.api.domain.list.IpAddressesList;
import com.zang.api.exceptions.ZangException;
import com.zang.api.restproxies.SipIpAccessControlListsProxy;
import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;

/**
 * Used for all forms of communication with the Sip IP Access Control Lists endpoint of the Zang REST API.
 * @see ZangConnectorFactory
 */
public class SipIpAccessControlListsConnector extends BaseConnector {

    private SipIpAccessControlListsProxy proxy;

    SipIpAccessControlListsConnector(ZangConfiguration conf, ClientHttpEngine executor) {
        super(conf, executor);
        proxy = createProxy(SipIpAccessControlListsProxy.class);
    }

    /**
     * View information for an IP access control list.
     * @param accountSid Account SID
     * @param ipAccessControlListSid IP ACL SID
     * @return The requested Access Control List
     * @throws ZangException
     */
    public AccessControlList viewIpAccessControlList(String accountSid, String ipAccessControlListSid) throws ZangException {
        return returnThrows(proxy.viewIpAccessControlList(accountSid, ipAccessControlListSid), AccessControlList.class);
    }

    /**
     * View information for an IP access control list.
     * @param ipAccessControlListSid IP ACL SID
     * @return The requested Access Control List
     * @throws ZangException
     */
    public AccessControlList viewIpAccessControlList(String ipAccessControlListSid) throws ZangException {
        return viewIpAccessControlList(conf.getSid(), ipAccessControlListSid);
    }

    /**
     * Lists IP Access Control Lists associated with an account.
     * @param accountSid Account SID
     * @param page Page to return
     * @param pageSize Number of items to return per page
     * @return List of IP Access Control Lists
     * @throws ZangException
     */
    public AccessControlListsList listIpAccessControlLists(String accountSid, Integer page, Integer pageSize) throws ZangException {
        return returnThrows(proxy.listIpAccessControlLists(accountSid, page, pageSize), AccessControlListsList.class);
    }

    /**
     * Lists IP Access Control Lists associated with your account.
     * @param page Page to return
     * @param pageSize Number of items to return per page
     * @return List of IP Access Control Lists
     * @throws ZangException
     */
    public AccessControlListsList listIpAccessControlLists(Integer page, Integer pageSize) throws ZangException {
        return listIpAccessControlLists(conf.getSid(), page, pageSize);
    }

    /**
     * Creates an IP Access Control List
     * @param accountSid Account SID
     * @param friendlyName A human-readable name associated with this IP ACL.
     * @return The created Access Control List
     * @throws ZangException
     */
    public AccessControlList createIpAccessControlList(String accountSid,  String friendlyName) throws ZangException {
        return returnThrows(proxy.createIpAccessControlList(accountSid, friendlyName), AccessControlList.class);
    }

    /**
     * Creates an IP Access Control List
     * @param friendlyName A human-readable name associated with this IP ACL.
     * @return The created Access Control List
     * @throws ZangException
     */
    public AccessControlList createIpAccessControlList(String friendlyName) throws ZangException {
        return createIpAccessControlList(conf.getSid(), friendlyName);
    }

    /**
     * Updates information for an IP access control list.
     * @param accountSid Account SID
     * @param ipAccessControlListSid Access Control List SID
     * @param friendlyName A human-readable name associated with this IP ACL.
     * @return The updated Access Control List
     * @throws ZangException
     */
    public AccessControlList updateIpAccessControlList(String accountSid, String ipAccessControlListSid,  String friendlyName) throws ZangException {
        return returnThrows(proxy.updateIpAccessControlList(accountSid, ipAccessControlListSid, friendlyName), AccessControlList.class);
    }

    /**
     * Updates information for an IP access control list.
     * @param ipAccessControlListSid Access Control List SID
     * @param friendlyName A human-readable name associated with this IP ACL.
     * @return The updated Access Control List
     * @throws ZangException
     */
    public AccessControlList updateIpAccessControlList(String ipAccessControlListSid,  String friendlyName) throws ZangException {
        return updateIpAccessControlList(conf.getSid(), ipAccessControlListSid, friendlyName);
    }

    /**
     * Deletes an IP Access Control List
     * @param accountSid Account SID
     * @param ipAccessControlListSid Access Control List SID
     * @return The deleted Access Control List
     * @throws ZangException
     */
    public AccessControlList deleteIpAccessControlList(String accountSid, String ipAccessControlListSid) throws ZangException {
        return returnThrows(proxy.deleteIpAccessControlList(accountSid, ipAccessControlListSid), AccessControlList.class);
    }

    /**
     * Deletes an IP Access Control List
     * @param ipAccessControlListSid Access Control List SID
     * @return The deleted Access Control List
     * @throws ZangException
     */
    public AccessControlList deleteIpAccessControlList(String ipAccessControlListSid) throws ZangException {
        return deleteIpAccessControlList(conf.getSid(), ipAccessControlListSid);
    }

    /**
     * View information on an IP access control list IP address.
     * @param accountSid Account SID
     * @param ipAccessControlListSid Access Control List SID
     * @param ipSid IP Address SID
     * @return Information about the requested IP Address
     * @throws ZangException
     */
    public IpAddress viewAccessControlListIp(String accountSid, String ipAccessControlListSid, String ipSid) throws ZangException {
        return returnThrows(proxy.viewAccessControlListIp(accountSid, ipAccessControlListSid, ipSid), IpAddress.class);
    }

    /**
     * View information on an IP access control list IP address.
     * @param ipAccessControlListSid Access Control List SID
     * @param ipSid IP Address SID
     * @return Information about the requested IP Address
     * @throws ZangException
     */
    public IpAddress viewAccessControlListIp(String ipAccessControlListSid, String ipSid) throws ZangException {
        return viewAccessControlListIp(conf.getSid(), ipAccessControlListSid, ipSid);
    }

    /**
     * Lists IP addresses attached to an IP access control list.
     * @param accountSid Account SID
     * @param ipAccessControlListSid Access Control List SID
     * @param page Page to return
     * @param pageSize Number of items to return per page
     * @return List of IP Addresses
     * @throws ZangException
     */
    public IpAddressesList listAccessControlListIps(String accountSid, String ipAccessControlListSid, Integer page, Integer pageSize) throws ZangException {
        return returnThrows(proxy.listAccessControlListIps(accountSid, ipAccessControlListSid, page, pageSize), IpAddressesList.class);
    }

    /**
     * Lists IP addresses attached to an IP access control list.
     * @param ipAccessControlListSid Access Control List SID
     * @param page Page to return
     * @param pageSize Number of items to return per page
     * @return List of IP Addresses
     * @throws ZangException
     */
    public IpAddressesList listAccessControlListIps(String ipAccessControlListSid, Integer page, Integer pageSize) throws ZangException {
        return listAccessControlListIps(conf.getSid(), ipAccessControlListSid, page, pageSize);
    }

    /**
     * Adds a new IP to an access control list.
     * @param accountSid Account SID
     * @param ipAccessControlListSid Access Control List SID
     * @param friendlyName A human-readable name associated with this IP Address.
     * @param ipAddress An IP address from which you wish to accept traffic. At this time, only IPv4 supported.
     * @return The associated IP Address.
     * @throws ZangException
     */
    public IpAddress addAccessControlListIp(String accountSid, String ipAccessControlListSid,  String friendlyName,  String ipAddress) throws ZangException {
        return returnThrows(proxy.addAccessControlListIp(accountSid, ipAccessControlListSid, friendlyName, ipAddress), IpAddress.class);
    }

    /**
     * Adds a new IP to an access control list.
     * @param ipAccessControlListSid Access Control List SID
     * @param friendlyName A human-readable name associated with this IP Address.
     * @param ipAddress An IP address from which you wish to accept traffic. At this time, only IPv4 supported.
     * @return The associated IP Address.
     * @throws ZangException
     */
    public IpAddress addAccessControlListIp(String ipAccessControlListSid,  String friendlyName,  String ipAddress) throws ZangException {
        return addAccessControlListIp(conf.getSid(), ipAccessControlListSid, friendlyName, ipAddress);
    }

    /**
     * Updates IP Address for an IP Access Control List
     * @param accountSid Account SID
     * @param ipAccessControlListSid IP Access Control List SID
     * @param ipSid IP Address SID
     * @param friendlyName A human-readable name associated with this IP Address.
     * @param ipAddress An IP address from which you wish to accept traffic. At this time, only IPv4 supported.
     * @return The updated IP Address.
     * @throws ZangException
     */
    public IpAddress updateAccessControlListIp(String accountSid, String ipAccessControlListSid, String ipSid,  String friendlyName,  String ipAddress) throws ZangException {
        return returnThrows(proxy.updateAccessControlListIp(accountSid, ipAccessControlListSid, ipSid, friendlyName, ipAddress), IpAddress.class);
    }

    /**
     * Updates IP Address for an IP Access Control List
     * @param ipAccessControlListSid IP Access Control List SID
     * @param ipSid IP Address SID
     * @param friendlyName A human-readable name associated with this IP Address.
     * @param ipAddress An IP address from which you wish to accept traffic. At this time, only IPv4 supported.
     * @return The updated IP Address.
     * @throws ZangException
     */
    public IpAddress updateAccessControlListIp(String ipAccessControlListSid, String ipSid,  String friendlyName,  String ipAddress) throws ZangException {
        return updateAccessControlListIp(conf.getSid(), ipAccessControlListSid, ipSid, friendlyName, ipAddress);
    }

    /**
     * Removes an IP address from an Access Control List.
     * @param accountSid Account SID
     * @param ipAccessControlListSid IP Access Control List SID
     * @param ipSid IP Address SID
     * @return The removed IP Address
     * @throws ZangException
     */
    public IpAddress deleteAccessControlListIp(String accountSid, String ipAccessControlListSid, String ipSid) throws ZangException {
        return returnThrows(proxy.deleteAccessControlListIp(accountSid, ipAccessControlListSid, ipSid), IpAddress.class);
    }

    /**
     * Removes an IP address from an Access Control List.
     * @param ipAccessControlListSid IP Access Control List SID
     * @param ipSid IP Address SID
     * @return The removed IP Address
     * @throws ZangException
     */
    public IpAddress deleteAccessControlListIp(String ipAccessControlListSid, String ipSid) throws ZangException {
        return deleteAccessControlListIp(conf.getSid(), ipAccessControlListSid, ipSid);
    }
}


text:
require 'test/unit'
require 'flexmock/test_unit'
require 'namaken/cli'
require 'uri'

class TestCLI < Test::Unit::TestCase
  def setup
    @app = flexmock("testapp")
    @cli = Namaken::CLI.new
    @cli.application = @app
  end

  def test_add
    @app.should_receive(:add_feed).with(URI.parse('http://www.example.com')).once
    @cli.add('http://www.example.com')
  end

  def test_parse
    @app.should_receive(:parse_and_extract_feed).with(URI.parse('http://www.example.com')).once
    @cli.parse('www.example.com')
  end

  def test_list
    @app.should_receive(:listup_feeds).with().once
    @cli.list
  end

  def test_remove
    @app.should_receive(:remove_feed).with().once
    @cli.remove
  end

  def test_update
    @app.should_receive(:update_feeds).with().once
    @cli.update
  end

  def test_generate
    @app.should_receive(:generate_summary).with(nil, since_last: nil).once
    @cli.generate
  end

  def test_generate_with_dest
    @app.should_receive(:generate_summary).with('DEST', since_last: nil).once
    @cli.generate 'DEST'
  end
end


text:
import unittest
from color_contrast_calc.color import Color
from color_contrast_calc.color import NAMED_COLORS
from color_contrast_calc.color import NAME_TO_COLOR
from color_contrast_calc.color import HEX_TO_COLOR
from color_contrast_calc.color import WEB_SAFE_COLORS
from color_contrast_calc.color import hsl_colors

class TestColor(unittest.TestCase):
    def setup(self):
        pass

    def test_from_name(self):
        yellow = Color.from_name('yellow')
        self.assertTrue(isinstance(yellow, Color))
        self.assertEqual(yellow.name, 'yellow')
        self.assertEqual(yellow.hex, '#ffff00')

        yellow = Color.from_name('Yellow')
        self.assertEqual(yellow.name, 'yellow')
        self.assertEqual(yellow.hex, '#ffff00')

        self.assertIsNone(Color.from_name('kiiro'))

    def test_from_rgb(self):
        yellow_rgb = (255, 255, 0)
        yellow_name = 'yellow'

        yellow = Color.from_rgb(yellow_rgb)
        self.assertTrue(isinstance(yellow, Color))
        self.assertEqual(yellow.rgb, yellow_rgb)
        self.assertEqual(yellow.name, yellow_name)

        new_name = 'new_yellow'
        new_yellow = Color.from_rgb(yellow_rgb, new_name)

        self.assertEqual(new_yellow.rgb, yellow_rgb)
        self.assertEqual(new_yellow.name, new_name)

        unnamed_rgb = (123, 234, 123)
        unnamed_hex = '#7bea7b'
        new_color = Color.from_rgb(unnamed_rgb)

        self.assertFalse(unnamed_hex in HEX_TO_COLOR)
        self.assertEqual(new_color.hex, unnamed_hex)
        self.assertEqual(new_color.name, unnamed_hex)

    def test_from_hex(self):
        yellow_normalized_hex = '#ffff00'
        yellow_name = 'yellow'
        undefined_color_hex = '#f3f2f1'
        undefined_color_name = 'undefined_color'
        new_yellow_name = 'new_yellow'

        yellow = Color.from_hex(yellow_normalized_hex)
        self.assertTrue(isinstance(yellow, Color))
        self.assertEqual(yellow.name, yellow_name)
        self.assertEqual(yellow.hex, yellow_normalized_hex)

        yellow = Color.from_hex('#FFFF00')
        self.assertTrue(isinstance(yellow, Color))
        self.assertEqual(yellow.name, yellow_name)
        self.assertEqual(yellow.hex, yellow_normalized_hex)

        yellow = Color.from_hex('#ff0')
        self.assertTrue(isinstance(yellow, Color))
        self.assertEqual(yellow.name, yellow_name)
        self.assertEqual(yellow.hex, yellow_normalized_hex)

        undefined_color = Color.from_hex(undefined_color_hex)
        self.assertTrue(isinstance(undefined_color, Color))
        self.assertEqual(undefined_color.name, undefined_color_hex)
        self.assertEqual(undefined_color.hex, undefined_color_hex)

        undefined_color = Color.from_hex(undefined_color_hex, undefined_color_name)
        self.assertEqual(undefined_color.name, undefined_color_name)

        new_yellow = Color.from_hex('#ff0', new_yellow_name)
        self.assertEqual(new_yellow.hex, yellow_normalized_hex)
        self.assertEqual(new_yellow.name, new_yellow_name)

    def test_from_hsl(self):
        self.assertEqual(Color.from_hsl((60, 100, 50)).hex, '#ffff00')
        self.assertEqual(Color.from_hsl((60.0, 100.0, 50.0)).hex, '#ffff00')

        self.assertEqual(Color.from_hsl((30, 100, 50)).hex, '#ff8000')
        self.assertEqual(Color.from_hsl((30.0, 100.0, 50.0)).hex, '#ff8000')

    def test_propertyies(self):
        yellow_rgb = (255, 255, 0)
        yellow_hex = '#ffff00'
        yellow_short_hex = '#ff0'
        yellow_name = 'yellow'
        yellow_hsl = (60, 100, 50)
        unnamed_rgb = (123, 234, 123)
        unnamed_hex = '#7bea7b'

        yellow = Color(yellow_rgb, yellow_name)
        self.assertEqual(yellow.rgb, yellow_rgb)
        self.assertEqual(yellow.hex, yellow_hex)
        self.assertEqual(yellow.name, yellow_name)
        self.assertAlmostEqual(yellow.relative_luminance, 0.9278)

        yellow = Color(yellow_hex, yellow_name)
        yellow_short = Color(yellow_short_hex, yellow_name)
        self.assertEqual(yellow.rgb, yellow_rgb)
        self.assertEqual(yellow.hex, yellow_hex)
        self.assertAlmostEqual(yellow.relative_luminance, 0.9278)
        self.assertEqual(yellow_short.rgb, yellow_rgb)
        self.assertEqual(yellow_short.hex, yellow_hex)
        self.assertAlmostEqual(yellow_short.relative_luminance, 0.9278)

        yellow = Color(yellow_rgb)
        self.assertEqual(yellow.rgb, yellow_rgb)
        self.assertEqual(yellow.hex, yellow_hex)
        self.assertEqual(yellow.name, yellow_name)

        tmp_color = Color(unnamed_rgb)
        self.assertEqual(tmp_color.rgb, unnamed_rgb)
        self.assertEqual(tmp_color.hex, unnamed_hex)
        self.assertEqual(tmp_color.name, unnamed_hex)

    def test_hsl(self):
        yellow_rgb = (255, 255, 0)
        yellow_hsl = (60, 100, 50)
        yellow = Color(yellow_rgb)

        for i, c in enumerate(yellow_hsl):
            self.assertAlmostEqual(yellow.hsl[i], c)

    def test_rgb_code(self):
        yellow = Color((255, 255, 0))
        yellow_rgb_code = 'rgb(255,255,0)'

        self.assertEqual(yellow.rgb_code, yellow_rgb_code)

    def test_common_name(self):
        yellow = Color('#ff0')
        self.assertEqual(yellow.common_name, 'yellow')

        unnamed_hex = '#123456'
        self.assertEqual(Color(unnamed_hex).common_name, unnamed_hex)

    def test_str(self):
        yellow = Color((255, 255, 0), 'yellow')
        yellow_rgb = '#ffff00'
        self.assertEqual(str(yellow), yellow_rgb)

    def test_contrast_ratio_against(self):
        color = Color((127, 127, 32))
        white = Color((255, 255, 255))
        expected_ratio = 4.23

        ratio = color.contrast_ratio_against(white.rgb)
        self.assertAlmostEqual(ratio, expected_ratio, 2)

        ratio = color.contrast_ratio_against(white.rgb)
        self.assertAlmostEqual(ratio, expected_ratio, 2)

        ratio = color.contrast_ratio_against(white)
        self.assertAlmostEqual(ratio, expected_ratio, 2)

    def test_contrast_level(self):
        white = Color((255, 255, 255))
        black = Color((0, 0, 0))
        orange = Color((255, 165, 0))
        royalblue = Color((65,105, 225))
        steelblue = Color((70, 130, 180))

        self.assertEqual(white.contrast_level(black), 'AAA')
        self.assertEqual(royalblue.contrast_level(white), 'AA')
        self.assertEqual(steelblue.contrast_level(white), 'A')
        self.assertEqual(orange.contrast_level(white), '-')

    def test_has_sufficient_contrast(self):
        black = Color((0, 0, 0))
        white  = Color((255, 255, 255))
        orange = Color((255, 165, 0))
        blueviolet = Color((138, 43, 226))

        self.assertTrue(black.has_sufficient_contrast(white))
        self.assertTrue(black.has_sufficient_contrast(white, 'A'))
        self.assertTrue(black.has_sufficient_contrast(white, 'AA'))
        self.assertTrue(black.has_sufficient_contrast(white, 'AAA'))

        self.assertFalse(orange.has_sufficient_contrast(white))
        self.assertFalse(orange.has_sufficient_contrast(white, 'A'))
        self.assertFalse(orange.has_sufficient_contrast(white, 'AA'))
        self.assertFalse(orange.has_sufficient_contrast(white, 'AAA'))

        self.assertTrue(orange.has_sufficient_contrast(blueviolet, 'A'))
        self.assertFalse(orange.has_sufficient_contrast(blueviolet))
        self.assertFalse(orange.has_sufficient_contrast(blueviolet, 'AA'))
        self.assertFalse(orange.has_sufficient_contrast(blueviolet, 'AAA'))

        self.assertTrue(white.has_sufficient_contrast(blueviolet))
        self.assertTrue(white.has_sufficient_contrast(blueviolet, 'AA'))
        self.assertFalse(white.has_sufficient_contrast(blueviolet, 'AAA'))

    def test_is_same_color(self):
        yellow_rgb = (255, 255, 0)
        yellow_hex = '#ffff00'
        yellow_short_hex = '#ff0'
        white_rgb = (255, 255, 255)
        yellow = Color(yellow_rgb, 'yellow')
        yellow2 = Color(yellow_rgb, 'yellow2')
        white = Color(white_rgb)

        self.assertEqual(yellow.hex, yellow2.hex)
        self.assertTrue(yellow.is_same_color(yellow2))

        self.assertNotEqual(yellow.hex, white.hex)
        self.assertFalse(yellow.is_same_color(white))

        self.assertTrue(yellow.is_same_color(yellow_hex))
        self.assertTrue(yellow.is_same_color(yellow_short_hex))
        self.assertFalse(white.is_same_color(yellow_short_hex))
        self.assertFalse(white.is_same_color(yellow_short_hex))

        self.assertTrue(yellow.is_same_color(yellow_rgb))
        self.assertFalse(white.is_same_color(yellow_rgb))

    def test_has_max_contrast(self):
        self.assertTrue(Color((255, 255, 0)).has_max_contrast())
        self.assertFalse(Color((255, 165, 0)).has_max_contrast())

    def test_has_min_contrast(self):
        gray = Color((128, 128, 128))
        orange = Color((255, 165, 0))

        self.assertTrue(gray.has_min_contrast())
        self.assertFalse(orange.has_min_contrast())

    def test_has_higher_luminance(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))

        self.assertTrue(yellow.has_higher_luminance(orange))
        self.assertFalse(orange.has_higher_luminance(yellow))
        self.assertFalse(orange.has_higher_luminance(orange))

    def test_has_same_luminance(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))

        self.assertTrue(yellow.has_same_luminance(yellow))
        self.assertFalse(orange.has_same_luminance(yellow))

    def test_is_light_color(self):
        self.assertTrue(Color((118, 118, 118)).is_light_color())
        self.assertFalse(Color((117, 117, 117)).is_light_color())

    def test_with_contrast(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))
        lime = Color((0, 255, 0))
        blue = Color((0, 0, 255))
        white = Color((255, 255, 255))
        black = Color((0, 0, 0))
        neutral_gray = Color((118, 118, 118))
        gray_rgb = (128, 128, 128)

        self.assertEqual(yellow.with_contrast(100).rgb, yellow.rgb)
        self.assertEqual(orange.with_contrast(100).rgb, orange.rgb)
        self.assertEqual(lime.with_contrast(100).rgb, lime.rgb)
        self.assertEqual(blue.with_contrast(100).rgb, blue.rgb)

        self.assertEqual(yellow.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(orange.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(lime.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(blue.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(white.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(black.with_contrast(0).rgb, gray_rgb)
        self.assertEqual(neutral_gray.with_contrast(0).rgb, gray_rgb)

        self.assertEqual(orange.with_contrast(60).rgb, (204, 150, 51))
        self.assertEqual(orange.with_contrast(120).rgb, (255, 173, 0))

    def test_with_brightness(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))
        lime = Color((0, 255, 0))
        blue = Color((0, 0, 255))
        white = Color((255, 255, 255))
        black = Color((0, 0, 0))

        self.assertEqual(yellow.with_brightness(100).rgb, yellow.rgb)
        self.assertEqual(orange.with_brightness(100).rgb, orange.rgb)
        self.assertEqual(lime.with_brightness(100).rgb, lime.rgb)
        self.assertEqual(blue.with_brightness(100).rgb, blue.rgb)

        self.assertEqual(yellow.with_brightness(0).rgb, black.rgb)
        self.assertEqual(orange.with_brightness(0).rgb, black.rgb)
        self.assertEqual(lime.with_brightness(0).rgb, black.rgb)
        self.assertEqual(blue.with_brightness(0).rgb, black.rgb)

        self.assertEqual(white.with_brightness(120).rgb, white.rgb)
        self.assertEqual(yellow.with_brightness(120).rgb, yellow.rgb)

    def test_with_invert(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))
        blue = Color((0, 0, 255))
        royalblue = Color((65,105, 225))
        gray = Color((128, 128, 128))

        self.assertEqual(yellow.with_invert(0).rgb, yellow.rgb)
        self.assertEqual(orange.with_invert(0).rgb, orange.rgb)
        self.assertEqual(blue.with_invert(0).rgb, blue.rgb)
        self.assertEqual(royalblue.with_invert(0).rgb, royalblue.rgb)
        self.assertEqual(gray.with_invert(0).rgb, gray.rgb)

        self.assertEqual(yellow.with_invert().rgb, blue.rgb)
        self.assertEqual(yellow.with_invert(100).rgb, blue.rgb)
        self.assertEqual(blue.with_invert(100).rgb, yellow.rgb)

        self.assertEqual(orange.with_invert(100).rgb, (0, 90, 255))
        self.assertEqual(royalblue.with_invert(100).rgb, (190, 150, 30))

        self.assertEqual(yellow.with_invert(50).rgb, gray.rgb)
        self.assertEqual(orange.with_invert(50).rgb, gray.rgb)
        self.assertEqual(blue.with_invert(50).rgb, gray.rgb)
        self.assertEqual(royalblue.with_invert(50).rgb, gray.rgb)
        self.assertEqual(gray.with_invert(50).rgb, gray.rgb)

    def test_with_hue_rotate(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))
        blue = Color((0, 0, 255))

        self.assertEqual(yellow.with_hue_rotate(0).rgb, yellow.rgb)
        self.assertEqual(orange.with_hue_rotate(0).rgb, orange.rgb)
        self.assertEqual(blue.with_hue_rotate(0).rgb, blue.rgb)

        self.assertEqual(yellow.with_hue_rotate(360).rgb, yellow.rgb)
        self.assertEqual(orange.with_hue_rotate(360).rgb, orange.rgb)
        self.assertEqual(blue.with_hue_rotate(360).rgb, blue.rgb)

        self.assertEqual(yellow.with_hue_rotate(180).rgb, (218, 218, 255))
        self.assertEqual(orange.with_hue_rotate(180).rgb, (90, 180, 255))
        self.assertEqual(blue.with_hue_rotate(180).rgb, (37, 37, 0))

        self.assertEqual(yellow.with_hue_rotate(90).rgb, (0, 255, 218))
        self.assertEqual(orange.with_hue_rotate(90).rgb, (0, 232, 90))
        self.assertEqual(blue.with_hue_rotate(90).rgb, (255, 0, 37))

    def test_with_saturate(self):
        red = Color((255, 0, 0))
        orange = Color((255, 165, 0))
        yellow = Color((255, 255, 0))
        blue = Color((0, 0, 255))

        self.assertEqual(orange.with_saturate(100).rgb, orange.rgb)
        self.assertEqual(yellow.with_saturate(100).rgb, yellow.rgb)
        self.assertEqual(blue.with_saturate(100).rgb, blue.rgb)

        self.assertEqual(orange.with_saturate(0).rgb, (172, 172, 172))
        self.assertEqual(yellow.with_saturate(0).rgb, (237, 237, 237))
        self.assertEqual(blue.with_saturate(0).rgb, (18, 18, 18))

        self.assertEqual(orange.with_saturate(2357).rgb, red.rgb)
        self.assertEqual(orange.with_saturate(3000).rgb, red.rgb)

    def test_with_grayscale(self):
        orange = Color((255, 165, 0))

        self.assertEqual(orange.with_grayscale(0).rgb, orange.rgb)

        self.assertEqual(orange.with_grayscale().rgb, (172, 172, 172))
        self.assertEqual(orange.with_grayscale(100).rgb, (172, 172, 172))

        self.assertEqual(orange.with_grayscale(50).rgb, (214,169, 86))

    def test_find_brightness_threshold(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))

        level = 'A'
        target_ratio = 3.0

        new_color = yellow.find_brightness_threshold(orange, level)
        new_contrast_ratio = yellow.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        new_color = orange.find_brightness_threshold(orange, level)
        new_contrast_ratio = orange.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        level = 'AA'
        target_ratio = 4.5

        new_color = yellow.find_brightness_threshold(orange, level)
        new_contrast_ratio = yellow.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        new_color = orange.find_brightness_threshold(orange, level)
        new_contrast_ratio = orange.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

    def test_find_lightness_threshold(self):
        yellow = Color((255, 255, 0))
        orange = Color((255, 165, 0))

        level = 'A'
        target_ratio = 3.0

        new_color = yellow.find_lightness_threshold(orange, level)
        new_contrast_ratio = yellow.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        new_color = orange.find_lightness_threshold(orange, level)
        new_contrast_ratio = orange.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        level = 'AA'
        target_ratio = 4.5

        new_color = yellow.find_lightness_threshold(orange, level)
        new_contrast_ratio = yellow.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

        new_color = orange.find_lightness_threshold(orange, level)
        new_contrast_ratio = orange.contrast_ratio_against(new_color)
        self.assertTrue(orange.has_higher_luminance(new_color))
        self.assertGreater(new_contrast_ratio, target_ratio)
        self.assertAlmostEqual(new_contrast_ratio, target_ratio, 1)

    def test_WHITE(self):
        self.assertTrue(isinstance(Color.WHITE, Color))
        self.assertEqual(Color.WHITE.name, 'white')
        self.assertEqual(Color.WHITE.hex, '#ffffff')

    def test_GRAY(self):
        self.assertTrue(isinstance(Color.GRAY, Color))
        self.assertEqual(Color.GRAY.name, 'gray')
        self.assertEqual(Color.GRAY.hex, '#808080')

    def test_BLACK(self):
        self.assertTrue(isinstance(Color.BLACK, Color))
        self.assertEqual(Color.BLACK.name, 'black')
        self.assertEqual(Color.BLACK.hex, '#000000')

    def test_NAMED_COLORS(self):
        first_color = NAMED_COLORS[0]
        last_color = NAMED_COLORS[-1]
        self.assertTrue(isinstance(first_color, Color))
        self.assertEqual(first_color.name, 'aliceblue')
        self.assertEqual(first_color.hex, '#f0f8ff')
        self.assertTrue(isinstance(last_color, Color))
        self.assertEqual(last_color.name, 'yellowgreen')
        self.assertEqual(last_color.hex, '#9acd32')
        self.assertEqual(len(NAMED_COLORS), 147)

    def test_NAME_TO_COLOR(self):
        black = 'black'
        white = 'white'
        self.assertEqual(NAME_TO_COLOR[black].name, black)
        self.assertEqual(NAME_TO_COLOR[white].name, white)

    def test_HEX_TO_COLOR(self):
        self.assertEqual(HEX_TO_COLOR['#000000'].name, 'black')
        self.assertEqual(HEX_TO_COLOR['#ffffff'].name, 'white')

    def test_WEB_SAFE_COLORS(self):
        self.assertEqual(len(WEB_SAFE_COLORS), 216)

        first_color = WEB_SAFE_COLORS[0]
        self.assertTrue(isinstance(first_color, Color))
        self.assertEqual(first_color.name, 'black')
        self.assertEqual(first_color.hex, '#000000')

        last_color = WEB_SAFE_COLORS[-1]
        self.assertTrue(isinstance(last_color, Color))
        self.assertEqual(last_color.name, 'white')
        self.assertEqual(last_color.hex, '#ffffff')

        middle_color = WEB_SAFE_COLORS[107]
        self.assertTrue(isinstance(middle_color, Color))
        self.assertEqual(middle_color.hex, '#66ffff')

    def test_hsl_colors(self):
        black = Color.from_name('black')
        white = Color.from_name('white')
        gray = Color.from_name('gray')
        red = Color.from_name('red')
        yellow = Color.from_name('yellow')

        colors = hsl_colors()
        self.assertEqual(len(colors), 361)
        self.assertTrue(colors[0].is_same_color(red))
        self.assertTrue(colors[-1].is_same_color(red))
        self.assertTrue(colors[60].is_same_color(yellow))

        colors = hsl_colors(h_interval = 15)
        self.assertEqual(len(colors), 25)
        self.assertTrue(colors[0].is_same_color(red))
        self.assertTrue(colors[-1].is_same_color(red))
        self.assertTrue(colors[4].is_same_color(yellow))

        colors = hsl_colors(l = 0)
        for c in colors:
            self.assertTrue(c.is_same_color(black))

        colors = hsl_colors(l = 100)
        for c in colors:
            self.assertTrue(c.is_same_color(white))

        colors = hsl_colors(s = 0)
        for c in colors:
            self.assertTrue(c.is_same_color(gray))


text:
// load in the test language
var expect = require('chai').expect;

global.document = require('jsdom').jsdom();
global.window = document.defaultView;

// set up some default stuff
global.jQuery = window.jQuery = require('jquery');
global.$ = window.$ = require('jquery');

require('../jquery.vToggle');

/**
 * vShow function tests
 */
describe('vShow', function () {

    var $testEl = $('
This is a test element
');

    // top level view initialization
    describe('Initialize an element', function () {
        it('vShow it', function () {
            $testEl.vShow();
            expect($testEl.hasClass('display-block')).to.be.true;

            expect($testEl.hasClass('display-none')).to.be.false;
            expect($testEl.hasClass('display-inline')).to.be.false;
            expect($testEl.hasClass('display-inline-block')).to.be.false;
        });

        it('vShow inline', function () {
            $testEl.vShow('inline');
            expect($testEl.hasClass('display-inline')).to.be.true;

            expect($testEl.hasClass('display-none')).to.be.false;
            expect($testEl.hasClass('display-block')).to.be.false;
            expect($testEl.hasClass('display-inline-block')).to.be.false;
        });

        it('vShow inline-block', function () {
            $testEl.vShow('inline-block');
            expect($testEl.hasClass('display-inline-block')).to.be.true;

            expect($testEl.hasClass('display-none')).to.be.false;
            expect($testEl.hasClass('display-block')).to.be.false;
            expect($testEl.hasClass('display-inline')).to.be.false;
        });

        it('vHide it', function () {
            $testEl.vHide();
            expect($testEl.hasClass('display-none')).to.be.true;

            expect($testEl.hasClass('display-inline-block')).to.be.false;
            expect($testEl.hasClass('display-block')).to.be.false;
            expect($testEl.hasClass('display-inline')).to.be.false;
        });
    });
});