text:
#ifndef WEBRTC_BASE_WIN32SOCKETSERVER_H_
#define WEBRTC_BASE_WIN32SOCKETSERVER_H_

#if defined(WEBRTC_WIN)
#include "webrtc/base/asyncsocket.h"
#include "webrtc/base/criticalsection.h"
#include "webrtc/base/messagequeue.h"
#include "webrtc/base/socketserver.h"
#include "webrtc/base/socketfactory.h"
#include "webrtc/base/socket.h"
#include "webrtc/base/thread.h"
#include "webrtc/base/win32window.h"

namespace rtc {

///////////////////////////////////////////////////////////////////////////////
// Win32Socket
///////////////////////////////////////////////////////////////////////////////

class Win32Socket : public AsyncSocket {
 public:
  Win32Socket();
  virtual ~Win32Socket();

  bool CreateT(int family, int type);

  int Attach(SOCKET s);
  void SetTimeout(int ms);

  // AsyncSocket Interface
  virtual SocketAddress GetLocalAddress() const;
  virtual SocketAddress GetRemoteAddress() const;
  virtual int Bind(const SocketAddress& addr);
  virtual int Connect(const SocketAddress& addr);
  virtual int Send(const void *buffer, size_t length);
  virtual int SendTo(const void *buffer, size_t length, const SocketAddress& addr);
  virtual int Recv(void *buffer, size_t length);
  virtual int RecvFrom(void *buffer, size_t length, SocketAddress *out_addr);
  virtual int Listen(int backlog);
  virtual Win32Socket *Accept(SocketAddress *out_addr);
  virtual int Close();
  virtual int GetError() const;
  virtual void SetError(int error);
  virtual ConnState GetState() const;
  virtual int EstimateMTU(uint16* mtu);
  virtual int GetOption(Option opt, int* value);
  virtual int SetOption(Option opt, int value);

 private:
  void CreateSink();
  bool SetAsync(int events);
  int DoConnect(const SocketAddress& addr);
  bool HandleClosed(int close_error);
  void PostClosed();
  void UpdateLastError();
  static int TranslateOption(Option opt, int* slevel, int* sopt);

  void OnSocketNotify(SOCKET socket, int event, int error);
  void OnDnsNotify(HANDLE task, int error);

  SOCKET socket_;
  int error_;
  ConnState state_;
  SocketAddress addr_;         // address that we connected to (see DoConnect)
  uint32 connect_time_;
  bool closing_;
  int close_error_;

  class EventSink;
  friend class EventSink;
  EventSink * sink_;

  struct DnsLookup;
  DnsLookup * dns_;
};

///////////////////////////////////////////////////////////////////////////////
// Win32SocketServer
///////////////////////////////////////////////////////////////////////////////

class Win32SocketServer : public SocketServer {
 public:
  explicit Win32SocketServer(MessageQueue* message_queue);
  virtual ~Win32SocketServer();

  void set_modeless_dialog(HWND hdlg) {
    hdlg_ = hdlg;
  }

  // SocketServer Interface
  virtual Socket* CreateSocket(int type);
  virtual Socket* CreateSocket(int family, int type);

  virtual AsyncSocket* CreateAsyncSocket(int type);
  virtual AsyncSocket* CreateAsyncSocket(int family, int type);

  virtual void SetMessageQueue(MessageQueue* queue);
  virtual bool Wait(int cms, bool process_io);
  virtual void WakeUp();

  void Pump();

  HWND handle() { return wnd_.handle(); }

 private:
  class MessageWindow : public Win32Window {
   public:
    explicit MessageWindow(Win32SocketServer* ss) : ss_(ss) {}
   private:
    virtual bool OnMessage(UINT msg, WPARAM wp, LPARAM lp, LRESULT& result);
    Win32SocketServer* ss_;
  };

  static const TCHAR kWindowName[];
  MessageQueue *message_queue_;
  MessageWindow wnd_;
  CriticalSection cs_;
  bool posted_;
  HWND hdlg_;
};

///////////////////////////////////////////////////////////////////////////////
// Win32Thread. Automatically pumps Windows messages.
///////////////////////////////////////////////////////////////////////////////

class Win32Thread : public Thread {
 public:
  Win32Thread() : ss_(this), id_(0) {
    set_socketserver(&ss_);
  }
  virtual ~Win32Thread() {
    Stop();
    set_socketserver(NULL);
  }
  virtual void Run() {
    id_ = GetCurrentThreadId();
    Thread::Run();
    id_ = 0;
  }
  virtual void Quit() {
    PostThreadMessage(id_, WM_QUIT, 0, 0);
  }
 private:
  Win32SocketServer ss_;
  DWORD id_;
};

///////////////////////////////////////////////////////////////////////////////

}  // namespace rtc

#endif  // WEBRTC_WIN

#endif  // WEBRTC_BASE_WIN32SOCKETSERVER_H_


text:
package org.opencloudb.handler;

import org.opencloudb.config.ErrorCode;
import org.opencloudb.manager.ManagerConnection;
import org.opencloudb.parser.ManagerParseReload;
import org.opencloudb.response.ReloadConfig;
import org.opencloudb.response.ReloadUser;

/**
 * @author mycat
 */
public final class ReloadHandler
{

    public static void handle(String stmt, ManagerConnection c, int offset)
    {
        int rs = ManagerParseReload.parse(stmt, offset);
        switch (rs)
        {
            case ManagerParseReload.CONFIG:
                ReloadConfig.execute(c,false);
                break;
            case ManagerParseReload.CONFIG_ALL:
                ReloadConfig.execute(c,true);
                break;
            case ManagerParseReload.ROUTE:
                c.writeErrMessage(ErrorCode.ER_YES, "Unsupported statement");
                break;
            case ManagerParseReload.USER:
                ReloadUser.execute(c);
                break;
            default:
                c.writeErrMessage(ErrorCode.ER_YES, "Unsupported statement");
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
1. Introdução
    1. Java 8 Lambdas
    2. Código Fonte
    3. Executando os exemplos
2. Filters
   1. Implementando um predicate
3. Mappers
   1. Escrevendo uma function
   2. ```flatMap``` e ```distinct```
4. Sorters
   1. Implementando um ```Comparator```
   2. Usando um ```Comparator```
   3. Revertendo uma lista
5. Collectors
   1. ```toList()``` e ```toSet```
   2. ```toMap```
6. ```toMap```
7. Conclusão

## Introdução

Star Wars é uma das franquias mais famosas deste lado do universo. Todas a trama ocorre há muito tempo atrás em uma galáxia muito muito distante. Foi responsável por gerar incontáveis fãs pelo planeta entre muitas gerações. Com oito filmes, sete da saga principal e um spin-off (até o momento de encerramento desse artigo existe um filme da saga sendo filmado e um outro spin-off) muitas coisas podem ser feitas para minerar seus dados. Esse artigo está ignorando o Star Wars Holiday Special e os filmes dos Ewoks. Sinta-se livre para inseri-los no arquivo ```all_star_wars_movie.json```.

### Java 8 Lambdas

Na linguagem de programação Java, os lambdas foram introduzidos na versão 8 e estão espalhadas pela linguagem facilitando o jeito pelo qual usamos as coisas. Verifique no pacote de IO para ver novas maneiras de carregar arquivos. Outra característica que foi introduzida com os lambdas, foram os métodos default nas interfaces. Verifique a interface Comparator, lá existem muitos métodos default. Eles serão utilizados nos exemplos desse artigo para ordenar coisas. Muitas outras coisas foram introduzidas na versão 8 para facilitar o desenvolvimento de aplicações em Java.

Esse artigo está dividido em quatro seções:

1. Filters, no qual o método ```filter``` é demonstrado.
2. Mappers, no qual os métodos ```map``` e ```flatMap``` serão discutidos
3. Sorters, no qual o método ```sort``` é usado
4. Collector, no qual o método ```collect``` é usado

### Código Fonta

Para escrever esse arquivo, foi desenvolvido um pequeno projeto. Ele está no github pronto para ser clonado. Veja a e [página do projeto](https://github.com/ortolanph/starlambdawars) e se divirta. Não se esqueça de marcar o projeto com uma estrela!

### Executando os exemplos

Leia o arquivo README.md para entender como executar os exemplos desse artigo.

## Filters

Filters significam que é desejado selecionar dados sob uma condição. Em java, condições são predicados e os mesmos estão endereçados para a interface ```java.util.function.Predicate<T>```. Há somente um método que deve ser implementado: o método ```boolean test(T t)```, que avalia a expressão e retorna um booleano. Existem ainda outros métodos default que podem ser usados ao implementar essa interface.

Acesse o link para a classe [Predicate](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html) da documentação da Oracle.

### Implmentando um Predicate

Existem duas maneiras de se usar um Predicate. A primeira é implementar a interface em uma classe concreta. O desenvolvedor deve implementar todos os métodos abstratos, nesse caso, o método ```test```. É possivel ainda sobrescrever todos os métodos default, mas esse não é foco para esse artigo.

Ilustrando um exemplo com os magníficos dados, é desejado encontrar filmes que foram dirigidos por um certo diretor, George Lucas, a mente por trás da saga.

```java
package org.starlambdawars.finder;

import org.starlambdawars.beans.StarWarsMovie;

import java.util.function.Predicate;

public class DirectorPredicate implements Predicate<StarWarsMovie> {

    public DirectorPredicate(String director) {
        this.director = director;
    }

    @Override
    public boolean test(StarWarsMovie starWarsMovie) {
        return starWarsMovie.getDirector().equals(director);
    }

    private String director;
}
```

A classe acima mostra a implementação de um ```Predicate```.  O método test foi implementado e recebe um objeto do tipo ```StarWarMovie```, contendo todas as informações de um filme, incluindo o diretor. É necessário criar uma instância dessa classe toda vez que for desejado usá-la.

```java
public List<StarWarsMovie> findMovieByDirector(String director) {
    DirectorPredicate predicate = new DirectorPredicate(director);

    return movies
            .stream()
            .filter(m -> predicate.test(m))
            .collect(Collectors.toList());
}
```

Para começar a usar streams no Java8, o método ```stream()``` inicia a mágica. Por sua vez o método irá retornar uma instânca de ```Stream<R>``` representando o stream de objeto para ser manipulado. Legal, né?

O método ```filter``` recebe uma implementação de um ```Predicate``` como um parâmetro e retorna um ```Stream<R>```. Parece um  pouco complicado no começo, mas ao verificar os dois códigos, verifica-se que ambos combinam. Pode-se utilizar esse filtro customizado, utilizando o método ```test```.

Existe um outro modo de implementar a interface ```Predicate```. No Java 8, interfaces que possuem um método
podem ser implementados diretamente. Mas, como? Não é mais necessário criar mais uma classe concreta para isso, a implementação pode ocorrer diretamente na chamada do método usando a notação lambda do Java 8. Isso! Progredindo mais e mais! O código abaixo ilustra esse método:

```java
public List<StarWarsMovie> findMovieByDirector(String director) {
    return movies
            .stream()
            .filter(m -> m.getDirector().equals(director))
            .collect(Collectors.toList());
}
```

O que está ocorrendo aqui? Mágica pura! No método filter, temos uma arrow notation sendo utilizada para implementar um ```Predicate```. O símbolo ```m``` representa uma instância da classe ```StarWarsMovie``` e, por isso, pode-se ser chamado todos os métodos implementados, inclusive o método ```getDirector``` que obtém informação de diretor. Desse modo é possível usar o método ```equals``` para filtrar pelo diretor.

Ainda é possível encadear múltiplas chamadas de ```filter``` com o intuito de filtrar mais os dados. O código abaixo mostra o encadeamento em ação:

```java
movies
        .stream()
        .filter(m -> m.getDirector().equals(director))
        .filter(m -> m.getMainCharacters().contains(lukeSkywalker()))
        .filter(inThe80s())
        .collect(Collectors.toList())
        .forEach(m -> System.out.println(m.getTitle()));
```

O método ```lukeSkywalker()``` cria uma instância de StarWarsCharacter contendo o nome "Luke Skywalker". A implementação do método ```inThe80s()```, filtra por filmes que foram estreados na década de 80. A implementação dele seria:

```java
private static Predicate<StarWarsMovie> inThe80s() {
    LocalDate startDate = LocalDate.of(1980, Month.JANUARY, 1);
    LocalDate endDate = LocalDate.of(1989, Month.DECEMBER, 31);

    return m -> (m.getReleaseDate().isEqual(startDate) || m.getReleaseDate().isAfter(startDate))
            || (m.getReleaseDate().isEqual(endDate) || m.getReleaseDate().isBefore(endDate));
}
```

Nota-se o uso dos métodos ```collect``` e ```forEach```. Ambos serão discutidos mais para frente nesse artigo.

Veja os exemplos implementados no pacote ```org.starlambdawars.finder ``` para verificar a implmentação de um ```Predicate```. Sinta-se livre para clonar o repositório e realizar mudanças no código.

## Mappers

Mappers no Java 8 são conversores. Não estão relacionados com a estutura de dados ```Map```. O método ```map``` recebe uma implementação da interface ```java.util.function.Function``` que realiza a conversão. Assim como ```Predicate```, a interface ```Function``` possui um método para ser implmentado que é o método ```apply``` e outros métodos default e estáticos.

Os métodos default são utilizados para composição, mas infelizmente isso não será discutido nesse artigo. O método de classe se refere à uma função especial que é a função identidade (identity).

Os exemplos desse artigo são simples. Não são complexos. Estão aqui somente para introduzir a noção de mapas dentro de uma encadeamento de streams.

### Escrevendo uma Function

Se faz necessário obter uma lista de todos os filmes em uma coleção. Antes de Java 8, isso podia ser feito criando uma instância de ```List```, interando sobre a lista de todos filmes com um for-each (ou até um loop for tradicional) e adicionando cada item à lista criada.

Isso está parecendo muito trabalho, de fato!  Vamos deixar mais fácil.

A primeira maneira para solucionar, é implementar a interface ```Function```. Fácil! O código abaixo trata dessa abordagem:

```java
public class TitleFunction implements Function<StarWarsMovie, String> {

    @Override
    public String apply(StarWarsMovie starWarsMovie) {
        return starWarsMovie.getTitle();
    }
}
```

E essa função pode ser utilizada na chamada do método ```map``` no encadeamento de strems dessa maneira:

```java
public List<String> allTitles() {
    return movies
            .stream()
            .map(titleFunction)
            .collect(Collectors.toList());
}
```

No exemplo acima, a variável ```titleFunction``` é uma instância da classe ```TitleFunction``` implementada antes. Para facilitar as coisas, é possível utilizar a notação arrow function para implementar essa função. Observe o código abaixo:

```java
public List<String> allTitles() {
    return movies
            .stream()
            .map(m -> m.getTitle())
            .collect(Collectors.toList());
}
```

### ```flatMap``` e ```distinct```

Outra maneira de converter objetos é usar Flatmaps. O comportamento é parecido com o do map, mas retornará zero ou mais ocorrências. O código abaixo ilustra o uso de Flatmaps:

```java
public List<StarWarsCharacter> allCharacters() {
    return movies
            .stream()
            .map(l -> l.getMainCharacters())
            .collect(Collectors.toList())
            .stream()
            .flatMap(List::stream)
            .distinct()
            .collect(Collectors.toList());
}
```

O código retorna uma lista de todos os personagens de todos os filmes distintamente. Se um filme não possui personagens, nada será adicionado (como é o caso dos filmes da trilogia Qatsi). Star Wars possui muitos personagens memoráveis e a lista de personagens nunca retornará vazia.

Encadeando ```distinct()``` irá resultar em uma lista sem repetições. Para isso ser possível, o desenvolvedor deve implementar os métodos ```hashCode()``` e ```equals()``` com o intuito de obter melhores resultados.

Simples e divertido! Outra maneira de implementar uma função customizada é criar uma interface anotada com ```@FunctionalInterface```. Como os exemplos desse artigo não possui muitos exemplos complexos, não há exemplo desse recurso.

Veja os exemplos implementados no pacote ```org.starlambdawars.mapper```. Tente implementar funções para obter outras informações do conjunto de dados.

## Sorters

Quando se fala em ordenação, se pensa na interface ```java.util.Comparator```. O método chave no encadeamento de streams é o método ```sort```.

Foi adicionado à interface ```Comparator``` vários métodos default para deixar o desenvolvimento de um Comparator mais fácil. Não serão discutidos todos os métodos default nesse artigo, somente o método ```comparing```.

### Implementando um ```Comparator```

Implementar um Comparator não é uma tarefa complexa. Quem programa em Java há um tempo já deve ter implementado um. Por causa disso não será mostrada nesse artigo uma implmenetação dessa interface.

Existem duas maneiras de usar um Comparator: implementar usando a arrow notation ou usando o método default ```comparing```.

Vamos implementar um Comparator usando o campo ```chronologicalOrder```. Ordenando os filmes pela ordem cronológica, colocará os episódio em ordem crescente numérica de episódios do Star Wars. Veja o código abaixo:

```java
List<StarWarsMovie> myMovies = movies
        .stream()
        .sorted((m1, m2) -> m1.getChronologicalOrder() - m2.getChronologicalOrder())
        .collect(Collectors.toList());
```

A síntaxe é um pouco difereten de outras implementações, pois o método ```compare``` necessita de dois parâmetros, assim como se fosse implementada.

### Usando um ```Comparator```

Na interface ```Comparator``` existem vários métodos de classe que podem ser utilizados para evitar implementações desnecessárias. Um desses métodos é o método ```comparing```, que espera um objeto do tipo ```Function``` como parâmetro. Não é necessário implementar uma função para utilizá-lo, pode ser utilizada a notação double-colon (```::```) informando a classe e o nome do método, exemplo: ```Class::method```. Isso será convertido em função.

A implementação de outro exemplo, utilizando o campo ```releaseDate``` fica conforme trecho de código a seguir:

```java
List<StarWarsMovie> myMovies = movies
        .stream()
        .sorted(Comparator.comparing(StarWarsMovie::getReleaseDate))
        .collect(Collectors.toList());
```

### Invertendo uma lista

Seguindo o exemplo anterior, fica simples escrever um código para modificar a ordenação dos dados. Se faz necessário somente uma coisa: uma chamada para o método ```reversed()```.

```java
List<StarWarsMovie> myMovies = movies
        .stream()
        .sorted(Comparator.comparing(StarWarsMovie::getReleaseDate).reversed())
        .collect(Collectors.toList());
```

Com isso, ordenar dados fica fácil!

Veja o pacote ```org.starlambdawars.sorter``` para ver os exemplos implementados com Comparator para odenar dados. Modifique o campo ```personalOrder``` no arquivo de dados para ver qual o output do método ```personalOrderSorting()```.

## Collectors

Todos os exemplos terminam com uma chamada ao método ```collect```. Este é um método especial que encerra o ```Stream``` aberto pelo método ```stream()``` reduzindo para uma coleção.

Existe uma classe que facilita o uso desse método que é a classe utilitária ```Collectors```. Os três principais métodos dessa classe são:

1. ```toList``` que cria um ```List```
2. ```toSet``` que cria um ```Set```
3. ```toMap``` que cria um ```Map```

### ```toList``` e ```toSet```

Estes são métodos fáceis de usar. É só chamar um dos dois que irá resultar em um ```List``` ou um ```Set```. Mas lembre-se: ```Set``` é um tipo de coleção que **não** permite repetição, então, é necessário de implementar os métodos ```equals``` e ```hashCode``` na classe parametrizada antes de usar esses dois métodos.

```java
private List<String> findByForceAlignment(ForceAlignment alignment, List<StarWarsCharacter> characters) {
    return characters
            .stream()
            .filter(c -> c.getForceAlignment().equals(alignment))
            .map(c -> c.getName())
            .collect(Collectors.toList());
}
```

### ```toMap```

Para construir um ```Map``` são necessárias duas coisas: um tipo para a chave e um tipo para o valor. O método ```toMap``` necessita pelo menos de dois parâmetros:

1. uma ```Function``` que defina a chave
2. uma ```Function``` que defina o valor

No exemplo a seguir, o ```Map``` resultante irá conter uma chave enum, do enum ```ForceAlignment```, e o valor será uma lista de personagens. Primeiro é preciso transformar o stream ```StarWarsMovie```em um stream de ```ForceAlignment``` usando o método ```map```. Por fim, é necessário criar um stream distinto de ```ForceAlignment``` e realizar a chamada para o método ```collect``` para criar o ```Map```.

```java
public Map<ForceAlignment, List<String>> mapForceByCharacters() {
    return characters
            .stream()
            .map(f -> f.getForceAlignment())
            .distinct()
            .collect(
                    Collectors
                            .toMap(
                                    f -> f,
                                    f -> findByForceAlignment(f, characters)
                            )
            );
}
```

A chave será construída com uma função identidade que pode ser escrita como ```f -> f```. O valor deve ser uma lista de ```String``` criada pelo método ```findByForceAlignment```. A implementação do mesmo está na seção anterior.

## ```forEach```

Para finalizar o artigo, o método ```forEach``` implementa uma estrutura for-each. É muito simples de usar! O código abaixo mostra ele em ação:

```java
sorter
        .personalOrderSorting()
        .forEach(m -> System.out.println(m.getTitle()));
```

Nesse exemplo, o método ```forEach``` faz um loop em um stream de ```StarWarsMovies``` vindo do método ```personalOrderSorting()```. A classe que realizar esse loop, não necessita conhecer nada sobre a classe ```StarWarsMovie``` ou até mesmo importá-la se for utilizada por coisas simples. Como uma facilidade da versão 8, este método pode ser chamado por uma List ou um Set sem mesmo chamar o método ```stream()```.

## Conclusão

A API de streams, juntamente com os lambdas do Java 8, ajudam programadores a criar um código melhor e mais enxuto. Pode ser complicado no começo para assimilar, mas tudo ficará mais claro com um pouco mais de uso. Alguns programadores reclamam que Java é uma linguagem verbosa, mas com streams é possível simplificar o código como vistos nos exemplos. Sinta-se livre para clonar o repositório e aprender a partir dele Modifique os dados para realizar seus testes.


text:
RSpec.describe Spree::AbandonedCartService do
  let!(:abandoned_order) { create(:order, item_total: 1_00) }

  describe '#perform' do
    let(:future) { Time.current + SpreeAbandonedCarts::Config.abandoned_after_minutes.minutes + 1.second }

    it 'should touch abandoned order' do
      travel_to future do
        expect(Spree::AbandonedCartMailer).to receive(:abandoned_cart_email).with(abandoned_order).and_call_original

        expect { described_class.perform }.to change { abandoned_order.reload.abandoned_cart_email_sent_at }
      end
    end
  end
end


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('consultorio', '0041_auto_20180509_1139'),
    ]

    operations = [
        migrations.AddField(
            model_name='historiaclinica',
            name='otros_antecedentes',
            field=models.CharField(blank=True, max_length=300, null=True),
        ),
        migrations.AlterField(
            model_name='consulta',
            name='fecha_hora',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 670574)),
        ),
        migrations.AlterField(
            model_name='consulta',
            name='fecha_hora_egreso',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 670645)),
        ),
        migrations.AlterField(
            model_name='diagnosticoasignado',
            name='consulta',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
        ),
        migrations.AlterField(
            model_name='diagnosticoasignado',
            name='fecha_hora',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 672782)),
        ),
        migrations.AlterField(
            model_name='evoluciondiaria',
            name='consulta',
            field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
        ),
        migrations.AlterField(
            model_name='evoluciondiaria',
            name='fecha_hora',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 673639)),
        ),
        migrations.AlterField(
            model_name='historiaclinica',
            name='consulta',
            field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
        ),
        migrations.AlterField(
            model_name='historiaclinica',
            name='fecha_hora',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 671059)),
        ),
        migrations.AlterField(
            model_name='ordenmedica',
            name='consulta',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
        ),
        migrations.AlterField(
            model_name='ordenmedica',
            name='fecha_hora',
            field=models.DateTimeField(default=datetime.datetime(2018, 5, 17, 21, 13, 48, 673190)),
        ),
    ]


text:
package com.google.zxing.pdf417.detector;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.NotFoundException;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.DetectorResult;
import com.google.zxing.common.GridSampler;

import java.util.Arrays;
import java.util.Map;

/**
 *
Encapsulates logic that can detect a PDF417 Code in an image, even if the
 * PDF417 Code is rotated or skewed, or partially obscured.

 *
 * @author SITA Lab (kevin.osullivan@sita.aero)
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class Detector {

  private static final int MAX_AVG_VARIANCE = (int) ((1 << 8) * 0.42f);
  private static final int MAX_INDIVIDUAL_VARIANCE = (int) ((1 << 8) * 0.8f);
  private static final int SKEW_THRESHOLD = 2;

  // B S B S B S B S Bar/Space pattern
  // 11111111 0 1 0 1 0 1 000
  private static final int[] START_PATTERN = {8, 1, 1, 1, 1, 1, 1, 3};

  // 11111111 0 1 0 1 0 1 000
  private static final int[] START_PATTERN_REVERSE = {3, 1, 1, 1, 1, 1, 1, 8};

  // 1111111 0 1 000 1 0 1 00 1
  private static final int[] STOP_PATTERN = {7, 1, 1, 3, 1, 1, 1, 2, 1};

  // B S B S B S B S B Bar/Space pattern
  // 1111111 0 1 000 1 0 1 00 1
  private static final int[] STOP_PATTERN_REVERSE = {1, 2, 1, 1, 1, 3, 1, 1, 7};

  private final BinaryBitmap image;

  public Detector(BinaryBitmap image) {
    this.image = image;
  }

  /**
   *
Detects a PDF417 Code in an image, simply.

   *
   * @return {@link DetectorResult} encapsulating results of detecting a PDF417 Code
   * @throws NotFoundException if no QR Code can be found
   */
  public DetectorResult detect() throws NotFoundException {
    return detect(null);
  }

  /**
   *
Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.

   *
   * @param hints optional hints to detector
   * @return {@link DetectorResult} encapsulating results of detecting a PDF417 Code
   * @throws NotFoundException if no PDF417 Code can be found
   */
  public DetectorResult detect(Map<DecodeHintType,?> hints) throws NotFoundException {
    // Fetch the 1 bit matrix once up front.
    BitMatrix matrix = image.getBlackMatrix();

    // Try to find the vertices assuming the image is upright.
    ResultPoint[] vertices = findVertices(matrix);
    if (vertices == null) {
      // Maybe the image is rotated 180 degrees?
      vertices = findVertices180(matrix);
      if (vertices != null) {
        correctCodeWordVertices(vertices, true);
      }
    } else {
      correctCodeWordVertices(vertices, false);
    }

    if (vertices == null) {
      throw NotFoundException.getNotFoundInstance();
    }

    float moduleWidth = computeModuleWidth(vertices);
    if (moduleWidth < 1.0f) {
      throw NotFoundException.getNotFoundInstance();
    }

    int dimension = computeDimension(vertices[4], vertices[6],
        vertices[5], vertices[7], moduleWidth);
    if (dimension < 1) {
      throw NotFoundException.getNotFoundInstance();
    }

    // Deskew and sample image.
    BitMatrix bits = sampleGrid(matrix, vertices[4], vertices[5],
        vertices[6], vertices[7], dimension);
    return new DetectorResult(bits, new ResultPoint[]{vertices[5],
        vertices[4], vertices[6], vertices[7]});
  }

  /**
   * Locate the vertices and the codewords area of a black blob using the Start
   * and Stop patterns as locators.
   * TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER.
   *
   * @param matrix the scanned barcode image.
   * @return an array containing the vertices:
   *           vertices[0] x, y top left barcode
   *           vertices[1] x, y bottom left barcode
   *           vertices[2] x, y top right barcode
   *           vertices[3] x, y bottom right barcode
   *           vertices[4] x, y top left codeword area
   *           vertices[5] x, y bottom left codeword area
   *           vertices[6] x, y top right codeword area
   *           vertices[7] x, y bottom right codeword area
   */
  private static ResultPoint[] findVertices(BitMatrix matrix) {
    int height = matrix.getHeight();
    int width = matrix.getWidth();

    ResultPoint[] result = new ResultPoint[8];
    boolean found = false;

    int[] counters = new int[START_PATTERN.length];

    // Top Left
    for (int i = 0; i < height; i++) {
      int[] loc = findGuardPattern(matrix, 0, i, width, false, START_PATTERN, counters);
      if (loc != null) {
        result[0] = new ResultPoint(loc[0], i);
        result[4] = new ResultPoint(loc[1], i);
        found = true;
        break;
      }
    }
    // Bottom left
    if (found) { // Found the Top Left vertex
      found = false;
      for (int i = height - 1; i > 0; i--) {
        int[] loc = findGuardPattern(matrix, 0, i, width, false, START_PATTERN, counters);
        if (loc != null) {
          result[1] = new ResultPoint(loc[0], i);
          result[5] = new ResultPoint(loc[1], i);
          found = true;
          break;
        }
      }
    }

    counters = new int[STOP_PATTERN.length];

    // Top right
    if (found) { // Found the Bottom Left vertex
      found = false;
      for (int i = 0; i < height; i++) {
        int[] loc = findGuardPattern(matrix, 0, i, width, false, STOP_PATTERN, counters);
        if (loc != null) {
          result[2] = new ResultPoint(loc[1], i);
          result[6] = new ResultPoint(loc[0], i);
          found = true;
          break;
        }
      }
    }
    // Bottom right
    if (found) { // Found the Top right vertex
      found = false;
      for (int i = height - 1; i > 0; i--) {
        int[] loc = findGuardPattern(matrix, 0, i, width, false, STOP_PATTERN, counters);
        if (loc != null) {
          result[3] = new ResultPoint(loc[1], i);
          result[7] = new ResultPoint(loc[0], i);
          found = true;
          break;
        }
      }
    }
    return found ? result : null;
  }

  /**
   * Locate the vertices and the codewords area of a black blob using the Start
   * and Stop patterns as locators. This assumes that the image is rotated 180
   * degrees and if it locates the start and stop patterns at it will re-map
   * the vertices for a 0 degree rotation.
   * TODO: Change assumption about barcode location.
   * TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER.
   *
   * @param matrix the scanned barcode image.
   * @return an array containing the vertices:
   *           vertices[0] x, y top left barcode
   *           vertices[1] x, y bottom left barcode
   *           vertices[2] x, y top right barcode
   *           vertices[3] x, y bottom right barcode
   *           vertices[4] x, y top left codeword area
   *           vertices[5] x, y bottom left codeword area
   *           vertices[6] x, y top right codeword area
   *           vertices[7] x, y bottom right codeword area
   */
  private static ResultPoint[] findVertices180(BitMatrix matrix) {
    int height = matrix.getHeight();
    int width = matrix.getWidth();
    int halfWidth = width >> 1;

    ResultPoint[] result = new ResultPoint[8];
    boolean found = false;

    int[] counters = new int[START_PATTERN_REVERSE.length];

    // Top Left
    for (int i = height - 1; i > 0; i--) {
      int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE, counters);
      if (loc != null) {
        result[0] = new ResultPoint(loc[1], i);
        result[4] = new ResultPoint(loc[0], i);
        found = true;
        break;
      }
    }
    // Bottom Left
    if (found) { // Found the Top Left vertex
      found = false;
      for (int i = 0; i < height; i++) {
        int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE, counters);
        if (loc != null) {
          result[1] = new ResultPoint(loc[1], i);
          result[5] = new ResultPoint(loc[0], i);
          found = true;
          break;
        }
      }
    }

    counters = new int[STOP_PATTERN_REVERSE.length];

    // Top Right
    if (found) { // Found the Bottom Left vertex
      found = false;
      for (int i = height - 1; i > 0; i--) {
        int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE, counters);
        if (loc != null) {
          result[2] = new ResultPoint(loc[0], i);
          result[6] = new ResultPoint(loc[1], i);
          found = true;
          break;
        }
      }
    }
    // Bottom Right
    if (found) { // Found the Top Right vertex
      found = false;
      for (int i = 0; i < height; i++) {
        int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE, counters);
        if (loc != null) {
          result[3] = new ResultPoint(loc[0], i);
          result[7] = new ResultPoint(loc[1], i);
          found = true;
          break;
        }
      }
    }
    return found ? result : null;
  }

  /**
   * Because we scan horizontally to detect the start and stop patterns, the vertical component of
   * the codeword coordinates will be slightly wrong if there is any skew or rotation in the image.
   * This method moves those points back onto the edges of the theoretically perfect bounding
   * quadrilateral if needed.
   *
   * @param vertices The eight vertices located by findVertices().
   */
  private static void correctCodeWordVertices(ResultPoint[] vertices, boolean upsideDown) {
    float skew = vertices[4].getY() - vertices[6].getY();
    if (upsideDown) {
      skew = -skew;
    }
    if (skew > SKEW_THRESHOLD) {
      // Fix v4
      float length = vertices[4].getX() - vertices[0].getX();
      float deltax = vertices[6].getX() - vertices[0].getX();
      float deltay = vertices[6].getY() - vertices[0].getY();
      float correction = length * deltay / deltax;
      vertices[4] = new ResultPoint(vertices[4].getX(), vertices[4].getY() + correction);
    } else if (-skew > SKEW_THRESHOLD) {
      // Fix v6
      float length = vertices[2].getX() - vertices[6].getX();
      float deltax = vertices[2].getX() - vertices[4].getX();
      float deltay = vertices[2].getY() - vertices[4].getY();
      float correction = length * deltay / deltax;
      vertices[6] = new ResultPoint(vertices[6].getX(), vertices[6].getY() - correction);
    }

    skew = vertices[7].getY() - vertices[5].getY();
    if (upsideDown) {
      skew = -skew;
    }
    if (skew > SKEW_THRESHOLD) {
      // Fix v5
      float length = vertices[5].getX() - vertices[1].getX();
      float deltax = vertices[7].getX() - vertices[1].getX();
      float deltay = vertices[7].getY() - vertices[1].getY();
      float correction = length * deltay / deltax;
      vertices[5] = new ResultPoint(vertices[5].getX(), vertices[5].getY() + correction);
    } else if (-skew > SKEW_THRESHOLD) {
      // Fix v7
      float length = vertices[3].getX() - vertices[7].getX();
      float deltax = vertices[3].getX() - vertices[5].getX();
      float deltay = vertices[3].getY() - vertices[5].getY();
      float correction = length * deltay / deltax;
      vertices[7] = new ResultPoint(vertices[7].getX(), vertices[7].getY() - correction);
    }
  }

  /**
   *
Estimates module size (pixels in a module) based on the Start and End
   * finder patterns.

   *
   * @param vertices an array of vertices:
   *           vertices[0] x, y top left barcode
   *           vertices[1] x, y bottom left barcode
   *           vertices[2] x, y top right barcode
   *           vertices[3] x, y bottom right barcode
   *           vertices[4] x, y top left codeword area
   *           vertices[5] x, y bottom left codeword area
   *           vertices[6] x, y top right codeword area
   *           vertices[7] x, y bottom right codeword area
   * @return the module size.
   */
  private static float computeModuleWidth(ResultPoint[] vertices) {
    float pixels1 = ResultPoint.distance(vertices[0], vertices[4]);
    float pixels2 = ResultPoint.distance(vertices[1], vertices[5]);
    float moduleWidth1 = (pixels1 + pixels2) / (17 * 2.0f);
    float pixels3 = ResultPoint.distance(vertices[6], vertices[2]);
    float pixels4 = ResultPoint.distance(vertices[7], vertices[3]);
    float moduleWidth2 = (pixels3 + pixels4) / (18 * 2.0f);
    return (moduleWidth1 + moduleWidth2) / 2.0f;
  }

  /**
   * Computes the dimension (number of modules in a row) of the PDF417 Code
   * based on vertices of the codeword area and estimated module size.
   *
   * @param topLeft     of codeword area
   * @param topRight    of codeword area
   * @param bottomLeft  of codeword area
   * @param bottomRight of codeword are
   * @param moduleWidth estimated module size
   * @return the number of modules in a row.
   */
  private static int computeDimension(ResultPoint topLeft,
                                      ResultPoint topRight,
                                      ResultPoint bottomLeft,
                                      ResultPoint bottomRight,
                                      float moduleWidth) {
    int topRowDimension = round(ResultPoint.distance(topLeft, topRight) / moduleWidth);
    int bottomRowDimension = round(ResultPoint.distance(bottomLeft, bottomRight) / moduleWidth);
    return ((((topRowDimension + bottomRowDimension) >> 1) + 8) / 17) * 17;
  }

  private static BitMatrix sampleGrid(BitMatrix matrix,
                                      ResultPoint topLeft,
                                      ResultPoint bottomLeft,
                                      ResultPoint topRight,
                                      ResultPoint bottomRight,
                                      int dimension) throws NotFoundException {

    // Note that unlike the QR Code sampler, we didn't find the center of modules, but the
    // very corners. So there is no 0.5f here; 0.0f is right.
    GridSampler sampler = GridSampler.getInstance();

    return sampler.sampleGrid(
        matrix,
        dimension, dimension,
        0.0f, // p1ToX
        0.0f, // p1ToY
        dimension, // p2ToX
        0.0f, // p2ToY
        dimension, // p3ToX
        dimension, // p3ToY
        0.0f, // p4ToX
        dimension, // p4ToY
        topLeft.getX(), // p1FromX
        topLeft.getY(), // p1FromY
        topRight.getX(), // p2FromX
        topRight.getY(), // p2FromY
        bottomRight.getX(), // p3FromX
        bottomRight.getY(), // p3FromY
        bottomLeft.getX(), // p4FromX
        bottomLeft.getY()); // p4FromY
  }

  /**
   * Ends up being a bit faster than Math.round(). This merely rounds its
   * argument to the nearest int, where x.5 rounds up.
   */
  private static int round(float d) {
    return (int) (d + 0.5f);
  }

  /**
   * @param matrix row of black/white values to search
   * @param column x position to start search
   * @param row y position to start search
   * @param width the number of pixels to search on this row
   * @param pattern pattern of counts of number of black and white pixels that are
   *                 being searched for as a pattern
   * @param counters array of counters, as long as pattern, to re-use
   * @return start/end horizontal offset of guard pattern, as an array of two ints.
   */
  private static int[] findGuardPattern(BitMatrix matrix,
                                        int column,
                                        int row,
                                        int width,
                                        boolean whiteFirst,
                                        int[] pattern,
                                        int[] counters) {
    Arrays.fill(counters, 0, counters.length, 0);
    int patternLength = pattern.length;
    boolean isWhite = whiteFirst;

    int counterPosition = 0;
    int patternStart = column;
    for (int x = column; x < column + width; x++) {
      boolean pixel = matrix.get(x, row);
      if (pixel ^ isWhite) {
        counters[counterPosition]++;
      } else {
        if (counterPosition == patternLength - 1) {
          if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
            return new int[]{patternStart, x};
          }
          patternStart += counters[0] + counters[1];
          System.arraycopy(counters, 2, counters, 0, patternLength - 2);
          counters[patternLength - 2] = 0;
          counters[patternLength - 1] = 0;
          counterPosition--;
        } else {
          counterPosition++;
        }
        counters[counterPosition] = 1;
        isWhite = !isWhite;
      }
    }
    return null;
  }

  /**
   * Determines how closely a set of observed counts of runs of black/white
   * values matches a given target pattern. This is reported as the ratio of
   * the total variance from the expected pattern proportions across all
   * pattern elements, to the length of the pattern.
   *
   * @param counters observed counters
   * @param pattern expected pattern
   * @param maxIndividualVariance The most any counter can differ before we give up
   * @return ratio of total variance between counters and pattern compared to
   *         total pattern size, where the ratio has been multiplied by 256.
   *         So, 0 means no variance (perfect match); 256 means the total
   *         variance between counters and patterns equals the pattern length,
   *         higher values mean even more variance
   */
  private static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
    int numCounters = counters.length;
    int total = 0;
    int patternLength = 0;
    for (int i = 0; i < numCounters; i++) {
      total += counters[i];
      patternLength += pattern[i];
    }
    if (total < patternLength) {
      // If we don't even have one pixel per unit of bar width, assume this
      // is too small to reliably match, so fail:
      return Integer.MAX_VALUE;
    }
    // We're going to fake floating-point math in integers. We just need to use more bits.
    // Scale up patternLength so that intermediate values below like scaledCounter will have
    // more "significant digits".
    int unitBarWidth = (total << 8) / patternLength;
    maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> 8;

    int totalVariance = 0;
    for (int x = 0; x < numCounters; x++) {
      int counter = counters[x] << 8;
      int scaledPattern = pattern[x] * unitBarWidth;
      int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
      if (variance > maxIndividualVariance) {
        return Integer.MAX_VALUE;
      }
      totalVariance += variance;
    }
    return totalVariance / total;
  }

}


text:
This is the complete source code of the tiny todo app we built during the [basics tutorial](./README.md).

## Entry Point

#### `index.js`

```js
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'

let store = createStore(todoApp)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
```

## Action Creators

#### `actions/index.js`

```js
let nextTodoId = 0
export const addTodo = text => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

export const setVisibilityFilter = filter => {
  return {
    type: 'SET_VISIBILITY_FILTER',
    filter
  }
}

export const toggleTodo = id => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}
```

## Reducers

#### `reducers/todos.js`

```js
const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ]
    case 'TOGGLE_TODO':
      return state.map(todo =>
        (todo.id === action.id)
          ? {...todo, completed: !todo.completed}
          : todo
      )
    default:
      return state
  }
}

export default todos
```

#### `reducers/visibilityFilter.js`

```js
const visibilityFilter = (state = 'SHOW_ALL', action) => {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

export default visibilityFilter
```

#### `reducers/index.js`

```js
import { combineReducers } from 'redux'
import todos from './todos'
import visibilityFilter from './visibilityFilter'

const todoApp = combineReducers({
  todos,
  visibilityFilter
})

export default todoApp
```

## Presentational Components

#### `components/Todo.js`

```js
import React from 'react'
import PropTypes from 'prop-types'

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
  </li>
)

Todo.propTypes = {
  onClick: PropTypes.func.isRequired,
  completed: PropTypes.bool.isRequired,
  text: PropTypes.string.isRequired
}

export default Todo
```

#### `components/TodoList.js`

```js
import React from 'react'
import PropTypes from 'prop-types'
import Todo from './Todo'

const TodoList = ({ todos, onTodoClick }) => (
  <ul>
    {todos.map(todo => (
      <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} />
    ))}
  </ul>
)

TodoList.propTypes = {
  todos: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number.isRequired,
      completed: PropTypes.bool.isRequired,
      text: PropTypes.string.isRequired
    }).isRequired
  ).isRequired,
  onTodoClick: PropTypes.func.isRequired
}

export default TodoList
```

#### `components/Link.js`
```js
import React from 'react'
import PropTypes from 'prop-types'

const Link = ({ active, children, onClick }) => {
  if (active) {
    return <span>{children}</span>
  }

  return (
    <a
      href="#"
      onClick={e => {
        e.preventDefault()
        onClick()
      }}
    >
      {children}
    </a>
  )
}

Link.propTypes = {
  active: PropTypes.bool.isRequired,
  children: PropTypes.node.isRequired,
  onClick: PropTypes.func.isRequired
}

export default Link
```

#### `components/Footer.js`

```js
import React from 'react'
import FilterLink from '../containers/FilterLink'

const Footer = () => (
  <p>
    Show:
    {' '}
    <FilterLink filter="SHOW_ALL">
      All
    </FilterLink>
    {', '}
    <FilterLink filter="SHOW_ACTIVE">
      Active
    </FilterLink>
    {', '}
    <FilterLink filter="SHOW_COMPLETED">
      Completed
    </FilterLink>
  </p>
)

export default Footer
```

#### `components/App.js`

```js
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'

const App = () => (
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
)

export default App
```

## Container Components

#### `containers/VisibleTodoList.js`

```js
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = state => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = dispatch => {
  return {
    onTodoClick: id => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList
```

#### `containers/FilterLink.js`

```js
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'

const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onClick: () => {
      dispatch(setVisibilityFilter(ownProps.filter))
    }
  }
}

const FilterLink = connect(
  mapStateToProps,
  mapDispatchToProps
)(Link)

export default FilterLink
```

### Other Components

#### `containers/AddTodo.js`

```js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

let AddTodo = ({ dispatch }) => {
  let input

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          dispatch(addTodo(input.value))
          input.value = ''
        }}
      >
        <input
          ref={node => {
            input = node
          }}
        />
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}
AddTodo = connect()(AddTodo)

export default AddTodo
```


text:
from buildtest.utils.command import BuildTestCommand

class TestBuildTestCommand:
    def test_command(self):

        cmd = "hostname"
        a = BuildTestCommand(cmd)
        a.execute()

        out, err, ret = a.get_output(), a.get_error(), a.returncode

        print("Command: {cmd}")
        print(f"Output: {out}")
        print(f"Error: {err}")
        print(f"Return Code: {ret}")
        assert 0 == ret

    def test_error_command(self):

        cmd = "xyz"
        a = BuildTestCommand(cmd)
        a.execute()

        out, err, ret = a.get_output(), a.get_error(), a.returncode

        print("Command: {cmd}")
        print(f"Output: {out}")
        print(f"Error: {err}")
        print(f"Return Code: {ret}")

        assert 0 != ret


text:
"use strict";
import { shouldIgnoreNodeOfStrNode, strReporter } from "@textlint-rule/textlint-report-helper-for-google-preset";
import { classifyArticle } from "english-article-classifier";

const DocumentURL = "https://developers.google.com/style/articles";
const isCapital = text => {
    return /^[A-Z]/.test(text);
};
const report = (context, options = {}) => {
    const forceA = Array.isArray(options.a) ? options.a : [];
    const forceAn = Array.isArray(options.an) ? options.an : [];
    const classifyOptions = {
        forceA,
        forceAn
    };
    const dictionaries = [
        {
            pattern: /\b(a) ([\w.-]+)\b/i,
            test: ({ captures }) => {
                const result = classifyArticle(captures[1], classifyOptions);
                return result.type === "an";
            },
            replace: ({ captures }) => {
                const an = isCapital(captures[0]) ? "An" : "an";
                return `${an} ${captures[1]}`;
            },
            message: ({ captures }) => {
                const result = classifyArticle(captures[1], classifyOptions);
                return `Should be begin with "an"` + "\nReason: " + result.reason + "\n" + DocumentURL;
            }
        },
        {
            pattern: /\b(an) ([\w.-]+)\b/i,
            test: ({ captures }) => {
                const result = classifyArticle(captures[1], classifyOptions);
                return result.type === "a";
            },
            replace: ({ captures }) => {
                const a = isCapital(captures[0]) ? "A" : "a";
                return `${a} ${captures[1]}`;
            },
            message: ({ captures }) => {
                const result = classifyArticle(captures[1], classifyOptions);
                return `Should be begin with "a"` + "\nReason: " + result.reason + "\n" + DocumentURL;
            }
        }
    ];
    const { Syntax, RuleError, getSource, fixer, report } = context;
    return {
        [Syntax.Str](node) {
            if (shouldIgnoreNodeOfStrNode(node, context)) {
                return;
            }
            return strReporter({
                node,
                dictionaries,
                report,
                getSource,
                RuleError,
                fixer
            });
        }
    };
};
module.exports = {
    linter: report,
    fixer: report
};


text:
using Innovator.Client;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace InnovatorAdmin
{
  public static class Utils
  {
    public static ILogger Logger { get; set; }

    public static bool EndsWith(this IList<string> values, params string[] predicate)
    {
      if (predicate == null || predicate.Length < 1)
        return true;
      if (values.Count < predicate.Length)
        return false;
      var offset = values.Count - predicate.Length;
      for (var i = 0; i < predicate.Length; i++)
      {
        if (!string.Equals(values[i + offset], predicate[i]))
          return false;
      }
      return true;
    }

    public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
                  this IEnumerable<TSource> source, int size)
    {
      TSource[] bucket = null;
      var count = 0;

      foreach (var item in source)
      {
        if (bucket == null)
          bucket = new TSource[size];

        bucket[count++] = item;
        if (count != size)
          continue;

        yield return bucket;

        bucket = null;
        count = 0;
      }

      if (bucket != null && count > 0)
        yield return bucket.Take(count);
    }

    public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType)
    {
      if (source.Length == 0 || oldValue.Length == 0)
        return source;

      var result = new System.Text.StringBuilder();
      int startingPos = 0;
      int nextMatch;
      while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1)
      {
        result.Append(source, startingPos, nextMatch - startingPos);
        result.Append(newValue);
        startingPos = nextMatch + oldValue.Length;
      }
      result.Append(source, startingPos, source.Length - startingPos);

      return result.ToString();
    }

    public static void CopyTo(this TextReader reader, TextWriter writer)
    {
      var buffer = new char[4096];
      var cnt = reader.Read(buffer, 0, buffer.Length);
      while (cnt > 0)
      {
        writer.Write(buffer, 0, cnt);
        cnt = reader.Read(buffer, 0, buffer.Length);
      }
    }
    public static async Task CopyToAsync(this TextReader reader, TextWriter writer)
    {
      var buffer = new char[4096];
      var cnt = await reader.ReadAsync(buffer, 0, buffer.Length);
      while (cnt > 0)
      {
        await writer.WriteAsync(buffer, 0, cnt);
        cnt = await reader.ReadAsync(buffer, 0, buffer.Length);
      }
    }
    public static Control FindFocusedControl(this IContainerControl container)
    {
      Control control = null;
      while (container != null)
      {
        control = container.ActiveControl;
        container = control as IContainerControl;
      }
      return control;
    }

    public static IEnumerable<Control> ParentsAndSelf(this Control control)
    {
      var parent = control;
      while (parent != null)
      {
        yield return parent;
        parent = parent.Parent;
      }
    }

    public static string IndentXml(string xml)
    {
      string result;
      if (IndentXml(xml, out result) == null)
        return result;
      return xml;
    }

    /// <summary>
    /// Tidy the xml of the editor by indenting
    /// </summary>
    /// <param name="xml">Unformatted XML string</param>
    /// <returns>Formatted Xml String</returns>
    public static Exception IndentXml(string xml, out string formattedString)
    {
      try
      {
        var readerSettings = new XmlReaderSettings();
        readerSettings.IgnoreWhitespace = true;

        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.CheckCharacters = true;
        settings.CloseOutput = true;

        using (var reader = new StringReader(xml))
        using (var xmlReader = XmlReader.Create(reader, readerSettings))
        using (var writer = new StringWriter())
        using (var xmlWriter = XmlWriter.Create(writer, settings))
        {
          xmlWriter.WriteNode(xmlReader, true);
          xmlWriter.Flush();
          formattedString = writer.ToString();
        }

        return null;
      }
      catch (Exception ex)
      {
        Dialog.MessageDialog.Show(ex.Message);
        formattedString = string.Empty;
        return ex;
      }
    }

    public static string GroupConcat<T>(this IEnumerable<T> values, string separator, Func<T, string> renderer)
    {
      if (values.Any())
      {
        if (renderer == null)
        {
          return values.Select(v => v.ToString()).Aggregate((p, c) => p + separator + c);
        }
        return values.Select(renderer).Aggregate((p, c) => p + separator + c);
      }
      else
      {
        return string.Empty;
      }
    }

    public static void HandleError(Exception ex)
    {
      if (ex == null) return;

      Logger.LogError(ex, null);

      using (var dialog = new Dialog.MessageDialog())
      {
        if (ex is AggregateException agg
          && agg.Flatten().InnerExceptions.Count == 1)
        {
          ex = agg.Flatten().InnerExceptions[0];
        }

        dialog.Message = ex.Message;
        dialog.Details = ex.ToString();

        if (ex.Data.Count > 0)
        {
          dialog.Details += Environment.NewLine;
          foreach (var key in ex.Data.Keys)
          {
            dialog.Details += Environment.NewLine + $"{key} = {ex.Data[key]}";
          }
        }

        dialog.OkText = "&Keep Going";
        dialog.Caption = "Oops, that error wasn't expected";
        dialog.CaptionColor = System.Drawing.Color.Red;
        dialog.ShowDialog();
      }
    }

    //public static IEnumerable<Item> AsEnum(this Item item)
    //{
    //  for (var i = 0; i < item.getItemCount(); i++)
    //  {
    //    yield return item.getItemByIndex(i);
    //  }
    //}

    public static void UiThreadInvoke(this Control control, Action code)
    {
      if (control.InvokeRequired && (control.Parent != null || control is Form))
      {
        control.Invoke(code);
      }
      else
      {
        code.Invoke();
      }
    }

    public static string FormatXml(XmlNode node)
    {
      var settings = new XmlWriterSettings
      {
        OmitXmlDeclaration = true,
        Indent = true,
        IndentChars = "  "
      };

      using (var writer = new StringWriter())
      {
        using (var xml = XmlWriter.Create(writer, settings))
        {
          node.WriteTo(xml);
        }
        return writer.ToString();
      }
    }

    public static T AddAndReturn<T>(this XElement parent, T content)
    {
      parent.Add(content);
      return content;
    }

    public static void RemoveFilter<T>(this IList<T> list, Func<T, bool> predicate)
    {
      var i = 0;
      while (i < list.Count)
      {
        if (predicate(list[i]))
        {
          list.RemoveAt(i);
        }
        else
        {
          i++;
        }
      }
    }

    public static string AttributeValue(this XElement element, string attributeName)
    {
      var attr = element.Attribute(attributeName);
      if (attr == null) return null;
      return attr.Value;
    }

    public static IPromise<T> UiPromise<T>(this IPromise<T> promise, Control ctrl)
    {
      return promise.WithInvoker((d, a) => {
        if (ctrl.InvokeRequired)
          ctrl.Invoke(d, a);
        else
          d.DynamicInvoke(a);
      });
    }

    public static bool CellIsNull(this DataRow row, DataColumn col)
    {
      if (row.RowState == DataRowState.Deleted)
        return row.IsNull(col, DataRowVersion.Original);
      return row.IsNull(col);
    }
    public static bool CellIsNull(this DataRow row, string col)
    {
      return row.CellIsNull(row.Table.Columns[col]);
    }
    public static object CellValue(this DataRow row, DataColumn col)
    {
      if (row.RowState == DataRowState.Deleted)
        return row[col, DataRowVersion.Original];
      return row[col];
    }
    public static object CellValue(this DataRow row, string col)
    {
      if (row.RowState == DataRowState.Deleted)
        return row[col, DataRowVersion.Original];
      return row[col];
    }

    /// <summary>
    /// Call a method and wait synchronously for completion for at most <see cref="timeout"/>
    /// milliseconds
    /// </summary>
    /// <param name="timeout">Maximum time to wait in milliseconds</param>
    /// <param name="method">Method to execute</param>
    public static bool CallWithTimeout(int timeout, Action method)
    {
      using (var cts = new CancellationTokenSource())
      {
        cts.CancelAfter(timeout);
        Task.Run(method, cts.Token).Wait();
        return true;
      }
    }

    public static string PathEllipse(string path)
    {
      return Ellipsis(path, 400, new System.Drawing.Font("Arial", 9), TextFormatFlags.PathEllipsis);
    }
    public static string Ellipsis(string path, int width, float fontSize, TextFormatFlags FormatFlags)
    {
      return Ellipsis(path, width, new System.Drawing.Font("Arial", fontSize), FormatFlags);
    }
    public static string Ellipsis(string path, int width, System.Drawing.Font Font, TextFormatFlags formatFlags)
    {
      var result = string.Copy(path);
      TextRenderer.MeasureText(result, Font, new System.Drawing.Size(width, 0), formatFlags | TextFormatFlags.ModifyString);

      for (int index = 0; index <= result.Length - 1; index++)
      {
        if (result[index] == '\0')
        {
          return result.Substring(0, index);
        }
      }

      return result;
    }
    public static string URLEllipse(string path)
    {
      return Ellipsis(path.Replace('/', '\\'), 300, new System.Drawing.Font("Arial", 9), TextFormatFlags.PathEllipsis).Replace('\\', '/');
    }

  }
}


text:
/* global QUnit, fillIn */

import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';
import wait from 'ember-test-helpers/wait';

const tHelper = Ember.Helper.extend({
  compute: (params) => params[0]
});

const andHelper = Ember.Helper.extend({
  compute: (params) => params[0] && params[1]
});

import startApp from '../../../helpers/start-app';

QUnit.testStart(function () {
  window.App = startApp();
});

const webrtcService = Ember.Service.extend({
  canListDevices: true,
  cameraList: Ember.A(),
  microphoneList: Ember.A(),
  outputDeviceList: Ember.A(),
  resolutionList: Ember.A(),
  setOutputDevice: function () { return Ember.RSVP.resolve(); },
  enumerateDevices () { },
  enumerateResolutions () { }
});

const mockDevices = [
  { deviceId: 'foobarId', label: 'foobar label' },
  { deviceId: 'fizzbuzzId', label: 'fizzbuzz label' }
];

const mockResolutions = [
  { presetId: 1, label: 'low' },
  { presetId: 2, label: 'high' }
];

const renderDefault = function () {
  this.render(hbs`
        {{device-selection
          selectedCamera=camera
          selectedMicrophone=microphone
          selectedOutputDevice=outputDevice
          selectedResolution=resolution
          video=video
          audio=audio
          audioCallCapable=audioCallCapable
          videoCallCapable=videoCallCapable
          }}
    `);
};

const hasAudioSupport = function () {
  const audio = document.createElement('audio');
  return !!audio.play;
};

moduleForComponent('device-selection', 'Integration | Component | device selection', {
  integration: true,

  beforeEach: function () {
    this.register('helper:t', tHelper);
    this.register('helper:and', andHelper);
    this.register('service:webrtc', webrtcService);
    this.inject.service('webrtc', { as: 'webrtc' });
    this.renderDefault = renderDefault.bind(this);
    this.get('webrtc.resolutionList').clear();
    this.get('webrtc.cameraList').clear();
    this.get('webrtc.microphoneList').clear();
    this.get('webrtc.outputDeviceList').clear();
    this.set('camera', null);
    this.set('microphone', null);
    this.set('resolution', null);
    this.set('outputDevice', null);
    this.set('video', true);
    this.set('audio', true);
    this.set('audioCallCapable', true);
    this.set('videoCallCapable', true);
  }
});

test('it renders', function (assert) {
  // Set any properties with this.set('myProperty', 'value')
  // Handle any actions with this.on('myAction', function(val) { ... });"

  this.renderDefault();

  assert.equal(this.$('.options').length, 1);
});

test('it shows a message iff the browser cannot enumerate devices', function (assert) {
  this.set('webrtc.canListDevices', false);
  this.renderDefault();
  assert.equal(this.$('.browser-settings-message').length, 1);

  this.set('webrtc.canListDevices', true);
  this.renderDefault();
  assert.equal(this.$('.browser-settings-message').length, 0);
});

test('it shows a camera select and resolution select iff there are cameras, and video is true, and there are resolutions', function (assert) {
  Ember.run(this, function () {
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.set('webrtc.hasCamera', true);
    this.get('webrtc.resolutionList').pushObjects(mockResolutions);
    this.renderDefault();
  });

  assert.equal(this.$('select').length, 2);

  Ember.run(this, function () {
    this.get('webrtc.cameraList').clear();
    this.renderDefault();
  });

  assert.equal(this.$('select').length, 0);

  Ember.run(this, function () {
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.set('video', false);
    this.renderDefault();
  });

  assert.equal(this.$('select').length, 0);
});

test('it shows microphone select iff there are microphones and audio is true', function (assert) {
  Ember.run(this, function () {
    this.get('webrtc.microphoneList').pushObjects(mockDevices);
    this.set('webrtc.hasMicrophone', true);
    this.renderDefault();
  });

  assert.equal(this.$('select').length, 1);

  Ember.run(this, function () {
    this.get('webrtc.microphoneList').pushObjects(mockDevices);
    this.set('audio', false);
    this.renderDefault();
  });

  assert.equal(this.$('select').length, 0);
});

test('it shows a troubleshoot button if an openTroubleshoot action is provided', function (assert) {
  const done = assert.async();
  this.renderDefault();
  assert.equal(this.$('button').length, 0);

  this.actions = {
    dummyAction: function () {
      done();
    }
  };

  this.render(hbs`
    {{device-selection openTroubleshoot=(action "dummyAction") troubleshoot=false}}
  `);

  assert.equal(this.$('button').length, 0);

  this.render(hbs`
    {{device-selection openTroubleshoot=(action "dummyAction")}}
  `);

  assert.equal(this.$('button').length, 1);
  this.$('button').trigger('click');
});

test('it should start with specified camera', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.set('webrtc.hasCamera', true);
    this.set('camera', mockDevices[0]);
    this.renderDefault();

    assert.equal(this.$('select').val(), mockDevices[0].deviceId);
    assert.equal(this.$('select option:selected').text(), mockDevices[0].label);

    this.set('camera', mockDevices[1]);
    this.renderDefault();

    assert.equal(this.$('select').val(), mockDevices[1].deviceId);
    assert.equal(this.$('select option:selected').text(), mockDevices[1].label);
  });
});

test('it should start with specified mic', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.microphoneList').pushObjects(mockDevices);
    this.set('webrtc.hasMicrophone', true);
    this.set('microphone', mockDevices[0]);
    this.renderDefault();

    assert.equal(this.$('select').val(), mockDevices[0].deviceId);
    assert.equal(this.$('select option:selected').text(), mockDevices[0].label);

    this.set('microphone', mockDevices[1]);
    this.renderDefault();

    assert.equal(this.$('select').val(), mockDevices[1].deviceId);
    assert.equal(this.$('select option:selected').text(), mockDevices[1].label);
  });
});

test('it should start with specified outputDevice', function (assert) {
  return Ember.run(this, function () {
    if (!hasAudioSupport()) {
      return assert.expect(0);
    }

    this.get('webrtc.outputDeviceList').pushObjects(mockDevices);
    this.set('outputDevice', mockDevices[0]);
    this.renderDefault();

    assert.equal(this.$('select[id*="-speakers-select"]').val(), mockDevices[0].deviceId);
    assert.equal(this.$('select[id*="-speakers-select"] option:selected').text(), mockDevices[0].label);

    this.set('outputDevice', mockDevices[1]);
    this.renderDefault();

    assert.equal(this.$('select[id*="-speakers-select"]').val(), mockDevices[1].deviceId);
    assert.equal(this.$('select[id*="-speakers-select"] option:selected').text(), mockDevices[1].label);
  });
});

test('it should show a system default message if there are no output devices listed', function (assert) {
  return Ember.run(this, function () {
    if (!hasAudioSupport()) {
      return assert.expect(0);
    }

    this.set('webrtc.outputDeviceList', []);
    this.renderDefault();

    assert.equal(this.$('.system-default-message').length, 1);
  });
});

test('it should start with specified resolution', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.resolutionList').pushObjects(mockResolutions);
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.set('resolution', mockResolutions[0]);
    this.renderDefault();

    assert.equal(this.$('select[id*="-resolution-select"]').val(), mockResolutions[0].presetId);
    assert.equal(this.$('select[id*="-resolution-select"] option:selected').text(), mockResolutions[0].label);

    this.set('resolution', mockResolutions[1]);
    this.renderDefault();

    assert.equal(this.$('select[id*="-resolution-select"]').val(), mockResolutions[1].presetId);
    assert.equal(this.$('select[id*="-resolution-select"] option:selected').text(), mockResolutions[1].label);
  });
});

test('it should change camera', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.set('webrtc.hasCamera', true);
    this.set('camera', mockDevices[0]);
    this.renderDefault();

    const select = this.$('select');
    assert.equal(select.val(), mockDevices[0].deviceId);

    return fillIn('select', mockDevices[1].deviceId).then(() => {
      assert.equal(this.get('camera'), mockDevices[1]);
      this.get('webrtc.cameraList').clear();
    });
  });
});

test('it should change mic', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.microphoneList').pushObjects(mockDevices);
    this.set('webrtc.hasMicrophone', true);
    this.set('microphone', mockDevices[0]);
    this.renderDefault();

    const select = this.$('select');
    assert.equal(select.val(), mockDevices[0].deviceId);

    return fillIn('select', mockDevices[1].deviceId).then(() => {
      assert.equal(this.get('microphone'), mockDevices[1]);
    });
  });
});

test('it should change resolution', function (assert) {
  return Ember.run(this, function () {
    this.get('webrtc.cameraList').pushObjects(mockDevices);
    this.get('webrtc.resolutionList').pushObjects(mockResolutions);
    this.renderDefault();

    const select = this.$('select[id*="-resolution-select"]');
    assert.equal(select.val(), mockResolutions[0].presetId);

    return fillIn('select[id*="-resolution-select"]', mockResolutions[1].presetId).then(() => {
      assert.equal(this.get('resolution'), mockResolutions[1]);
    });
  });
});

test('it should change outputDevice', function (assert) {
  return Ember.run(this, function () {
    if (!hasAudioSupport()) {
      return assert.expect(0);
    }
    this.get('webrtc.outputDeviceList').pushObjects(mockDevices);
    this.set('audio', true);
    this.renderDefault();

    const select = this.$('select[id*="-speakers-select"]');
    assert.equal(select.val(), mockDevices[0].deviceId);

    return fillIn('select[id*="-speakers-select"]', mockDevices[1].deviceId).then(() => {
      assert.equal(this.get('outputDevice'), mockDevices[1]);
    });
  });
});

test('playTestSound | should not set the output device if there was not one provided', function (assert) {
  const webrtc = this.get('webrtc');
  this.set('outputDevice', null);
  this.renderDefault();
  sinon.stub(webrtc, 'setOutputDevice').returns(Ember.RSVP.resolve());
  this.$('.play-sound-btn').click();
  return wait()
    .then(() => {
      sinon.assert.notCalled(webrtc.setOutputDevice);
      assert.expect(0);
    });
});

test('playTestSound | should set the output device if there was one selected', function (assert) {
  const webrtc = this.get('webrtc');
  this.set('outputDevice', {});
  this.renderDefault();
  sinon.stub(webrtc, 'setOutputDevice').returns(Ember.RSVP.resolve());
  this.$('.play-sound-btn').click();
  return wait()
    .then(() => {
      const audio = this.$('audio');
      if (audio.play) {
        // the test can't run if audio.play is not available
        sinon.assert.calledOnce(webrtc.setOutputDevice);
        assert.expect(0);
      } else {
        assert.ok('unsupported browser for test');
      }
    });
});


text:
/* global require, module */

const DEBUG = false;

function buildQUnitTree(app) {
  const funnel = require('broccoli-funnel');
  const concat = require('broccoli-concat');
  const replace = require('broccoli-string-replace');
  const mergeTrees = require('broccoli-merge-trees');
  const babelTranspiler = require('broccoli-babel-transpiler');
  const Rollup = require('broccoli-rollup');
  const path = require('path');
  const babelOpts = require('./babel-opts');
  const typeScriptOpts = require('./typescript-opts');
  const { debug } = require('broccoli-stew');

  let preprocessJs = app.registry.registry.js[0].toTree;

  let buildPreprocessedAddon = function(addonName, dir) {
    return preprocessJs(path.dirname(require.resolve(addonName)) + '/' + dir, {
      registry: app.registry
    });
  };

  let waitersTree = buildPreprocessedAddon('ember-test-waiters', 'addon');
  let qunitTree = buildPreprocessedAddon('ember-qunit', 'addon-test-support');
  let testHelpersTreeForQUnit = buildPreprocessedAddon('@ember/test-helpers', 'addon-test-support');

  if (DEBUG) {
    waitersTree = debug(waitersTree)
  }

  let testLoaderTreeForQUnit = funnel("node_modules/ember-cli-test-loader/addon-test-support", {
    files: ['index.js']
  });

  testLoaderTreeForQUnit = new Rollup(testLoaderTreeForQUnit, {
    rollup: {
      input: 'index.js',
      output: {
        file: 'ember-cli-test-loader/test-support/index.js',
        format: 'es'
      },
      plugins: [
        require('@rollup/plugin-commonjs')()
      ]
    }
  });

  waitersTree = babelTranspiler(waitersTree, typeScriptOpts({
    addonName: 'ember-test-waiters'
  }));
  qunitTree = babelTranspiler(qunitTree, babelOpts());
  testHelpersTreeForQUnit = babelTranspiler(testHelpersTreeForQUnit, babelOpts());
  testLoaderTreeForQUnit = babelTranspiler(testLoaderTreeForQUnit, babelOpts());

  if (DEBUG) {
    waitersTree = debug(waitersTree)
  }

  // TODO: figure out why we need this hack and remove it
  waitersTree = replace(waitersTree, {
    files: ['**/*.js'],
    pattern: {
      match: /_types\.(\w+)/g,
      replacement: "void 0"
    }
  });

  if (DEBUG) {
    waitersTree = debug(waitersTree)
  }

  let finalQUnitTree = concat(mergeTrees([waitersTree, qunitTree, testHelpersTreeForQUnit, testLoaderTreeForQUnit]), {
    inputFiles: ['**/*.js'],
    outputFile: '/assets/ember-qunit.js'
  });

  if (DEBUG) {
    finalQUnitTree = debug(finalQUnitTree);
  }

  return finalQUnitTree;
}

module.exports = buildQUnitTree;


text:
@interface AppDelegate : NSObject <NSApplicationDelegate> {
    TwitterController *twitter;
}
@property (weak) IBOutlet NSTextField *consumerKey;
@property (weak) IBOutlet NSTextField *consumerSecret;
@property (weak) IBOutlet NSTextField *accessToken;

@property (weak) IBOutlet NSTextField *accessTokenSecret;

- (IBAction)startButton:(id)sender;

@end


text:
package com.hazelcast.map.impl.mapstore.writebehind.entry;

import com.hazelcast.map.MapStore;

import javax.annotation.Nullable;
import java.util.UUID;

/**
 * General contract for an entry to be stored into {@link MapStore}
 * when {@link com.hazelcast.config.MapStoreConfig#writeDelaySeconds} is greater than 0.
 *
 * @param <K> the key type.
 * @param <V> the value type.
 * @see AddedDelayedEntry
 * @see DeletedDelayedEntry
 * @see NullValueDelayedEntry
 */
public interface DelayedEntry<K, V> {

    K getKey();

    V getValue();

    long getExpirationTime();

    long getStoreTime();

    int getPartitionId();

    void setStoreTime(long storeTime);

    void setSequence(long sequence);

    long getSequence();

    void setTxnId(UUID txnId);

    @Nullable
    UUID getTxnId();
}


text:
/**
 * parseGcloudIgnore parses a gcloud ignore at the given filepath. It follows
 * the parsing rules defined at
 * https://cloud.google.com/sdk/gcloud/reference/topic/gcloudignore, including
 * parsing any included files.
 *
 * @param pth Path to the gcloudignore file.
 * @return Ordered list of strings from the various ignore files.
 */
export declare function parseGcloudIgnore(pth: string): Promise<string[]>;


text:
package candr.yoclip.option;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.junit.Test;

import candr.yoclip.OptionsBadTypeException;
import candr.yoclip.OptionsParseException;
import candr.yoclip.annotation.Arguments;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

/**
 * {@link ArgumentsSetter} unit tests.
 */
public class ArgumentsSetterTest {

    // The test case.
    interface BeanSetter {
        @Arguments(required = true,
                   description = {
                           "arguments",
                           "testField"
                   },
                   usage = {
                           "arguments",
                           "\n",
                           "usage"
                   }
        )
        public void setArgument(String argument);

        @Arguments
        public void setTooManyArguments(String one, String two);

        @Arguments
        public void notEnoughArguments();

        @Arguments
        public void setWrongType(Integer bad);
    }

    final private ArgumentsSetter<BeanSetter> test;

    public ArgumentsSetterTest() throws NoSuchMethodException {
        final Method setter = BeanSetter.class.getDeclaredMethod("setArgument", String.class);
        final Arguments arguments = setter.getAnnotation(Arguments.class);
        test = new ArgumentsSetter<BeanSetter>(arguments, setter);
    }

    @Test(expected = IllegalArgumentException.class)
    public void initWithNullSetter() throws NoSuchMethodException {
        final Arguments mockArguments = mock(Arguments.class);
        new ArgumentsSetter<BeanSetter>(mockArguments, null);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void initWithTooManyArguments() throws NoSuchMethodException {
        final Method setter = BeanSetter.class.getDeclaredMethod("setTooManyArguments", String.class, String.class);
        final Arguments mockArguments = mock(Arguments.class);
        new ArgumentsSetter<BeanSetter>(mockArguments, setter);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void initWithNotEnoughArguments() throws NoSuchMethodException {
        final Method setter = BeanSetter.class.getDeclaredMethod("notEnoughArguments");
        final Arguments mockArguments = mock(Arguments.class);
        new ArgumentsSetter<BeanSetter>(mockArguments, setter);
    }

    @Test(expected = IllegalArgumentException.class)
    public void initWithWrongType() throws NoSuchMethodException {
        final Method setter = BeanSetter.class.getDeclaredMethod("setWrongType", Integer.class);
        final Arguments mockArguments = mock(Arguments.class);
        new ArgumentsSetter<BeanSetter>(mockArguments, setter);
    }

    @Test
    public void getNames() {
        assertThat("names", test.getNames().length, is(0));
    }

    @Test
    public void hasValue() {
        assertThat("value", test.hasValue(), is(false));
    }

    @Test
    public void isHelp() {
        assertThat("help", test.isHelp(), is(false));
    }

    @Test
    public void isProperties() {
        assertThat("properties", test.isProperties(), is(false));
    }

    @Test
    public void getUsage() {
        assertThat("unexpected usage", test.getUsage(), is("arguments\nusage"));
    }

    @Test
    public void getDescription() {
        assertThat("unexpected description", test.getDescription(), is("arguments testField"));
    }

    @Test
    public void getPropertyDescriptions() {
        assertThat("unexpected property descriptions", test.getPropertyDescriptions().isEmpty(), is(true));
    }

    @Test
    public void isRequired() {
        assertThat("required", test.isRequired(), is(true));
    }

    @Test
    public void isArguments() {
        assertThat("arguments", test.isArguments(), is(true));
    }

    @Test
    public void testSetOption() {
        final BeanSetter mock = mock(BeanSetter.class);
        test.setOption(mock, "foobar");
        verify(mock).setArgument("foobar");

        reset(mock);
        test.setOption(mock, null);
        verify(mock).setArgument(null);
    }

    @Test
    public void getDeclaringClass() {
        assertTrue("unexpected declaring class " + test.getDeclaringClass(), test.getDeclaringClass().equals(BeanSetter.class));
    }

    @Test
    public void getType() {
        assertTrue("unexpected type " + test.getType(), test.getType().equals(String.class));
    }

    @Test
    public void getUniqueId() {
        assertTrue("unexpected unique ID " + test.getUniqueId(), test.getUniqueId().equals("setArgument"));
        assertTrue("unexpected toString() " + test.toString(), test.toString().equals(test.getUniqueId()));
    }

    @Test(expected = OptionsParseException.class)
    public void testSetOptionWithException() {
        final BeanSetter mock = mock(BeanSetter.class);
        doThrow(new RuntimeException()).when(mock).setArgument("foobar");
        test.setOption(mock, "foobar");
    }

}


text:
r"""GRef dataset.
"""
from __future__ import annotations

import collections
import json

from tensorflow_datasets.core.utils.lazy_imports_utils import tensorflow as tf
import tensorflow_datasets.public_api as tfds

_DESCRIPTION = """
The Google RefExp dataset is a collection of text descriptions of objects in
images which builds on the publicly available MS-COCO dataset. Whereas the
image captions in MS-COCO apply to the entire image, this dataset focuses on
text descriptions that allow one to uniquely identify a single object or region
within an image. See more details in this paper: Generation and Comprehension
of Unambiguous Object Descriptions.
"""

_CITATION = """
@inproceedings{mao2016generation,
  title={Generation and Comprehension of Unambiguous Object Descriptions},
  author={Mao, Junhua and Huang, Jonathan and Toshev, Alexander and Camburu, Oana and Yuille, Alan and Murphy, Kevin},
  booktitle={CVPR},
  year={2016}
}
"""

def _build_bbox(image_info, x, y, width, height):
  return tfds.features.BBox(
      ymin=y / image_info['height'],
      xmin=x / image_info['width'],
      ymax=(y + height) / image_info['height'],
      xmax=(x + width) / image_info['width'],
  )

def _combine_gref_anns(gref_anns):
  """Reorganize G-Ref by matching annotations to image_id.

  Also map referring expressions to annotation id.
  Args:
    gref_anns: a dict of gref_anns annotations.

  Returns:
    combine_anns: a list of dict based on gref_anns['images'].
      Each dict has a key 'instances' corresponding to a list of annotations
      of that image.
  """
  img_id2annotations = collections.defaultdict(list)
  for _, v in gref_anns['annotations'].items():
    # Add ref expression to annotation.
    # this adds the referent, the raw string, tokens, and the referring
    # expression id to the annotation.
    ref_list = []
    for rexp_id in sorted(v['refexp_ids']):
      r = gref_anns['refexps'][str(rexp_id)]
      if 'word' in r['parse']['referent']:
        r['referent'] = r['parse']['referent']['word']
      else:
        r['referent'] = ''
      r.pop('parse')
      ref_list.append(r)

    v['refexps'] = ref_list
    img_id2annotations[int(v['image_id'])].append(v)

  img_id2annotations = {
      k: list(sorted(v, key=lambda a: a['annotation_id']))
      for k, v in img_id2annotations.items()
  }
  combined_anns = []
  for _, v in gref_anns['images'].items():
    v['instances'] = img_id2annotations[v['image_id']]
    combined_anns.append((v['image_id'], v))

  combined_anns = sorted(combined_anns, key=lambda a: a[0])
  return combined_anns

class Gref(tfds.core.GeneratorBasedBuilder):
  """DatasetBuilder for gref dataset."""

  VERSION = tfds.core.Version('1.0.0')
  RELEASE_NOTES = {
      '1.0.0': 'Initial release.',
  }
  MANUAL_DOWNLOAD_INSTRUCTIONS = """
    Follow instructions at https://github.com/mjhucla/Google_Refexp_toolbox
    to download and pre-process the data into aligned format with COCO.
    The directory contains 2 files and one folder:
    * google_refexp_train_201511_coco_aligned_catg.json
    * google_refexp_val_201511_coco_aligned_catg.json
    * coco_train2014/

    The coco_train2014 folder contains all of COCO 2014 training images.
    """

  def _info(self) -> tfds.core.DatasetInfo:
    """Returns the dataset metadata."""
    return tfds.core.DatasetInfo(
        builder=self,
        # Description and homepage used for documentation
        description=_DESCRIPTION,
        homepage='https://github.com/mjhucla/Google_Refexp_toolbox',
        features=tfds.features.FeaturesDict({
            'image':
                tfds.features.Image(encoding_format='jpeg'),
            'image/id':
                tf.int64,
            'objects':
                tfds.features.Sequence({
                    'id': tf.int64,
                    'area': tf.int64,
                    'bbox': tfds.features.BBoxFeature(),
                    'label': tf.int64,
                    'label_name': tfds.features.ClassLabel(num_classes=80),
                    'refexp': tfds.features.Sequence({
                        'refexp_id': tf.int64,
                        'tokens': tfds.features.Sequence(tfds.features.Text()),
                        'referent': tfds.features.Text(),
                        'raw': tfds.features.Text()}),
                }),
        }),
        # If there's a common `(input, target)` tuple from the features,
        # specify them here. They'll be used if as_supervised=True in
        # builder.as_dataset.
        supervised_keys=None,
        # Bibtex citation for the dataset
        citation=_CITATION,
    )

  def _split_generators(self, dl_manager):
    coco_image_dir = dl_manager.manual_dir / 'coco_train2014'
    gref_aligned_json_train = dl_manager.manual_dir / (
        'google_refexp_train_201511_coco_aligned_catg.json')
    gref_aligned_json_val = dl_manager.manual_dir / (
        'google_refexp_val_201511_coco_aligned_catg.json')
    # Specify the splits
    return {
        tfds.Split.TRAIN: self._generate_examples(
            coco_image_dir, gref_aligned_json_train,
        ),
        tfds.Split.VALIDATION: self._generate_examples(
            coco_image_dir, gref_aligned_json_val,
        ),
    }

  def _generate_examples(self, image_dir, gref_aligned_json):
    """Yields examples."""
    gref_anns = json.loads(gref_aligned_json.read_text())

    categories_id2name = {c['id']: c['name'] for c in gref_anns['categories']}
    self.info.features['objects']['label_name'].names = [
        c['name'] for c in gref_anns['categories']
    ]
    gref_anns = _combine_gref_anns(gref_anns)
    for image_id, image_ann in gref_anns:
      image_path = image_dir / image_ann['file_name']
      example = {
          'image': image_path,
          'image/id': image_id,
          'objects': [],
      }
      for inst in image_ann['instances']:
        # build instance dictionary
        example['objects'].append({
            'id': inst['annotation_id'],
            'area': inst['area'],
            'bbox': _build_bbox(image_ann, *inst['bbox']),
            'label': inst['category_id'],  # 1-index.
            'label_name': categories_id2name[inst['category_id']],
            'refexp': inst['refexps'],
        })
      yield image_id, example


text:
var test = require('tape');
var tryit = require('../tryit');

test('basic functionality', function (t) {
    var count = 0;

    var noOp = function () {};
    var throwsError = function () {
        throw new Error('whammo');
    };
    tryit(noOp, function (e) {
        t.ok(e == null, 'should be called without an error');
    });

    tryit(throwsError, function (e) {
        t.ok('should be called');
        t.ok(e instanceof Error);
    });

    t.end();
});

test('handle case where callback throws', function (t) {
    var count = 0;

    t.throws(function () {
        tryit(function () {}, function(e) {
            count++;
            t.equal(count, 1, 'should be called once');
            throw new Error('kablowie');
        });
    }, 'should throw once');

    t.end();
});


text:
import { v4 } from 'node-uuid'

export const ADD_RECIPE = 'ADD_RECIPE';
export const EDIT_RECIPE = 'EDIT_RECIPE';
export const DELETE_RECIPE = 'DELETE_RECIPE';
export const DELETE_INGREDIENT = 'DELETE_INGREDIENT';
/* action creators */

export function addRecipe(name, ingredients, imageURL) {
  return {
    type: ADD_RECIPE,
    id: v4(),
    name,
    ingredients,
    imageURL
  };
}

export function editRecipe(id, name, ingredients, imageURL){
  return{
    type: EDIT_RECIPE,
    id,
    name,
    ingredients,
    imageURL
  }
}

export function deleteRecipe(id){
  return{
    type: DELETE_RECIPE,
    id
  }
}