text:
<?php
declare(strict_types = 1);
namespace FireflyIII\Helpers\Csv\Mapper;

/**
 * Interface MapperInterface
 *
 * @package FireflyIII\Helpers\Csv\Mapper
 */
interface MapperInterface
{
    /**
     * @return array
     */
    public function getMap(): array;
}


text:
/* O formato do CSS é:

selector {
	property:value;
}

Sendo que o selector representa qualquer tag HTML. Dessa forma, ao invés de formatar todo título H1 individualmente, usamos o seguinte CSS para formatar todos de uma vez só. Assim, toda tag h1 que for utilizada no HTML, será formatada com a fonte Arial: */
h1 {
	font-family:Arial;
}

/* Toda tag p do html será formatado com a cor azul. */
p {
	color:blue;
}

/* Toda tag span do html será formatado com a cor verde e em negrito. */
span {
	color:green;
	font-weight:bold;
}

/* Quando uma tag possui um id, ele é referenciado aqui com #. O ID significa uma formatação única para determinada situação. Cada página HTML pode ter somente uma tag usando este ID. */
#sou-unico {
	/* Use cores em hexadecimal para obter mais variedades. */
	background-color:#FFD700;
	color:#000000;
	font-family:Courier;
}

/* Quando uma tag possui uma classe, ela é referenciada aqui com um ponto. As classes podem ser reutilizadas quantas vezes for necessário por diversas tags por página HTML. */
.listas {
	/* Informar mais de uma fonte, significa que o navegador tentará usar a primeira que foi informada, caso não consiga ele vai tentar usar a segunda e assim sucessivamente. */
	font-family:Garamond, Arial, sans-serif;
	font-size:15px;
}

/* A seguinte formatação será feita na tag span que está dentro da classe 'listas' apenas. O CSS vai dar preferência sempre para o código mais detalhado. Sendo assim, o código a seguir vai sobrescrever o que já foi definido para a tag span (mais acima nesse documento). */
.listas span {
	font-size:2em;
	color:red;
}

/* Formatação da classe 'primeira_div' */
.primeira-div {
	background-color:blue;
	/* Largura */
	width:150px;
	/* Altura */
	height:150px;
}

/* Isso significa que toda tag 'p' que está dentro da classe 'primeira_div' vai ser formatada da seguinte forma. Sendo assim, isso sobrescreverá a formatação da tag 'p' que foi declarada acima. */
.primeira-div > p {
	color:white;
	text-align:center;
	padding-top:50px;
}

/* O parâmetro border suporta mais de um valor (tamanho, formato e cor). */
.borda {
	border:2px dotted green;
}

/* Formatação do link, cujo id é 'link_principal'. Na formatação de links, existem as pseudo-classes, que nos permite formatar não somente o link, mas também seu estado:
- link = link normal, não visitado;
- hover = quando o mouse está sobre o link;
- visited = um link que o usuário já visitou;
- active = link no momento em que é clicado. */
#link-principal:link {
	/* Com o parâmetro text decoration você indica se quer o sublinhado abaixo, acima, cortado ou nada. */
	text-decoration:none;
	font-size:20px;
	font-family:Courier, sans-serif;
	background-color:blue;
	color:white;
	font-weight:bold;
	/* Com text transform você pode dizer se quer o texto maiúsculo ou minúsculo. */
	text-transform:uppercase;
}

#link-principal:hover {
	background-color:green;
}

#link-principal:visited {
	color:white;
}

#link-principal:active {
	font-weight: normal;
}
/* Formatação da div (botao-twitter + a (link-twitter) + span (span-twitter) usadas no botão do Twitter */
.botao-twitter {
	/* A tag border-radius arredonda a borda de acordo com o número informado. Sendo que border-radius:100% é um círculo. */
	border-radius:4px;
	border:1px solid #4169E1;
	background-color:#87CEEB;
	width:100px;
	height:50px;
	text-align:center;
	/* margin:auto é usada para dizer ao navegador que queremos a mesma margem em todo esse elemento. Sendo assim, esse elemento será centralizado na página. É o equivalente de text-align:center (mas esse é usado somente para elementos de texto). */
	margin:auto;
}

/* É possível usar as pseudo-classes também nas DIVs, não somente em links. */
.botao-twitter:hover {
	background-color:#ADD8E6;
}

.link-twitter {
	text-decoration:none;
	color:white;
	font-family:Tahoma;
}

.span-twitter {
	color:blue;
	font-weight:bold;
	font-family:Tahoma;
	font-size:20px;
}

/* Para alterar a cor do fundo inteiro do seu HTML, basta tirar o comentário da próxima instrução: */
/*
body {
	background-color:#90EE90;
}
*/

/* Para formatar tudo dentro do seu HTML, basta usar o seletor *. Para ver o exemplo, tire o comentário da próxima instrução: */
/*
* {
	border:1px solid red;
}
 */

/* É possível descer quantos níveis forem necessários. Este código vai formatar os itens de uma lista não ordenada que está dentro de uma lista ordenada. */
ol li ul li {
	color:#9400D3;
}

/* Formata apenas a primeira tag 'p' da div cuja classe é 'filho' */
.filho p:first-child {
	color:green;
	font-weight:bold;
}

/* Formata apenas a segunda tag 'p' da div cuja classe é 'filho' */
.filho p:nth-child(2) {
	color:red;
}

/* Formata apenas a segunda tag 'p' da div cuja classe é 'filho' */
.filho p:nth-child(3) {
	font-family:Verdana, serif;
}

/* Formata as DIVs cuja classe é 'posicao-block'. */
.posicao-block {
	width:30px;
	height:30px;
	border-radius:100%;
	/* display:block é o default (um elemento em cima do outro). */
	display:block;
}

#posicao1 {
	background-color:red;
}

#posicao2 {
	background-color:yellow;
}

#posicao3 {
	background-color:green;
}

/* Formata as DIVs cuja classe é 'posicao-iblock'. */
.posicao-iblock {
	width:30px;
	height:30px;
	border-radius:100%;
	/* display:inline-block coloca os elementos na mesma linha. */
	display:inline-block;
}

#posicao4 {
	background-color:red;
}

#posicao5 {
	background-color:yellow;
}

#posicao6 {
	background-color:green;
}

/* Formata as DIVs cuja classe é 'posicao-inline'. */
.posicao-inline {
	width:30px;
	height:30px;
	border-radius:100%;
	/* display:inline coloca os elementos na mesma linha, não respeitando suas dimensões. */
	display:inline;
	border:5px solid black;
}

#posicao7 {
	background-color:red;
}

#posicao8 {
	background-color:yellow;
}

#posicao9 {
	background-color:green;
}

/* Aplica margem na DIV cujo ID é margem1 */
#margem1 {
	width:30px;
	height:30px;
	border-radius:100%;
	background-color:blue;
	/* Margens podem ser aplicadas com as tags:
	margin-top:<valor>px;
	margin-right:<valor>px;
	margin-bottom:<valor>px;
	margin-left:<valor>px;
	OU (todas de uma vez):
	margin:<top>px <right>px <bottom>px <left>px; */
	margin:50px 30px 30px 100px;
}

/* Aplica preenchimento na DIV cujo ID é preenc1 */
#preenc1 {
	width:30px;
	height:30px;
	border-radius:100%;
	background-color:blue;
	/* Preenchimentos podem ser aplicados com as tags:
	padding-top:<valor>px;
	padding-right:<valor>px;
	padding-bottom:<valor>px;
	padding-left:<valor>px;
	OU (para aplicar o mesmo valor em todas as direções):
	padding: 10px (isso aplica 10px em todas as direções)
	OU (todas de uma vez):
	padding:<top>px <right>px <bottom>px <left>px; */
	padding:50px 30px 50px 100px;
}

/* Aplica margem na DIV cujo ID é margem2 */
#margem2 {
	width:50px;
	height:50px;
	border-radius:100%;
	background-color:blue;
	margin-left:-30px;
}

/* Formata um quadrado fixo, para inserirmos um elemento float dentro dele. A tag float serve para fazer um elemento flutuar dentro do elemento em que ele se encontra. */
.fixo {
	width:100px;
	height:100px;
	background-color:blue;
}

/* Insere um elemento flutuante dentro da DIV cuja classe é 'fixo'. Esse elemento flutua à direita dessa DIV. */
#flutuando1 {
	width:30px;
	height:90px;
	background-color:yellow;
	float:right;
}

/* Insere um elemento flutuante dentro da DIV cuja classe é 'fixo'. Esse elemento flutua à esquerda dessa DIV. */
#flutuando2 {
	width:30px;
	height:90px;
	background-color:yellow;
	float:left;
}

/* Insere dois elementos flutuantes dentro da DIV cuja classe é 'fixo'. Esses elementos flutuam à esquerda e a direita dessa DIV. */
#flutuando3 {
	width:30px;
	height:90px;
	background-color:yellow;
	float:left;
}

#flutuando4 {
	width:50px;
	height:90px;
	background-color:green;
	float:right;
}

/* Insere dois elementos flutuantes dentro da DIV cuja classe é 'fixo'. */
#flutuando5 {
	width:60px;
	height:80px;
	background-color:yellow;
	float:right;
}

#flutuando6 {
	width:40px;
	height:80px;
	background-color:green;
	float:right;
}

/* Insere um 'rodapé' dentro da DIV. */
#clear1 {
	width:100px;
	height:20px;
	background-color:gray;
	/* A tag clear serve para posicionar o elemento abaixo dos elementos flutuantes. Dessa forma, eles não ficam sobrepostos.
	- clear:left posiciona o elemento abaixo do elemento flutuante à esquerda.
	- clear:right posiciona o elemento abaixo do elemento flutuante à direita.
	- clear:both posiciona o elemento abaixo dos elementos flutuantes à esquerda e direita. */
	clear:both;
}

/* Posição relativa significa que o elemento será ajustado de acordo com sua posição normal.  */
#relative-position1 {
	width:100px;
	height:100px;
	background-color:green;
	position:relative;
}

/* Posição absoluta significa que o elemento será posicionado relativamente ao parente mais próximo, cuja position não seja static. */
#absolute-position1 {
	width:40px;
	height:40px;
	background-color:yellow;
	position:absolute;
	margin:30px 0px 0px 50px;
}

/* Existe também a posição 'fixed' que fixa o elemento na tela. Ideal para cabeçalhos e menus de sites. */

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

RSpec.describe Comment, type: :model do
  context 'factories' do
    let(:factories) do
      [
        FactoryBot.build(:measure_comment),
        FactoryBot.build(:comment_comment)
      ]
    end

    it 'has valid factories' do
      expect(factories).to all(be_valid)
    end
  end

  context 'validations' do
    subject { FactoryBot.build(:measure_comment) }

    it { is_expected.to validate_presence_of(:text) }
  end

  context 'associations' do
    describe ':user' do
      it { is_expected.to belong_to(:user) }
    end

    describe ':commentable' do
      it { is_expected.to belong_to(:commentable) }
    end
  end
end


text:
namespace aura {
class RootWindow;
class Window;
}

namespace gfx {
class LinearAnimation;
}

namespace ash {

namespace test {
class DragDropControllerTest;
}

namespace internal {

class DragDropTracker;
class DragDropTrackerDelegate;
class DragImageView;

class ASH_EXPORT DragDropController
    : public aura::client::DragDropClient,
      public ui::EventHandler,
      public gfx::AnimationDelegate,
      public aura::WindowObserver {
 public:
  DragDropController();
  virtual ~DragDropController();

  void set_should_block_during_drag_drop(bool should_block_during_drag_drop) {
    should_block_during_drag_drop_ = should_block_during_drag_drop;
  }

  // Overridden from aura::client::DragDropClient:
  virtual int StartDragAndDrop(
      const ui::OSExchangeData& data,
      aura::RootWindow* root_window,
      aura::Window* source_window,
      const gfx::Point& root_location,
      int operation,
      ui::DragDropTypes::DragEventSource source) OVERRIDE;
  virtual void DragUpdate(aura::Window* target,
                          const ui::LocatedEvent& event) OVERRIDE;
  virtual void Drop(aura::Window* target,
                    const ui::LocatedEvent& event) OVERRIDE;
  virtual void DragCancel() OVERRIDE;
  virtual bool IsDragDropInProgress() OVERRIDE;

  // Overridden from ui::EventHandler:
  virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE;
  virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE;
  virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE;
  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;

  // Overridden from aura::WindowObserver.
  virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE;

 protected:
  // Helper method to create a LinearAnimation object that will run the drag
  // cancel animation. Caller take ownership of the returned object. Protected
  // for testing.
  virtual gfx::LinearAnimation* CreateCancelAnimation(
      int duration,
      int frame_rate,
      gfx::AnimationDelegate* delegate);

  // Actual implementation of |DragCancel()|. protected for testing.
  virtual void DoDragCancel(int drag_cancel_animation_duration_ms);

 private:
  friend class ash::test::DragDropControllerTest;

  // Overridden from gfx::AnimationDelegate:
  virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE;
  virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE;
  virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE;

  // Helper method to start drag widget flying back animation.
  void StartCanceledAnimation(int animation_duration_ms);

  // Helper method to forward |pending_log_tap_| event to |drag_source_window_|.
  void ForwardPendingLongTap();

  // Helper method to reset everything.
  void Cleanup();

  scoped_ptr<DragImageView> drag_image_;
  gfx::Vector2d drag_image_offset_;
  const ui::OSExchangeData* drag_data_;
  int drag_operation_;

  // Window that is currently under the drag cursor.
  aura::Window* drag_window_;

  // Starting and final bounds for the drag image for the drag cancel animation.
  gfx::Rect drag_image_initial_bounds_for_cancel_animation_;
  gfx::Rect drag_image_final_bounds_for_cancel_animation_;

  scoped_ptr<gfx::LinearAnimation> cancel_animation_;

  // Window that started the drag.
  aura::Window* drag_source_window_;

  // Indicates whether the caller should be blocked on a drag/drop session.
  // Only be used for tests.
  bool should_block_during_drag_drop_;

  // Closure for quitting nested message loop.
  base::Closure quit_closure_;

  scoped_ptr<ash::internal::DragDropTracker> drag_drop_tracker_;
  scoped_ptr<DragDropTrackerDelegate> drag_drop_window_delegate_;

  ui::DragDropTypes::DragEventSource current_drag_event_source_;

  // Holds a synthetic long tap event to be sent to the |drag_source_window_|.
  // See comment in OnGestureEvent() on why we need this.
  scoped_ptr<ui::GestureEvent> pending_long_tap_;

  base::WeakPtrFactory<DragDropController> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(DragDropController);
};

}  // namespace internal
}  // namespace ash

#endif  // ASH_DRAG_DROP_DRAG_DROP_CONTROLLER_H_


text:
namespace CompSys
{
    partial class frmListStaff
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmListStaff));
            this.dgvListStaff = new System.Windows.Forms.DataGridView();
            this.printStaffList = new System.Drawing.Printing.PrintDocument();
            this.btnPrintStaffList = new System.Windows.Forms.Button();
            this.gbSortBy = new System.Windows.Forms.GroupBox();
            this.rbRegDate = new System.Windows.Forms.RadioButton();
            this.rbFirstname = new System.Windows.Forms.RadioButton();
            this.rbLastname = new System.Windows.Forms.RadioButton();
            this.rbTown = new System.Windows.Forms.RadioButton();
            this.cbStatus = new System.Windows.Forms.ComboBox();
            this.btnBack = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dgvListStaff)).BeginInit();
            this.gbSortBy.SuspendLayout();
            this.SuspendLayout();
            //
            // dgvListStaff
            //
            this.dgvListStaff.AllowUserToAddRows = false;
            this.dgvListStaff.AllowUserToDeleteRows = false;
            this.dgvListStaff.AllowUserToResizeRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.Azure;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgvListStaff.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            this.dgvListStaff.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvListStaff.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
            this.dgvListStaff.BackgroundColor = System.Drawing.Color.LightSlateGray;
            this.dgvListStaff.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.dgvListStaff.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
            this.dgvListStaff.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
            this.dgvListStaff.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvListStaff.Cursor = System.Windows.Forms.Cursors.Hand;
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.DarkOrange;
            dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.Black;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
            this.dgvListStaff.DefaultCellStyle = dataGridViewCellStyle2;
            this.dgvListStaff.GridColor = System.Drawing.SystemColors.ActiveBorder;
            this.dgvListStaff.Location = new System.Drawing.Point(12, 129);
            this.dgvListStaff.Name = "dgvListStaff";
            this.dgvListStaff.ReadOnly = true;
            this.dgvListStaff.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
            this.dgvListStaff.RowHeadersVisible = false;
            dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle3.ForeColor = System.Drawing.Color.White;
            this.dgvListStaff.RowsDefaultCellStyle = dataGridViewCellStyle3;
            this.dgvListStaff.RowTemplate.DefaultCellStyle.ForeColor = System.Drawing.Color.Black;
            this.dgvListStaff.RowTemplate.DividerHeight = 3;
            this.dgvListStaff.Size = new System.Drawing.Size(680, 358);
            this.dgvListStaff.TabIndex = 13;
            //
            // printStaffList
            //
            this.printStaffList.DocumentName = "Printing Staff List";
            this.printStaffList.BeginPrint += new System.Drawing.Printing.PrintEventHandler(this.printStaffList_BeginPrint);
            this.printStaffList.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printStaffList_PrintPage);
            //
            // btnPrintStaffList
            //
            this.btnPrintStaffList.BackColor = System.Drawing.Color.Transparent;
            this.btnPrintStaffList.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnPrintStaffList.BackgroundImage")));
            this.btnPrintStaffList.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.btnPrintStaffList.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.btnPrintStaffList.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.btnPrintStaffList.Font = new System.Drawing.Font("Lucida Fax", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnPrintStaffList.ForeColor = System.Drawing.SystemColors.HighlightText;
            this.btnPrintStaffList.Location = new System.Drawing.Point(0, 500);
            this.btnPrintStaffList.Name = "btnPrintStaffList";
            this.btnPrintStaffList.Size = new System.Drawing.Size(704, 42);
            this.btnPrintStaffList.TabIndex = 17;
            this.btnPrintStaffList.Text = "Print Staff Details";
            this.btnPrintStaffList.UseCompatibleTextRendering = true;
            this.btnPrintStaffList.UseVisualStyleBackColor = false;
            this.btnPrintStaffList.Click += new System.EventHandler(this.btnPrintStaffList_Click);
            //
            // gbSortBy
            //
            this.gbSortBy.BackColor = System.Drawing.Color.Transparent;
            this.gbSortBy.Controls.Add(this.rbRegDate);
            this.gbSortBy.Controls.Add(this.cbStatus);
            this.gbSortBy.Controls.Add(this.rbFirstname);
            this.gbSortBy.Controls.Add(this.rbLastname);
            this.gbSortBy.Controls.Add(this.rbTown);
            this.gbSortBy.Font = new System.Drawing.Font("Lucida Fax", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.gbSortBy.ForeColor = System.Drawing.SystemColors.ControlDark;
            this.gbSortBy.Location = new System.Drawing.Point(12, 71);
            this.gbSortBy.Name = "gbSortBy";
            this.gbSortBy.Size = new System.Drawing.Size(680, 52);
            this.gbSortBy.TabIndex = 20;
            this.gbSortBy.TabStop = false;
            this.gbSortBy.Text = "Sort by:";
            //
            // rbRegDate
            //
            this.rbRegDate.AutoSize = true;
            this.rbRegDate.BackColor = System.Drawing.Color.Transparent;
            this.rbRegDate.Font = new System.Drawing.Font("Lucida Fax", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.rbRegDate.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.rbRegDate.Location = new System.Drawing.Point(432, 19);
            this.rbRegDate.Name = "rbRegDate";
            this.rbRegDate.Size = new System.Drawing.Size(91, 20);
            this.rbRegDate.TabIndex = 17;
            this.rbRegDate.TabStop = true;
            this.rbRegDate.Text = "REG DATE";
            this.rbRegDate.UseVisualStyleBackColor = false;
            this.rbRegDate.CheckedChanged += new System.EventHandler(this.rbRegDate_CheckedChanged);
            //
            // rbFirstname
            //
            this.rbFirstname.AutoSize = true;
            this.rbFirstname.BackColor = System.Drawing.Color.Transparent;
            this.rbFirstname.Font = new System.Drawing.Font("Lucida Fax", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.rbFirstname.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.rbFirstname.Location = new System.Drawing.Point(169, 18);
            this.rbFirstname.Name = "rbFirstname";
            this.rbFirstname.Size = new System.Drawing.Size(96, 20);
            this.rbFirstname.TabIndex = 14;
            this.rbFirstname.TabStop = true;
            this.rbFirstname.Text = "FORENAME";
            this.rbFirstname.UseVisualStyleBackColor = false;
            this.rbFirstname.CheckedChanged += new System.EventHandler(this.rbFirstname_CheckedChanged);
            //
            // rbLastname
            //
            this.rbLastname.AutoSize = true;
            this.rbLastname.BackColor = System.Drawing.Color.Transparent;
            this.rbLastname.Font = new System.Drawing.Font("Lucida Fax", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.rbLastname.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.rbLastname.Location = new System.Drawing.Point(38, 19);
            this.rbLastname.Name = "rbLastname";
            this.rbLastname.Size = new System.Drawing.Size(88, 20);
            this.rbLastname.TabIndex = 15;
            this.rbLastname.TabStop = true;
            this.rbLastname.Text = "SURNAME";
            this.rbLastname.UseVisualStyleBackColor = false;
            this.rbLastname.CheckedChanged += new System.EventHandler(this.rbLastname_CheckedChanged);
            //
            // rbTown
            //
            this.rbTown.AutoSize = true;
            this.rbTown.BackColor = System.Drawing.Color.Transparent;
            this.rbTown.Font = new System.Drawing.Font("Lucida Fax", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.rbTown.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.rbTown.Location = new System.Drawing.Point(312, 19);
            this.rbTown.Name = "rbTown";
            this.rbTown.Size = new System.Drawing.Size(67, 20);
            this.rbTown.TabIndex = 16;
            this.rbTown.TabStop = true;
            this.rbTown.Text = "TOWN";
            this.rbTown.UseVisualStyleBackColor = false;
            this.rbTown.CheckedChanged += new System.EventHandler(this.rbTown_CheckedChanged);
            //
            // cbStatus
            //
            this.cbStatus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbStatus.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cbStatus.Font = new System.Drawing.Font("Lucida Fax", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cbStatus.ForeColor = System.Drawing.SystemColors.InfoText;
            this.cbStatus.FormattingEnabled = true;
            this.cbStatus.Items.AddRange(new object[] {
            "Active",
            "Inactive"});
            this.cbStatus.Location = new System.Drawing.Point(554, 17);
            this.cbStatus.Name = "cbStatus";
            this.cbStatus.Size = new System.Drawing.Size(108, 24);
            this.cbStatus.Sorted = true;
            this.cbStatus.TabIndex = 18;
            this.cbStatus.SelectedIndexChanged += new System.EventHandler(this.cbStatus_SelectedIndexChanged);
            this.cbStatus.SelectedValueChanged += new System.EventHandler(this.cbStatus_SelectedValueChanged);
            //
            // btnBack
            //
            this.btnBack.BackColor = System.Drawing.Color.Transparent;
            this.btnBack.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.btnBack.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnBack.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnBack.Font = new System.Drawing.Font("Lucida Fax", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnBack.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.btnBack.Image = global::CompSys.Properties.Resources.btnBack1;
            this.btnBack.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnBack.Location = new System.Drawing.Point(591, 22);
            this.btnBack.Name = "btnBack";
            this.btnBack.Size = new System.Drawing.Size(101, 42);
            this.btnBack.TabIndex = 22;
            this.btnBack.Text = "Back";
            this.btnBack.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnBack.UseCompatibleTextRendering = true;
            this.btnBack.UseVisualStyleBackColor = true;
            //
            // frmListStaff
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImage = global::CompSys.Properties.Resources.bgDefault;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.ClientSize = new System.Drawing.Size(704, 542);
            this.Controls.Add(this.btnBack);
            this.Controls.Add(this.gbSortBy);
            this.Controls.Add(this.btnPrintStaffList);
            this.Controls.Add(this.dgvListStaff);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.MaximizeBox = false;
            this.MaximumSize = new System.Drawing.Size(720, 580);
            this.MinimumSize = new System.Drawing.Size(720, 580);
            this.Name = "frmListStaff";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "CompuRite - List Staff";
            this.Load += new System.EventHandler(this.frmListStaff_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dgvListStaff)).EndInit();
            this.gbSortBy.ResumeLayout(false);
            this.gbSortBy.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dgvListStaff;
        private System.Drawing.Printing.PrintDocument printStaffList;
        private System.Windows.Forms.Button btnPrintStaffList;
        private System.Windows.Forms.GroupBox gbSortBy;
        private System.Windows.Forms.RadioButton rbFirstname;
        private System.Windows.Forms.RadioButton rbLastname;
        private System.Windows.Forms.RadioButton rbTown;
        private System.Windows.Forms.ComboBox cbStatus;
        private System.Windows.Forms.RadioButton rbRegDate;
        private System.Windows.Forms.Button btnBack;
    }
}


text:
(function() {
  var F = {};
  F[Symbol.hasInstance] = null;
  assertThrows(function() { 0 instanceof F; }, TypeError);
})();

// Make sure the result is coerced to boolean.
(function() {
  var F = {};
  F[Symbol.hasInstance] = function() { return undefined; };
  assertEquals(0 instanceof F, false);
  F[Symbol.hasInstance] = function() { return null; };
  assertEquals(0 instanceof F, false);
  F[Symbol.hasInstance] = function() { return true; };
  assertEquals(0 instanceof F, true);
})();

// Make sure if @@hasInstance throws, we catch it.
(function() {
  var F = {};
  F[Symbol.hasInstance] = function() { throw new Error("always throws"); }
  try {
    0 instanceof F;
  } catch (e) {
    assertEquals(e.message, "always throws");
  }
})();

// @@hasInstance works for bound functions.
(function() {
  var BC = function() {};
  var bc = new BC();
  var bound = BC.bind();
  assertEquals(bound[Symbol.hasInstance](bc), true);
  assertEquals(bound[Symbol.hasInstance]([]), false);
})();

// if OrdinaryHasInstance is passed a non-callable receiver, return false.
assertEquals(Function.prototype[Symbol.hasInstance].call(Array, []), true);
assertEquals(Function.prototype[Symbol.hasInstance].call({}, {}), false);

// OrdinaryHasInstance passed a non-object argument returns false.
assertEquals(Function.prototype[Symbol.hasInstance].call(Array, 0), false);


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Misfit 跑调 比赛面板</title>
    <link href="style.css" rel="stylesheet" type="text/css">

	用户:

	BPM:

	当前步数:

	加速度:


text:
using System;

namespace Convert_Speed_Units
{
    class Program
    {
        static void Main(string[] args)
        {
            // On first line, you receive – distance in meters
            // On second – hours
            // On third – minutes
            // On fourth – seconds

            float distanceInMeters = float.Parse(Console.ReadLine());
            float hours = float.Parse(Console.ReadLine());
            float minutes = float.Parse(Console.ReadLine());
            float seconds = float.Parse(Console.ReadLine());

            //Speed: meter per seconds (m/s)

            float hoursInSeconds = hours * 60 * 60;
            float minutesInSeconds = minutes * 60;
            float totalTimeInSeconds = hoursInSeconds + minutesInSeconds + seconds;
            float meterPerSecond = distanceInMeters / totalTimeInSeconds;

            Console.WriteLine($"{meterPerSecond:f7}");

            //Speed: kilometers per hour (km/h)

            float secondsInHours = ((seconds / 60) / 60);
            float minutesInHours = minutes / 60;
            float totalTimeInHours = hours + minutesInHours + secondsInHours;
            float distanceInKilometers = distanceInMeters / 1000;
            float kilometersPerHours = distanceInKilometers / totalTimeInHours;

            Console.WriteLine($"{kilometersPerHours:f7}");

            //Speed: milies per hours (mi/h)

            float metersInMilies = distanceInMeters / 1609;
            float miliesPerHour = metersInMilies / totalTimeInHours;

            Console.WriteLine($"{miliesPerHour:f7}");
        }
    }
}


text:
class TokyoMetro::Api::Point::Info::Title::Code

  def initialize( code , additional_info_ja )
    @first_char = nil
    @number = nil
    @last_char = nil
    @another_info = nil
    @additional_info_ja = nil

    if code.string?
      if /\A([A-Z]?)(\d{1,2})([a-z]?)/ =~ code
        @first_char = $1
        @number = $2.to_i
        @last_char = $3
      else
        @another_info = code
      end
    else
      unless code.nil?
        raise "Error: TokyoMetro::Api::Point::Info::Title::Code - #{ code } is not valid."
      end
    end

    if additional_info_ja.present?
      @additional_info_ja = additional_info_ja
    end
  end

  attr_reader :first_char
  attr_reader :number
  attr_reader :last_char
  attr_reader :another_info
  attr_reader :additional_info_ja

  def <=>( other )
    #-------- first_char が異なる場合
    c_first_char = compare_by( other , :first_char )
    if c_first_char.present?
      return c_first_char
    end

    #-------- first_char が同じで number が異なる場合
    c_number = compare_by( other , :number )
    if c_number.present?
      return c_number
    end

    #-------- first_char, number が同じで last_char が異なる場合
    c_last_char = compare_by( other , :last_char )
    if c_last_char.present?
      return c_last_char
    end

    c_another_info = compare_by( other , :another_info )
    if c_another_info.present?
      return c_another_info
    end

    c_additional_info_ja = compare_by( other , :additional_info_ja )
    if c_additional_info_ja.present?
      return c_additional_info_ja
    end

    return 0
  end

  private

  def compare_by( other , method_name )
    if send( method_name ).blank? and other.send( method_name ).present?
      return -1
    elsif send( method_name ).present? and other.send( method_name ).present?
      unless send( method_name ) == other.send( method_name )
        return ( send( method_name ) <=> other.send( method_name ) )
      end
    elsif send( method_name ).present? and other.send( method_name ).blank?
      return 1
    else
      nil
    end
  end

end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * The String.prototype.slice.length property has the attribute DontDelete
 *
 * @path ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A9.js
 * @description Checking if deleting the String.prototype.slice.length property fails
 */

//////////////////////////////////////////////////////////////////////////////
//CHECK#0
if (!(String.prototype.slice.hasOwnProperty('length'))) {
  $FAIL('#0: String.prototype.slice.hasOwnProperty(\'length\') return true. Actual: '+String.prototype.slice.hasOwnProperty('length'));
}
//
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (delete String.prototype.slice.length) {
  $ERROR('#1: delete String.prototype.slice.length return false');
}
//
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (!(String.prototype.slice.hasOwnProperty('length'))) {
  $FAIL('#2: delete String.prototype.slice.length; String.prototype.slice.hasOwnProperty(\'length\') return true. Actual: '+String.prototype.slice.hasOwnProperty('length'));
}
//
//////////////////////////////////////////////////////////////////////////////


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Riak.Bucket – Riak Elixir Client v1.0.0</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="ExDoc v0.10.0">
    <link rel="stylesheet" href="dist/app.css" />

<button class="sidebar-toggle">

</button>

  <button class="sidebar-toggle">

  </button>

        Riak Elixir Client

        v1.0.0

    <input type="text" class="sidebar-searchInput" placeholder="search" autocomplete="off" />

Pages

Modules

        Riak.Bucket

            Summary

      Functions

    get(bucket)

    get(pid, bucket)

Get bucket properties

    keys(bucket)

    keys(pid, bucket)

    keys(pid, type, bucket)

List all keys in a bucket.
This is a potentially expensive operation and should not be used in production.

    keys(pid, type, bucket, timeout)

    keys!(bucket)

    keys!(pid, bucket)

    keys!(pid, type, bucket)

List all keys in a bucket. Return only buckets.
This is a potentially expensive operation and should not be used in production.

    keys!(pid, type, bucket, timeout)

    list()

    list(pid)

List all buckets on the server with or without server-side timeout.
This is a potentially expensive operation and should not be used in production.

    list(pid, timeout)

    list!()

    list!(pid)

List all buckets on the server with or without server-side timeout. Return only buckets.
This is a potentially expensive operation and should not be used in production.

    list!(pid, timeout)

    possible_props()

Used to "register" the atoms used by the protobuf interface, not for public use

    put(bucket, props)

    put(pid, bucket, props)

Set bucket properties

    put(pid, bucket, type, props)

    reset(bucket)

    reset(pid, bucket)

Reset bucket properties back to the defaults

            Functions

    get(bucket)

    get(pid, bucket)

Get bucket properties.

    keys(bucket)

    keys(pid, bucket)

    keys(pid, type, bucket)

List all keys in a bucket.
This is a potentially expensive operation and should not be used in production.

    keys(pid, type, bucket, timeout)

    keys!(bucket)

    keys!(pid, bucket)

    keys!(pid, type, bucket)

List all keys in a bucket. Return only buckets.
This is a potentially expensive operation and should not be used in production.

    keys!(pid, type, bucket, timeout)

    list()

    list(pid)

List all buckets on the server with or without server-side timeout.
This is a potentially expensive operation and should not be used in production.

    list(pid, timeout)

    list!()

    list!(pid)

List all buckets on the server with or without server-side timeout. Return only buckets.
This is a potentially expensive operation and should not be used in production.

    list!(pid, timeout)

    possible_props()

Used to "register" the atoms used by the protobuf interface, not for public use.

    put(bucket, props)

    put(pid, bucket, props)

Set bucket properties.

    put(pid, bucket, type, props)

    reset(bucket)

    reset(pid, bucket)

Reset bucket properties back to the defaults.

          Built using
          ExDoc (v0.10.0),

          designed by
          Friedel Ziegelmayer.


text:
'use strict';
var api = require('./apiMock');

var convoId = 0;
// mock for main bot object
class Bot {
    // in constructor we pass controller mock instance
    constructor(controller) {
        this.apiResponses = new api();
        this.botkit = {
            tasks: [],
            log: function(){},
            memory_store: {
                users: {},
                channels: {},
                teams: {}
            }
        };
        var self = this;
        // this object will store bot answer for each user separately
        this.detailedAnswers = {
        // "userId": ["answer1","anwer2"]
        };
        // store all open convos
        this.convos = []
        // reference to controller object
        this.controller = controller;
        // bot patterns - migrated from origin botkit
        this.utterances = {
            yes: "yes",
            no: "no"
        }

        this.api = this.buildProxyAPI();

        this.callbacksHashByConvo = {};

        //store interactive replies callbacks
        this.interactiveRepliesCallbacks = [];

        this.botkit.storage = {
            teams: {
                get: function(team_id, cb) {
                    cb(null, self.botkit.memory_store.teams[team_id]);
                },
                save: function(team, cb) {
                    if (team.id) {
                        self.botkit.memory_store.teams[team.id] = team;
                        cb(null, team.id);
                    } else {
                        cb('No ID specified');
                    }
                },
                all: function(cb) {
                    cb(null, self.botkit.memory_store.teams);
                }
            },
            users: {
                get: function(user_id, cb) {
                    cb(null, self.botkit.memory_store.users[user_id]);
                },
                save: function(user, cb) {
                    if (user.id) {
                        self.botkit.memory_store.users[user.id] = user;
                        cb(null, user.id);
                    } else {
                        cb('No ID specified');
                    }
                },
                all: function(cb) {
                    cb(null, self.botkit.memory_store.users);
                }
            },
            channels: {
                get: function(channel_id, cb) {
                    cb(null, self.botkit.memory_store.channels[channel_id]);
                },
                save: function(channel, cb) {
                    if (channel.id) {
                        self.botkit.memory_store.channels[channel.id] = channel;
                        cb(null, channel.id);
                    } else {
                        cb('No ID specified');
                    }
                },
                all: function(cb) {
                    cb(null, self.botkit.memory_store.channels);
                }
            }
        };
    }

    getAPILogByNumber(i) {
        return this.log[i]
    }

    buildProxyAPI() {
        let o = {};
        this.log = []
        o['callAPI'] = (apiName, params, callback) => {
            if (apiName != 'chat.update')
                this.log.push(apiName);
            this.apiResponses.api['callAPI'](apiName, params, callback)
        }
        return o;
    }

    updateApiByKey(key, value) {
        this.apiResponses.updateData(key, value);
    }

    getApiByKey(key) {
        return this.apiResponses.getData(key);
    }

    startTyping(message, cb){
        if (typeof cb === 'function') {
            cb()
        }
    }

    stopTyping(message, cb){
        if (typeof cb === 'function') {
            cb()
        }
    }

    replyWithTyping(message, text){
        this.reply(message, text)
    }

    // reply to user and store reply in array
    reply(message, text, cb) {
        // check if this is first time then create anwers array
        if(message.channel){
            if(!this.detailedAnswers[message.channel]){
                this.detailedAnswers[message.channel] = []
            }
            this.detailedAnswers[message.channel].push(text)
        }
        else{
            if (!this.detailedAnswers[message.user])
                this.detailedAnswers[message.user] = []
            this.detailedAnswers[message.user].push(text)
        }

        this.callInteractiveRepliesCallbacks(message.user);

        if (typeof cb === 'function') {
            cb({}, {})
        }
    }
    replyInteractive(message, text, cb) {
        this.reply(message, text);
    }
    callInteractiveRepliesCallbacks(message_user) {
        //Check if we have an interactive reply to call to
        for (let user in this.interactiveRepliesCallbacks) {
            if (user != message_user)
                continue;
            let result;
            if (this.detailedAnswers[user]) {
                result = this.detailedAnswers[user][this.detailedAnswers[user].length - 1];
            }
            this.interactiveRepliesCallbacks[user](result);
            delete this.interactiveRepliesCallbacks[user];
        }
    }
    // start new conversation
    startConversation(message, callback) {
        // creat enew convo object
        this.convo = new Convo(this);
        // setup convo owner
        this.convo.user = message.user;
        this.convo.sourceMessage.user = message.user;
        this.convo.sourceMessage.channel = message.user;
        // store convo
        this.convos.push(this.convo);
        // invoke callback
        callback(null, this.convo)
    }
    //say mock - without logic
    say(message, callback) {
        if(message.channel){
            if(!this.detailedAnswers[message.channel]){
                this.detailedAnswers[message.channel] = []
            }
            this.detailedAnswers[message.channel].push(message.text)
        }
        else{
            if (!this.detailedAnswers[message.user])
                this.detailedAnswers[message.user] = [];
            this.detailedAnswers[message.user].push(message.text)
        }
        if (typeof callback === 'function') {
            callback(null, {
                message: {}
            })
        }
    }

}
// mock for controller class
class Controller {
    // constructor taks slackUserId and userName
    constructor(userId, userName) {
        this.userName = userName;
        this.user = userId
        // create bot object
        this.bot = new Bot(this);
        //link on bot.storage
        this.storage = this.bot.botkit.storage;
        // store action which we wanna listen
        this.actions = [];
        //store events we want to listen
        this.events = [];
    }
    interactiveMessage(message, userTypes) {
        if (!message.callback_id)
            throw "Missing callback_id";
        return new Promise((resolve, reject) => {
            let relevantEvents = this.events.filter((eventListener) => {
                return eventListener.event == 'interactive_message_callback';
            });

            if (relevantEvents.length == 0) {
                resolve();
                return;
            }
            if (userTypes && userTypes.length > 0) { //If we're expecting the user to enter some text in response to the interactive message, we better store it and let Convo.ask call resolve
                this.allTypers = userTypes;
                // save options
                this.typeOptions = {};
                // add resolve to type options
                this.typeOptions.resolve = resolve;
            } else { //Otherwise, we will call the resolve func once we get an interactiveReply
                this.bot.interactiveRepliesCallbacks[message.user] = resolve;
            }
            //Only support one event listener
            relevantEvents[0].callback(this.bot, message);
        });
    }
    // allow multiple convos
    // need refactor return promise
    usersInput(userTypes, options) {

        var self = this;
        // return promise which will be rosolved when we need assertion
        return new Promise((resolve, reject) => {
            // get user who first type message to bot chat
            var whoStartConvoWithBotFirst = userTypes.filter((userType) => {
                return userType.first;
            })[0]
            if (!whoStartConvoWithBotFirst)
                throw "initiator missing"
            // save all typers who will take action in conversation
            self.allTypers = userTypes;
            // save main typer ( first typer )
            self.mainTyper = whoStartConvoWithBotFirst;
            // save options
            self.typeOptions = options || {};
            // add resolve to type options
            self.typeOptions.resolve = resolve;
            // get first message which need send to bot
            var msg = whoStartConvoWithBotFirst.messages.shift()
            // correct message format - message must be an object with property text: "Message Text"
            if (typeof(msg) == 'string')
                msg = {
                    text: msg,
                }

            msg.type = (whoStartConvoWithBotFirst.type || 'direct_message');
            // set message user
            msg.user = msg.user || whoStartConvoWithBotFirst.user
            // send first message
            self.initialUserMessage(msg, options)
        })
    }
    initialUserMessage(message, options) {
        var self = this;
        // find action which will handle this message
        var matches = [];
        var action = self.actions.filter((obj) => {
            if (!Array.isArray(obj.type)) {
                obj.type = obj.type.split(",");
            }
            let matchType = obj.type.indexOf(message.type) > -1;
            // each action has pattern
            let pattern = obj.pattern;
            if (Array.isArray(obj.pattern)) {
                for (let i = 0;i < pattern.length;i++) {
                    if ((message.text || message).match(new RegExp(pattern[i], 'i'))) {
                        matches.push((message.text || message).match(pattern[i]));

                        return (message.text || message).match(new RegExp(pattern[i], 'i')) && matchType;
                    }
                }
            } else {
                if ((message.text || message).match(new RegExp(pattern, 'i'))) {
                    matches.push((message.text || message).match(new RegExp(pattern, 'i')) && matchType);
                }
            }

            return (message.text || message).match(new RegExp(pattern, 'i')) && matchType;
        })[0];
        if (action) {
            // call action callback with bot and new message object
            action.callback(self.bot, {
                user: message.user || self.user,
                is_bot: self.is_bot || false,
                username: self.userName,
                message: message.text,
                text: message.text,
                match: matches.find((v) => v!=null),
                //for controller.on
                channel: message.channel || message.user || self.user
            })
            // if message need assertion resolve promise - this cause test assertion
            if (message.isAssertion)
                if (message.onEvent) {
                    setTimeout(() => {
                        // simple resolve without params if we handle onEvent messages ( when user join to channel and join to team or leave channel )
                        self.typeOptions.resolve()
                    }, 200)
                } else {
                    setTimeout(() => {
                        let result;
                        if (self.bot.detailedAnswers[message.user]) {
                            result = self.bot.detailedAnswers[message.user][self.bot.detailedAnswers[message.user].length - 1];
                        }
                        // resolve with last message
                        self.typeOptions.resolve(result)
                    }, 200)
                }
        } else {
            // if we can`t find action - by default we`ll never came to this code because we have default bot response for all messages.
            throw 'Can`t find action for this user type'
        }
    }
    // mock for hears - when we subscribe for some actions
    hears(regex, type, callbacks) {
        // push to actions array and use in initialUserMessage
        this.actions.push({
            pattern: regex,
            type: type,
            callback: callbacks
        });
    }
    // mock for event listeners
    on(event, callback) {
        this.events.push({
            event: event,
            callback: callback
        });
    }
}
// convo object
class Convo {
    // takes bot object in constructor
    constructor(bot) {
        this.id = convoId = convoId + 1;
        this.bot = bot;
        this.sourceMessage = {
            user: ''
        }

    }
    // main ask action which as user some question
    ask(message, callbacks) {
        var self = this;
        // save bot message in user bot`s answers
        if (!self.bot.detailedAnswers[self.user])
        // if answers not exists create answers array for current convo user
            self.bot.detailedAnswers[self.user] = []
            // push bot message to answers array
        self.bot.detailedAnswers[self.user].push(message)
        // find current typer by message.user
        var currentTyper = (self.bot.controller.allTypers || []).filter((typer) => {
            return typer.user == self.user;
        })[0]
        if (currentTyper) {
            this.bot.callInteractiveRepliesCallbacks(self.user);
            // check if user has some message for answer to bot
            if (currentTyper.messages.length) {
                // get last message
                var messageNew = currentTyper.messages.shift()
                if (typeof(callbacks) == 'function' && (messageNew.text || messageNew.file)) {
                    // simple callback
                    callbacks({
                        text: messageNew.text,
                        channel: this.sourceMessage.user
                    }, self)
                } else if (Array.isArray(callbacks)) {
                    // find callback in callbacks array
                    var callback = callbacks.filter((c) => {
                        return (messageNew.text || '').toString().match(c.pattern)
                    })[0]
                    // check that message has text - we can`t send empty messages
                    if (messageNew.text || messageNew.file)
                    // invoke callback
                        if (callback && callback.callback) {
                            if (messageNew.callbackTimeout) {
                                setTimeout(() => {
                                    callback.callback({
                                        text: messageNew.text,
                                        user: self.user
                                    }, self)
                                }, messageNew.callbackTimeout)
                            } else {
                                callback.callback({
                                    text: messageNew.text,
                                    user: self.user,
                                    file: messageNew.file
                                }, self)
                            }
                        } else {
                            // find default callback and invoke
                            var defaultCallback = callbacks.filter((c) => {
                                return c.default
                            })[0]
                            if (defaultCallback) {
                                if (messageNew.callbackTimeout) {
                                    setTimeout(() => {
                                        default_callback.callback({
                                            text: messageNew.text,
                                            user: self.user
                                        }, self)
                                    }, messageNew.callbackTimeout)
                                } else {
                                    defaultCallback.callback({
                                        text: messageNew.text,
                                        user: self.user
                                    }, self)
                                }
                            }
                        }

                }
                // need wait some time before resolve

                if (messageNew.timeout && messageNew.isAssertion) {
                    return setTimeout(() => {
                        self.bot.controller.typeOptions.resolve(self.bot.detailedAnswers[self.user][self.bot.detailedAnswers[self.user].length - 1 - (messageNew.deep || 0)])
                    }, messageNew.timeout)
                }
                if (messageNew.isAssertion && !messageNew.timeout) {
                    setTimeout(() => {
                        self.bot.controller.typeOptions.resolve(self.bot.detailedAnswers[self.user][self.bot.detailedAnswers[self.user].length - 1 - (messageNew.deep || 0)])
                    }, 200)
                }
            } else {
                // last message already typed
            }

        } else {
            // when can`t find typer by slack id
        }
    }
    // simple say mock we just store answer in array
    say(text) {
        var self = this;
        // check if answers array exists for user
        if (!self.bot.detailedAnswers[self.user])
            self.bot.detailedAnswers[self.user] = []
            // push anwser to array
        self.bot.detailedAnswers[self.user].push(text)
    }
    // mock for next no logic
    next() {

    }
    // mock for stop no logic
    stop() {

    }
    // mock for repeat no logic
    repeat() {

    }
    // mock for silentRepeat no logic
    silentRepeat() {

    }

    // mock for deactivate no logic
    deactivate() {

    }
}
module.exports = {
    bot: Bot,
    controller: Controller,
    convo: Convo
}


text:
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description:  A library for managing GPS connections.
// ********************************************************************************************************
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// |    Developer             |    Date    |                             Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup  (Ben Tombs)      | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************

using System.IO;
using System.Xml.Serialization;

namespace DotSpatial.Positioning
{
    /// <summary>
    ///
    /// </summary>
    internal static class Xml
    {
        /// <summary>
        /// Returns the XML namespace for GML documents.
        /// </summary>
        public const string GML_XML_NAMESPACE = "http://www.opengis.net/gml";

        /// <summary>
        /// Returns the prefix applied to all GML XML elements.
        /// </summary>
        public const string GML_XML_PREFIX = "gml";

        /// <summary>
        /// Returns the XML namespace for DotSpatial.Positioning documents.
        /// </summary>
        public const string DOT_SPATIAL_POSITIONING_XML_NAMESPACE = "http://dotspatial.codeplex.com/gml";

        /// <summary>
        /// Returns the prefix applied to all DotSpatial.Positioning XML elements.
        /// </summary>
        public const string DOT_SPATIAL_POSITIONING_XML_PREFIX = "DotSpatial.Positioning";

#if Framework30

        /// <summary>
        /// Used to test the <see cref="IXmlSerializable.WriteXml"/> implementations of DotSpatial.Positioning types.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        internal static string Serialize<T>(T obj)
    where T : IXmlSerializable
        {
            using (StringWriter writer = new StringWriter())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj);

                return writer.ToString();
            }
        }

        /// <summary>
        /// Used to test the <see cref="IXmlSerializable.ReadXml"/> implementations of DotSpatial.Positioning types.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml">The XML.</param>
        /// <returns></returns>
        internal static T Deserialize<T>(string xml)
    where T : IXmlSerializable, new()
        {
            using (StringReader reader = new StringReader(xml))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(reader);
            }
        }

#endif
    }
}


text:
var should = require('should'),
    sinon = require('sinon'),
    getAuthorImage = require('../../../../frontend/meta/author_image');

describe('getAuthorImage', function () {
    afterEach(function () {
        sinon.restore();
    });

    it('should return author image url if post and has url', function () {
        var imageUrl = getAuthorImage({
            context: ['post'],
            post: {
                primary_author: {
                    profile_image: '/content/images/2016/01/myimage.jpg'
                }
            }
        }, false);

        imageUrl.should.equal('/content/images/2016/01/myimage.jpg');
    });

    it('should return absolute author image url if post and has url', function () {
        var imageUrl = getAuthorImage({
            context: ['post'],
            post: {
                primary_author: {
                    profile_image: '/content/images/2016/01/myimage.jpg'
                }
            }
        }, true);
        imageUrl.should.not.equal('/content/images/2016/01/myimage.jpg');
        imageUrl.should.match(/\/content\/images\/2016\/01\/myimage\.jpg$/);
    });

    it('should return author image url if AMP post and has url', function () {
        var imageUrl = getAuthorImage({
            context: ['amp', 'post'],
            post: {
                primary_author: {
                    profile_image: '/content/images/2016/01/myimage.jpg'
                }
            }
        }, false);
        imageUrl.should.equal('/content/images/2016/01/myimage.jpg');
    });

    it('should return absolute author image url if AMP post and has url', function () {
        var imageUrl = getAuthorImage({
            context: ['amp', 'post'],
            post: {
                primary_author: {
                    profile_image: '/content/images/2016/01/myimage.jpg'
                }
            }
        }, true);
        imageUrl.should.not.equal('/content/images/2016/01/myimage.jpg');
        imageUrl.should.match(/\/content\/images\/2016\/01\/myimage\.jpg$/);
    });

    it('should return null if context does not contain author image url and is a post', function () {
        var imageUrl = getAuthorImage({
            context: ['post'],
            post: {
                primary_author: {
                    name: 'Test Author'
                }
            }
        });

        should(imageUrl).equal(null);
    });

    it('should return null if context does not contain author and is a post', function () {
        var imageUrl = getAuthorImage({
            context: ['post'],
            post: {}
        });

        should(imageUrl).equal(null);
    });

    it('should return null if context is not a post', function () {
        var imageUrl = getAuthorImage({
            context: ['tag']
        });

        should(imageUrl).equal(null);
    });
});


text:
extern crate cgu_generic_function;

//~ MONO_ITEM fn user @@ extern_generic[Internal]
fn user() {
    let _ = cgu_generic_function::foo("abc");
}

mod mod1 {
    use cgu_generic_function;

    //~ MONO_ITEM fn mod1::user @@ extern_generic-mod1[Internal]
    fn user() {
        let _ = cgu_generic_function::foo("abc");
    }

    mod mod1 {
        use cgu_generic_function;

        //~ MONO_ITEM fn mod1::mod1::user @@ extern_generic-mod1-mod1[Internal]
        fn user() {
            let _ = cgu_generic_function::foo("abc");
        }
    }
}

mod mod2 {
    use cgu_generic_function;

    //~ MONO_ITEM fn mod2::user @@ extern_generic-mod2[Internal]
    fn user() {
        let _ = cgu_generic_function::foo("abc");
    }
}

mod mod3 {
    //~ MONO_ITEM fn mod3::non_user @@ extern_generic-mod3[Internal]
    fn non_user() {}
}

// Make sure the two generic functions from the extern crate get instantiated
// once for the current crate
//~ MONO_ITEM fn cgu_generic_function::foo::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]
//~ MONO_ITEM fn cgu_generic_function::bar::<&str> @@ cgu_generic_function-in-extern_generic.volatile[External]


text:
package com.mokiat.data.front.scanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.mokiat.data.front.error.WFException;

/**
 * Default implementation of the {@link IMTLScanner}
 * interface.
 *
 * @author Momchil Atanasov
 *
 */
public class MTLScanner implements IMTLScanner {

	/**
	 * Creates a new instance of {@link MTLScanner}.
	 */
	public MTLScanner() {
		super();
	}

	@Override
	public void scan(InputStream in, IMTLScannerHandler handler) throws WFException, IOException {
		final Reader reader = new InputStreamReader(in);
		scan(new BufferedReader(reader), handler);
	}

	@Override
	public void scan(BufferedReader reader, IMTLScannerHandler handler) throws WFException, IOException {
		final MTLScanRunner runner = new MTLScanRunner(handler);
		runner.run(reader);
	}

}


text:
using namespace rocksdb;

std::string kDBPath = "/tmp/rocksdb_simple_example";

int main() {
  DB* db_ptr;
  Options options;
  // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
  options.IncreaseParallelism();
  options.OptimizeLevelStyleCompaction();
  // create the DB if it's not already present
  options.create_if_missing = true;

  // open DB
  Status s = DB::Open(options, kDBPath, &db_ptr);
  std::unique_ptr<DB> db(db_ptr);
  assert(s.ok());

  // Put key-value
  s = db->Put(WriteOptions(), "key1", "value");
  assert(s.ok());
  std::string value;
  // get value
  s = db->Get(ReadOptions(), "key1", &value);
  assert(s.ok());
  assert(value == "value");

  // atomically apply a set of updates
  {
    WriteBatch batch;
    batch.Delete("key1");
    batch.Put("key2", value);
    s = db->Write(WriteOptions(), &batch);
  }

  s = db->Get(ReadOptions(), "key1", &value);
  assert(s.IsNotFound());

  db->Get(ReadOptions(), "key2", &value);
  assert(value == "value");

  return 0;
}


text:
layout: post
date:	2011-07-12 02:26:00
title:  The Yellow Lotus, Forest Park, 110711
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
This morning I took Malvika to see the minks, and we did see them, though they were not cavorting at our feet like they sometimes do...but the treasure of the day was happening upon a stand (or a float?) of

 YELLOW LOTUS

(Nelumbo lutea)

I've never seen yellow lotuses before, and was quite stunned at these beauties!

Nor did I realize that lotuses are native to the American continent, too, I've always thought of it as a kind of "Asian" flower!

We were lucky that the weather was cloudy and quite comfortable, and the sunrise was beautiful, whether at the pines:

Or at the creek:

The lotus and the sun are generally associated, and certainly, the flowers we saw were all facing the sun!


text:
class AddAutoAcceptBookingToDanvanthiriCorePatientCoordinator < ActiveRecord::Migration
  def change
    add_column :danvanthiri_core_patient_coordinators, :auto_accept_booking, :boolean, default: false
  end
end


text:
"""
All we need to create a Solr connection is a url.

>>> conn = Solr('http://127.0.0.1:8983/solr/')

First, completely clear the index.

>>> conn.delete(q='*:*')

For now, we can only index python dictionaries. Each key in the dictionary
will correspond to a field in Solr.

>>> docs = [
...     {'id': 'testdoc.1', 'order_i': 1, 'name': 'document 1', 'text': u'Paul Verlaine'},
...     {'id': 'testdoc.2', 'order_i': 2, 'name': 'document 2', 'text': u'Владимир Маякoвский'},
...     {'id': 'testdoc.3', 'order_i': 3, 'name': 'document 3', 'text': u'test'},
...     {'id': 'testdoc.4', 'order_i': 4, 'name': 'document 4', 'text': u'test'}
... ]

We can add documents to the index by passing a list of docs to the connection's
add method.

>>> conn.add(docs)

>>> results = conn.search('Verlaine')
>>> len(results)
1

>>> results = conn.search(u'Владимир')
>>> len(results)
1

Simple tests for searching. We can optionally sort the results using Solr's
sort syntax, that is, the field name and either asc or desc.

>>> results = conn.search('test', sort='order_i asc')
>>> for result in results:
...     print result['name']
document 3
document 4

>>> results = conn.search('test', sort='order_i desc')
>>> for result in results:
...     print result['name']
document 4
document 3

To update documents, we just use the add method.

>>> docs = [
...     {'id': 'testdoc.4', 'order_i': 4, 'name': 'document 4', 'text': u'blah'}
... ]
>>> conn.add(docs)

>>> len(conn.search('blah'))
1
>>> len(conn.search('test'))
1

We can delete documents from the index by id, or by supplying a query.

>>> conn.delete(id='testdoc.1')
>>> conn.delete(q='name:"document 2"')

>>> results = conn.search('Verlaine')
>>> len(results)
0

Docs can also have multiple values for any particular key. This lets us use
Solr's multiValue fields.

>>> docs = [
...     {'id': 'testdoc.5', 'cat': ['poetry', 'science'], 'name': 'document 5', 'text': u''},
...     {'id': 'testdoc.6', 'cat': ['science-fiction',], 'name': 'document 6', 'text': u''},
... ]

>>> conn.add(docs)
>>> results = conn.search('cat:"poetry"')
>>> for result in results:
...     print result['name']
document 5

>>> results = conn.search('cat:"science-fiction"')
>>> for result in results:
...     print result['name']
document 6

>>> results = conn.search('cat:"science"')
>>> for result in results:
...     print result['name']
document 5

"""

# TODO: unicode support is pretty sloppy. define it better.

from urllib import urlencode
from urlparse import urlsplit
from datetime import datetime, date
import re

try:
    # for python 2.5
    from xml.etree import cElementTree as ET
except ImportError:
    try:
        # use etree from lxml if it is installed
        from lxml import etree as ET
    except ImportError:
        try:
            # use cElementTree if available
            import cElementTree as ET
        except ImportError:
            try:
                from elementtree import ElementTree as ET
            except ImportError:
                raise ImportError("No suitable ElementTree implementation was found.")

try:
    # For Python < 2.6 or people using a newer version of simplejson
    import simplejson as json
except ImportError:
    # For Python >= 2.6
    import json

try:
    # Desirable from a timeout perspective.
    from httplib2 import Http
    TIMEOUTS_AVAILABLE = True
except ImportError:
    from httplib import HTTPConnection
    TIMEOUTS_AVAILABLE = False

try:
    set
except NameError:
    from sets import Set as set

__author__ = 'Joseph Kocherhans, Jacob Kaplan-Moss, Daniel Lindsley'
__all__ = ['Solr']
__version__ = (2, 0, 9)

def get_version():
    return "%s.%s.%s" % __version__

DATETIME_REGEX = re.compile('^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(\.\d+)?Z$')

class SolrError(Exception):
    pass

class Results(object):
    def __init__(self, docs, hits, highlighting={}, facets={}, spellcheck={}):
        self.docs = docs
        self.hits = hits
        self.highlighting = highlighting
        self.facets = facets
        self.spellcheck = spellcheck

    def __len__(self):
        return len(self.docs)

    def __iter__(self):
        return iter(self.docs)

class Solr(object):
    def __init__(self, url, decoder=None, timeout=60):
        self.decoder = decoder or json.JSONDecoder()
        self.url = url
        self.scheme, netloc, path, query, fragment = urlsplit(url)
        netloc = netloc.split(':')
        self.host = netloc[0]
        if len(netloc) == 1:
            self.host, self.port = netloc[0], None
        else:
            self.host, self.port = netloc
        self.path = path.rstrip('/')
        self.timeout = timeout

    def _send_request(self, method, path, body=None, headers=None):
        if TIMEOUTS_AVAILABLE:
            url = self.url.replace(self.path, '')
            http = Http(timeout=self.timeout)
            headers, response = http.request(url + path, method=method, body=body, headers=headers)

            if int(headers['status']) != 200:
                raise SolrError(self._extract_error(headers, response))

            return response
        else:
            if headers is None:
                headers = {}

            conn = HTTPConnection(self.host, self.port)
            conn.request(method, path, body, headers)
            response = conn.getresponse()

            if response.status != 200:
                raise SolrError(self._extract_error(dict(response.getheaders()), response.read()))

            return response.read()

    def _select(self, params):
        # encode the query as utf-8 so urlencode can handle it
        params['q'] = params['q'].encode('utf-8')
        params['wt'] = 'json' # specify json encoding of results
        path = '%s/select/?%s' % (self.path, urlencode(params, True))
        return self._send_request('GET', path)

    def _mlt(self, params):
        # encode the query as utf-8 so urlencode can handle it
        params['q'] = params['q'].encode('utf-8')
        params['wt'] = 'json' # specify json encoding of results
        path = '%s/mlt/?%s' % (self.path, urlencode(params, True))
        return self._send_request('GET', path)

    def _update(self, message, clean_ctrl_chars=True):
        """
        Posts the given xml message to http://<host>:<port>/solr/update and
        returns the result.

        Passing `sanitize` as False will prevent the message from being cleaned
        of control characters (default True). This is done by default because
        these characters would cause Solr to fail to parse the XML. Only pass
        False if you're positive your data is clean.
        """
        path = '%s/update/' % self.path

        # Clean the message of ctrl characters.
        if clean_ctrl_chars:
            message = sanitize(message)

        return self._send_request('POST', path, message, {'Content-type': 'text/xml'})

    def _extract_error(self, headers, response):
        """
        Extract the actual error message from a solr response. Unfortunately,
        this means scraping the html.
        """
        jetty_br = '<br/>                                                \n'
        return "[Reason: %s]\n%s" % (headers.get('reason'), response.replace(jetty_br, ''))

    # Conversion #############################################################

    def _from_python(self, value):
        """
        Converts python values to a form suitable for insertion into the xml
        we send to solr.
        """
        if isinstance(value, datetime):
            value = value.strftime('%Y-%m-%dT%H:%M:%SZ')
        elif isinstance(value, date):
            value = value.strftime('%Y-%m-%dT00:00:00Z')
        elif isinstance(value, bool):
            if value:
                value = 'true'
            else:
                value = 'false'
        else:
            value = unicode(value)
        return value

    def _to_python(self, value):
        """
        Converts values from Solr to native Python values.
        """
        if isinstance(value, (int, float, long, complex)):
            return value

        if isinstance(value, (list, tuple)):
            value = value[0]

        if value == 'true':
            return True
        elif value == 'false':
            return False

        if isinstance(value, basestring):
            possible_datetime = DATETIME_REGEX.search(value)

            if possible_datetime:
                date_values = possible_datetime.groupdict()

                for dk, dv in date_values.items():
                    date_values[dk] = int(dv)

                return datetime(date_values['year'], date_values['month'], date_values['day'], date_values['hour'], date_values['minute'], date_values['second'])

        try:
            # This is slightly gross but it's hard to tell otherwise what the
            # string's original type might have been. Be careful who you trust.
            converted_value = eval(value)

            # Try to handle most built-in types.
            if isinstance(converted_value, (list, tuple, set, dict, int, float, long, complex)):
                return converted_value
        except:
            # If it fails (SyntaxError or its ilk) or we don't trust it,
            # continue on.
            pass

        return value

    # API Methods ############################################################

    def search(self, q, **kwargs):
        """Performs a search and returns the results."""
        params = {'q': q}
        params.update(kwargs)
        response = self._select(params)

        # TODO: make result retrieval lazy and allow custom result objects
        result = self.decoder.decode(response)
        result_kwargs = {}

        if result.get('highlighting'):
            result_kwargs['highlighting'] = result['highlighting']

        if result.get('facet_counts'):
            result_kwargs['facets'] = result['facet_counts']

        if result.get('spellcheck'):
            result_kwargs['spellcheck'] = result['spellcheck']

        return Results(result['response']['docs'], result['response']['numFound'], **result_kwargs)

    def more_like_this(self, q, mltfl, **kwargs):
        """
        Finds and returns results similar to the provided query.

        Requires Solr 1.3+.
        """
        params = {
            'q': q,
            'mlt.fl': mltfl,
        }
        params.update(kwargs)
        response = self._mlt(params)

        result = self.decoder.decode(response)

        if result['response'] is None:
            result['response'] = {
                'docs': [],
                'numFound': 0,
            }

        return Results(result['response']['docs'], result['response']['numFound'])

    def add(self, docs, commit=True):
        """Adds or updates documents. For now, docs is a list of dictionaies
        where each key is the field name and each value is the value to index.
        """
        message = ET.Element('add')
        for doc in docs:
            d = ET.Element('doc')
            for key, value in doc.items():
                # handle lists, tuples, and other iterabes
                if hasattr(value, '__iter__'):
                    for v in value:
                        f = ET.Element('field', name=key)
                        f.text = self._from_python(v)
                        d.append(f)
                # handle strings and unicode
                else:
                    f = ET.Element('field', name=key)
                    f.text = self._from_python(value)
                    d.append(f)
            message.append(d)
        m = ET.tostring(message)
        response = self._update(m)
        # TODO: Supposedly, we can put a <commit /> element in the same post body
        # as the add element. That isn't working for some reason, and it would save us
        # an extra trip to the server. This works for now.
        if commit:
            self.commit()

    def delete(self, id=None, q=None, commit=True, fromPending=True, fromCommitted=True):
        """Deletes documents."""
        if id is None and q is None:
            raise ValueError('You must specify "id" or "q".')
        elif id is not None and q is not None:
            raise ValueError('You many only specify "id" OR "q", not both.')
        elif id is not None:
            m = '<delete><id>%s</id></delete>' % id
        elif q is not None:
            m = '<delete><query>%s</query></delete>' % q
        response = self._update(m)
        # TODO: Supposedly, we can put a <commit /> element in the same post body
        # as the delete element. That isn't working for some reason, and it would save us
        # an extra trip to the server. This works for now.
        if commit:
            self.commit()

    def commit(self):
        response = self._update('<commit />')

    def optimize(self):
        response = self._update('<optimize />')

# Using two-tuples to preserve order.
REPLACEMENTS = (
    # Nuke nasty control characters.
    ('\x00', ''), # Start of heading
    ('\x01', ''), # Start of heading
    ('\x02', ''), # Start of text
    ('\x03', ''), # End of text
    ('\x04', ''), # End of transmission
    ('\x05', ''), # Enquiry
    ('\x06', ''), # Acknowledge
    ('\x07', ''), # Ring terminal bell
    ('\x08', ''), # Backspace
    ('\x0b', ''), # Vertical tab
    ('\x0c', ''), # Form feed
    ('\x0e', ''), # Shift out
    ('\x0f', ''), # Shift in
    ('\x10', ''), # Data link escape
    ('\x11', ''), # Device control 1
    ('\x12', ''), # Device control 2
    ('\x13', ''), # Device control 3
    ('\x14', ''), # Device control 4
    ('\x15', ''), # Negative acknowledge
    ('\x16', ''), # Synchronous idle
    ('\x17', ''), # End of transmission block
    ('\x18', ''), # Cancel
    ('\x19', ''), # End of medium
    ('\x1a', ''), # Substitute character
    ('\x1b', ''), # Escape
    ('\x1c', ''), # File separator
    ('\x1d', ''), # Group separator
    ('\x1e', ''), # Record separator
    ('\x1f', ''), # Unit separator
)

def sanitize(data):
    fixed_string = data

    for bad, good in REPLACEMENTS:
        fixed_string = fixed_string.replace(bad, good)

    return fixed_string

if __name__ == "__main__":
    import doctest
    doctest.testmod()


text:
package net.sf.json.util;

import net.sf.json.JSONException;

/**
 * Defines the contract to handle JsonEvents when building an object or array.
 *
 * @author Andres Almiray <aalmiray@users.sourceforge.net>
 */
public interface JsonEventListener {

   /**
    * Ttriggered when reaching the end of an array.
    */
   void onArrayEnd();

   /**
    * triggered when the start of an array is encountered.
    */
   void onArrayStart();

   /**
    * Triggered when an element has been added to the current array.
    *
    * @param index the index where the element was added
    * @param element the added element
    */
   void onElementAdded( int index, Object element );

   /**
    * Triggered when an exception is thrown.
    *
    * @param jsone the thrown exception
    */
   void onError( JSONException jsone );

   /**
    * triggered when reaching the end of an object.
    */
   void onObjectEnd();

   /**
    * Triggered when the start of an object is encountered.
    */
   void onObjectStart();

   /**
    * Triggered when a property is set on an object
    *
    * @param key the name of the property
    * @param value the value of the property
    * @param accumulated if the value has been accumulated over 'key'
    */
   void onPropertySet( String key, Object value, boolean accumulated );

   /**
    * Triggered when a warning is encountered.
    *
    * @param warning the warning message
    */
   void onWarning( String warning );
}


text:
angular.module('app').controller('favoriteCtrl',['$scope','$http', function($scope, $http){
	$http.get('data/myFavorite.json').then(function(res){
		$scope.list = res.data;
	})
}])


text:
#include "mem/ruby/slicc_interface/RubyRequest.hh"

#include <iostream>

#include "mem/ruby/slicc_interface/RubySlicc_Util.hh"

namespace gem5
{

namespace ruby
{

void
RubyRequest::print(std::ostream& out) const
{
  out << "[RubyRequest: ";
  out << std::hex << "LineAddress = 0x" << m_LineAddress << std::dec << " ";
  out << std::hex << "PhysicalAddress = 0x" << m_PhysicalAddress;
  out << std::dec << " " << "Type = " << m_Type << " ";
  out << std::hex << "ProgramCounter = 0x" << m_ProgramCounter << std::dec;
  out << " " << "AccessMode = " << m_AccessMode << " ";
  out << "Size = " << m_Size << " ";
  out << "Prefetch = " << m_Prefetch << " ";
//  out << "Time = " << getTime() << " ";
  out << "]";
}

bool
RubyRequest::functionalRead(Packet *pkt)
{
    // This needs a little explanation. Initially I thought that this
    // message should be read. But the way the memtester works for now,
    // we should not be reading this message as memtester updates the
    // functional memory only after a write has actually taken place.
    return false;
}

bool
RubyRequest::functionalRead(Packet *pkt, WriteMask &mask)
{
    return false;
}

bool
RubyRequest::functionalWrite(Packet *pkt)
{
    // This needs a little explanation. I am not sure if this message
    // should be written. Essentially the question is how are writes
    // ordered. I am assuming that if a functional write is issued after
    // a timing write to the same address, then the functional write
    // has to overwrite the data for the timing request, even if the
    // timing request has still not been ordered globally.

    if (!pkt->hasData() || !m_pkt->hasData())
        return false;

    uint8_t *data =  m_pkt->getPtr<uint8_t>();

    if (pkt->isMaskedWrite() || m_pkt->isMaskedWrite()) {
        warn("Skiping functional write to/from a masked write packet"
            " (addr: %#x, other addr: %#x).\n", m_PhysicalAddress,
              pkt->getAddr());
        return false;
    }

    Addr wBase = pkt->getAddr();
    Addr wTail = wBase + pkt->getSize();
    Addr mBase = m_PhysicalAddress;
    Addr mTail = mBase + m_Size;

    const uint8_t * pktData = pkt->getConstPtr<uint8_t>();

    Addr cBase = std::max(wBase, mBase);
    Addr cTail = std::min(wTail, mTail);

    for (Addr i = cBase; i < cTail; ++i) {
        data[i - mBase] = pktData[i - wBase];
    }

    // also overwrite the WTData
    testAndWrite(m_PhysicalAddress, m_WTData, pkt);

    return cBase < cTail;
}

} // namespace ruby
} // namespace gem5


text:
"""Fix Khmer and Lao fonts for better coverage."""

__author__ = "roozbeh@google.com (Roozbeh Pournader)"

import os
import sys

from fontTools import ttLib

import coverage
import font_data
import opentype_data

def merge_chars_from_bank(orig_font, bank_font, target_font, chars):
    """Merge glyphs from a bank font to another font.

    Only the glyphs themselves, the horizontal metrics, and the cmaps will be
    copied.
    """
    bank_font = ttLib.TTFont(bank_font)
    orig_font = ttLib.TTFont(orig_font)

    bank_cmap = font_data.get_cmap(bank_font)
    extra_cmap = {}
    for char in sorted(chars):
        assert char in bank_cmap
        bank_glyph_name = bank_cmap[char]
        assert bank_glyph_name not in orig_font['glyf'].glyphs
        orig_font['glyf'][bank_glyph_name] = bank_font['glyf'][bank_glyph_name]
        orig_font['hmtx'][bank_glyph_name] = bank_font['hmtx'][bank_glyph_name]
        extra_cmap[char] = bank_glyph_name
    font_data.add_to_cmap(orig_font, extra_cmap)
    orig_font.save(target_font)

_UNHINTED_FONTS_DIR = os.path.abspath(
    os.path.join(
        os.path.dirname(__file__),
        os.pardir,
       'fonts',
       'individual',
       'unhinted'))

def main(argv):
    """Fix all the fonts given in the command line.

    If they are Lao fonts, make sure they have ZWSP and dotted circle. If they
    are Khmer fonts, make sure they have ZWSP, joiners, and dotted circle."""

    for font_name in argv[1:]:
        if 'Khmer' in font_name:
            script = 'Khmr'
        elif 'Lao' in font_name:
            script = 'Laoo'
        needed_chars = set(opentype_data.SPECIAL_CHARACTERS_NEEDED[script])

        lgc_font_name = (
            os.path.basename(font_name).replace('Khmer', '').replace('Lao', ''))
        lgc_font_name = os.path.join(_UNHINTED_FONTS_DIR, lgc_font_name)

        font_charset = coverage.character_set(font_name)
        missing_chars = needed_chars - font_charset
        if missing_chars:
            merge_chars_from_bank(
                font_name,
                lgc_font_name,
                os.path.dirname(font_name)+'/new/'+os.path.basename(font_name),
                missing_chars)

if __name__ == '__main__':
    main(sys.argv)