text:
[![NPM](https://nodei.co/npm/gulp-compass.png?downloads=true&stars=true)](https://nodei.co/npm/gulp-compass/)

> Compile Sass to CSS using Compass

## Requirements

`gulp-compass` requires the compass ruby gem in order to compile compass. This can easily be installed via Terminal.

```
$ gem update --system
$ gem install compass
```

Please refer the [user guide](http://compass-style.org/install/)

## Installation

Install with [npm](https://npmjs.org/package/gulp-compass)

```
$ npm install gulp-compass --save-dev
```

## Usage

load your compass ``config.rb`` file. Please make sure ``css_dir`` and ``sass_dir`` value on ``config.rb`` file.

* ``css_dir`` default value is ``css``.
* ``sass_dir`` default value is ``sass``.

if ``css_dir`` value is ``stylesheets``, please add ``css`` key as your define.

```javascript
var compass = require('gulp-compass');

gulp.task('compass', function() {
    gulp.src('./src/*.scss')
        .pipe(compass({
            config_file: './config.rb',
            css: 'stylesheets'
        }))
        .pipe(gulp.dest('app/assets/temp'));
});
```

set your project path.

```javascript
var compass = require('gulp-compass'),
    path = require('path');

gulp.task('compass', function() {
    gulp.src('./src/*.scss')
        .pipe(compass({
            project: path.join(__dirname, 'assets'),
            css: 'css',
            sass: 'sass'
        }))
        .pipe(gulp.dest('app/assets/temp'));
});
```

set your compass settings.

```javascript
var compass = require('gulp-compass'),
    minifyCSS = require('gulp-minify-css');

gulp.task('compass', function() {
    gulp.src('./src/*.scss')
        .pipe(compass({
            css: 'app/assets/css',
            sass: 'app/assets/sass',
            image: 'app/assets/images'
        }))
        .pipe(minifyCSS())
        .pipe(gulp.dest('app/assets/temp'));
});
```

Support multiple require option

```javascript
var compass = require('gulp-compass'),
    minifyCSS = require('gulp-minify-css');

gulp.task('compass', function() {
    gulp.src('./src/*.scss')
        .pipe(compass({
            css: 'app/assets/css',
            sass: 'app/assets/sass',
            image: 'app/assets/images',
            require: ['susy', 'modular-scale']
        }))
        .pipe(minifyCSS())
        .pipe(gulp.dest('app/assets/temp'));
});
```

Support return the output of the Compass as the callback

```javascript
var compass = require('gulp-compass'),
    minifyCSS = require('gulp-minify-css');

gulp.task('compass', function() {
    gulp.src('./src/*.scss')
        .pipe(compass({
            css: 'app/assets/css',
            sass: 'app/assets/sass',
            image: 'app/assets/images'
        }))
        .on('error', function(err) {
            // Would like to catch the error here
        })
        .pipe(minifyCSS())
        .pipe(gulp.dest('app/assets/temp'));
});
```

## Configuration

### Configuration Options

#### style

**default:** nested

**description:** The output style for the compiled css.
One of: nested, expanded, compact, or compressed.

#### comments

**default:** true

**description:** Show line comments or not.

#### relative

**default:** true

**description:** Are assets relative.

#### css

**default:** css

**description:** The target directory where you keep your css stylesheets. It is relative to the ``project`` option.

#### sass

**default:** sass

**description:** The source directory where you keep your sass stylesheets. It is relative to the ``project`` option.

#### javascript

**default:** js

**description:** The directory where you keep your javascripts. It is relative to the ``project`` option.

#### font

**default:** font

**description:** The directory where you keep your fonts. It is relative to the ``project`` option.

#### project

**default:** your project base

**description:** The location where all your assets are store.

#### logging

**default:** true

**description:** show/hide compile log message.

#### import_path

**default:** false

**description:** The directory where you keep external Compass plugins or extensions that you would like to make available using the `@import` function. Common use case would be setting this to your `bower_components` directory for example. It is relative to the ``project`` option.

#### require

**default:** false

**format:** ``string`` or ``array``

**description:** Require the given Ruby library before running commands. This is used to access Compass plugins without having a project configuration file.

#### load_all

**default:** false

**description:** Load all the frameworks or extensions found in the FRAMEWORKS_DIR directory.

## Running tests

```
$ gem install sass
$ gem install compass
$ gem install susy
$ gem install modular-scale
$ npm test
```


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. Fl. (New York) 7: 220 (1963)

#### Original name
Sphaeria lateritia Kunze, 1823

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
namespace MassTransit
{
    using System;

    public static class LegacySerializationExtensions
    {
        [Obsolete("Deprecated, use ClearSerialization instead")]
        public static void ClearMessageDeserializers(this IBusFactoryConfigurator configurator)
        {
            configurator.ClearSerialization();
        }

        [Obsolete("Deprecated, use ClearSerialization instead")]
        public static void ClearMessageDeserializers(this IReceiveEndpointConfigurator configurator)
        {
            configurator.ClearSerialization();
        }
    }
}


text:
cleanup()
# example cleanup function
{
  rm -f /tmp/tempfile
  return $?
}

control_z()
{
  echo -en "\n*** CTRL-Z ignored. ***\n"
  echo "You need to kill process if you really need to cancel compilation"
  cleanup
  sleep 5
  exit $?
}

# trap keyboard interrupt (control-z)
trap control_c SIGTSTP

# main() loop
while true; do echo 'hey'; done


text:
body {
	margin: 0px;
	background-color: #333333;
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
table.linkcontainer td{
	background-color: #000000;
	filter:alpha(opacity=70);
	opacity: .7;
	-moz-opacity: .7;
}
td.logo_area{
	border-top-width: 0px;
	border-right-width: 5px;
	border-bottom-width: 0px;
	border-left-width: 0px;
	border-top-style: none;
	border-right-style: none;
	border-bottom-style: none;
	border-left-style: none;
	border-top-color: #FFFFFF;
	border-right-color: #FFFFFF;
	border-bottom-color: #FFFFFF;
	border-left-color: #FFFFFF;
}
td.middle_spacer {
	width: 800px;
	background-color: #666666;
}
td.shadow_right {
	background-image: url(../images_template1/border_shadow_l.jpg);
	background-repeat: repeat-y;
	background-position: left;
}
td.shadow_left {
	background-image: url(../images_template1/border_shadow_r.jpg);
	background-repeat: repeat-y;
	background-position: right;
}
td.body_content {
	padding: 5px;
	background-image: url(../images_template1/bg_content.jpg);
	background-repeat: repeat;
}
td.below_header{
	background-color: #1F1F1F;
	height: 50px;
	color: #CCCCCC;
	padding: 5px;
}
td.main_content_box {
	background-color: #FFFFFF;
}

td.horizontal_column {
	background-color: #000000;
	border-top-width: 15px;
	border-right-width: 0px;
	border-bottom-width: 1px;
	border-left-width: 0px;
	border-top-style: solid;
	border-right-style: solid;
	border-bottom-style: solid;
	border-left-style: solid;
	border-top-color: #000000;
	border-right-color: #000000;
	border-bottom-color: #000000;
	border-left-color: #000000;
	height: 150px;
	display: table-cell;
	vertical-align: top;
}
td.bottom_link_container {
	background-color: #000000;
	text-align: center;
	color: #FFFFFF;
	padding: 5px;
}

td.horizontal_center {
	background-color: #FFFFFF;
	border-top-width: 15px;
	border-right-width: 0px;
	border-bottom-width: 1px;
	border-left-width: 0px;
	border-top-style: solid;
	border-right-style: solid;
	border-bottom-style: solid;
	border-left-style: solid;
	border-top-color: #000000;
	border-right-color: #333333;
	border-bottom-color: #000000;
	border-left-color: #333333;
	height: 150px;
	display: table-cell;
	vertical-align: top;
	background-image: url(../images_template1/header_bg.jpg);
}
td.header_column {
	height: 100px;
	vertical-align: middle;
	color: #FFFFFF;
	font-size: large;
	background-image: url(../images_template1/header2_bg.jpg);
	background-position: top;
}
td.left_content {
	width: 200px;
	padding: 5px;
	vertical-align: top;
	background-image: url(../images_template1/bg_content.jpg);
	background-repeat: repeat;
}

a.main_link:active,a.main_link:visited,a.main_link:link{
	font-weight: bold;
	text-decoration: none;
	display: block;
	width: 100%;
	color: #FFFFFF;
	line-height: 50px;
}
a.main_link:hover{
	background-color:#333333;
	color: #FFFFFF;
}
a.bottom_link:active,a.bottom_link:visited,a.bottom_link:link{
	font-weight: bold;
	text-decoration: none;
	color: #FFFFFF;
}
a.bottom_link:hover{
	color: #CCCCCC;
}
div.bottom_content{
	color: #FFFFFF;
	padding: 5px;
}
div.navigation {
	height: 50px;
	vertical-align: middle;
	text-align: center;
}
.buscador {
	text-align: right;
}


text:
using System.Collections.Generic;
using System.Web.Mvc;
using MvcContrib.FluentHtml.Behaviors;

namespace MvcContrib.FluentHtml
{
	public abstract class ModelWebViewPage<T> : WebViewPage<T>, IViewModelContainer<T> where T : class
	{
		protected readonly List<IBehaviorMarker> behaviors = new List<IBehaviorMarker>();

		protected ModelWebViewPage()
		{
			behaviors.Add(new ValidationBehavior(() => ViewData.ModelState));
		}

		protected ModelWebViewPage(params IBehaviorMarker[] behaviors) : this(null, behaviors) { }

		protected ModelWebViewPage(string htmlNamePrefix, params IBehaviorMarker[] memberBehaviors)
			: this()
		{
			HtmlNamePrefix = htmlNamePrefix;
			if (memberBehaviors != null)
			{
				behaviors.AddRange(memberBehaviors);
			}
		}

		public string HtmlNamePrefix { get; set; }

		public T ViewModel
		{
			get { return ViewData.Model; }
		}

		public IEnumerable<IBehaviorMarker> Behaviors
		{
			get { return behaviors; }
		}

		HtmlHelper IViewModelContainer<T>.Html
		{
			get { return Html; }
		}
	}
}


text:
import arrow
from flexmock import flexmock, flexmock_teardown
from ... import EloquentTestCase
from ...utils import MockConnection

from eloquent.query.builder import QueryBuilder
from eloquent.query.grammars import QueryGrammar
from eloquent.query.processors import QueryProcessor
from eloquent.query.expression import QueryExpression
from eloquent.orm.builder import Builder
from eloquent.orm.model import Model
from eloquent.orm.relations import MorphToMany
from eloquent.orm.relations.pivot import Pivot
from eloquent.orm.collection import Collection

class OrmMorphToManyTestCase(EloquentTestCase):

    def tearDown(self):
        flexmock_teardown()

    def test_eager_constraints_are_properly_added(self):
        relation = self._get_relation()
        relation.get_query().get_query().should_receive('where_in').once().with_args('taggables.taggable_id', [1, 2])
        relation.get_query().should_receive('where').once()\
            .with_args('taggables.taggable_type', relation.get_parent().__class__.__name__)
        model1 = OrmMorphToManyModelStub()
        model1.id = 1
        model2 = OrmMorphToManyModelStub()
        model2.id = 2

        relation.add_eager_constraints([model1, model2])

    def test_attach_inserts_pivot_table_record(self):
        flexmock(MorphToMany, touch_if_touching=lambda: True)
        relation = self._get_relation()
        query = flexmock()
        query.should_receive('from_').once().with_args('taggables').and_return(query)
        query.should_receive('insert').once()\
            .with_args(
                [{
                    'taggable_id': 1,
                    'taggable_type': relation.get_parent().__class__.__name__,
                    'tag_id': 2,
                    'foo': 'bar',
                }])\
            .and_return(True)
        mock_query_builder = flexmock()
        relation.get_query().should_receive('get_query').and_return(mock_query_builder)
        mock_query_builder.should_receive('new_query').once().and_return(query)
        relation.should_receive('touch_if_touching').once()

        relation.attach(2, {'foo': 'bar'})

    def test_detach_remove_pivot_table_record(self):
        flexmock(MorphToMany, touch_if_touching=lambda: True)
        relation = self._get_relation()
        query = flexmock()
        query.should_receive('from_').once().with_args('taggables').and_return(query)
        query.should_receive('where').once().with_args('taggable_id', 1).and_return(query)
        query.should_receive('where').once()\
            .with_args('taggable_type', relation.get_parent().__class__.__name__).and_return(query)
        query.should_receive('where_in').once().with_args('tag_id', [1, 2, 3])
        query.should_receive('delete').once().and_return(True)
        mock_query_builder = flexmock()
        relation.get_query().should_receive('get_query').and_return(mock_query_builder)
        mock_query_builder.should_receive('new_query').once().and_return(query)
        relation.should_receive('touch_if_touching').once()

        self.assertTrue(relation.detach([1, 2, 3]))

    def test_detach_clears_all_records_when_no_ids(self):
        flexmock(MorphToMany, touch_if_touching=lambda: True)
        relation = self._get_relation()
        query = flexmock()
        query.should_receive('from_').once().with_args('taggables').and_return(query)
        query.should_receive('where').once().with_args('taggable_id', 1).and_return(query)
        query.should_receive('where').once()\
            .with_args('taggable_type', relation.get_parent().__class__.__name__).and_return(query)
        query.should_receive('where_in').never()
        query.should_receive('delete').once().and_return(True)
        mock_query_builder = flexmock()
        relation.get_query().should_receive('get_query').and_return(mock_query_builder)
        mock_query_builder.should_receive('new_query').once().and_return(query)
        relation.should_receive('touch_if_touching').once()

        self.assertTrue(relation.detach())

    def _get_relation(self):
        builder, parent = self._get_relation_arguments()[:2]

        return MorphToMany(builder, parent, 'taggable', 'taggables', 'taggable_id', 'tag_id')

    def _get_relation_arguments(self):
        parent = flexmock(Model())
        parent.should_receive('get_morph_class').and_return(parent.__class__.__name__)
        parent.should_receive('get_key').and_return(1)
        parent.should_receive('get_created_at_column').and_return('created_at')
        parent.should_receive('get_updated_at_column').and_return('updated_at')

        query = flexmock(QueryBuilder(MockConnection().prepare_mock(), QueryGrammar(), QueryProcessor()))
        flexmock(Builder)
        builder = Builder(query)
        builder.should_receive('get_query').and_return(query)
        related = flexmock(Model())
        builder.set_model(related)
        builder.should_receive('get_model').and_return(related)

        related.should_receive('get_key_name').and_return('id')
        related.should_receive('get_table').and_return('tags')
        related.should_receive('get_morph_class').and_return(parent.__class__.__name__)

        builder.get_query().should_receive('join').once().with_args('taggables', 'tags.id', '=', 'taggables.tag_id')
        builder.should_receive('where').once().with_args('taggables.taggable_id', '=', 1)
        builder.should_receive('where').once().with_args('taggables.taggable_type', parent.__class__.__name__)

        return builder, parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'relation_name', False

class OrmMorphToManyModelStub(Model):

    __guarded__ = []

class OrmMorphToManyModelPivotStub(Model):

    __guarded__ = []

    def __init__(self):
        super(OrmMorphToManyModelPivotStub, self).__init__()

        self.pivot = OrmMorphToManyPivotStub()

class OrmMorphToManyPivotStub(object):
    pass


text:
const SET_REFERENCE_GRAMMAR_ID = 'WEB_CHAT/SET_REFERENCE_GRAMMAR_ID';

export default function setReferenceGrammarID(referenceGrammarID) {
  return {
    type: SET_REFERENCE_GRAMMAR_ID,
    payload: { referenceGrammarID }
  };
}

export { SET_REFERENCE_GRAMMAR_ID };


text:
using Gallio.Icarus.Controllers.Interfaces;
using MbUnit.Framework;
using Rhino.Mocks;

namespace Gallio.Icarus.Tests
{
    [Category("Views")]
    internal class PropertiesWindowTest
    {
        [Test]
        public void Constructor_Test()
        {
            var projectController = MockRepository.GenerateStub<IProjectController>();
            var propertiesWindow = new PropertiesWindow(projectController);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
	xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC"
	xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI"
	xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
	xmlns:activiti="http://activiti.org/bpmn"
	targetNamespace="Examples">

	<process id="testLoop">

		<startEvent id="theStart" />
		<sequenceFlow id="flow1" sourceRef="theStart" targetRef="timer" />

		<intermediateCatchEvent id="timer">
			<timerEventDefinition>
				<timeDuration>PT5M</timeDuration>
			</timerEventDefinition>
		</intermediateCatchEvent>
		<sequenceFlow id="flow2" sourceRef="timer" targetRef="checkCompletion" />

		<scriptTask id="checkCompletion" scriptFormat="javascript">
			<script>
				 <![CDATA[

				    var counter = execution.getVariable('counter');
				    if (!counter) {
				      counter = 0;
				    }
				    var newCounter = counter + 1;
				    execution.setVariable('counter', newCounter);

                    if (newCounter == 3) {
                      execution.setVariable('completed', true);
                    } else {
                      execution.setVariable('completed', false);
                    }

                ]]>
			</script>
		</scriptTask>
		<sequenceFlow id="flowToGW" sourceRef="checkCompletion" targetRef="exclusivegateway" />
		<exclusiveGateway id="exclusivegateway" name="Exclusive Gateway" default="flow4"></exclusiveGateway>
		<sequenceFlow id="flow3" sourceRef="exclusivegateway" targetRef="theEnd">
			<conditionExpression xsi:type="tFormalExpression">${completed}</conditionExpression>
		</sequenceFlow>
		<sequenceFlow id="flow4" sourceRef="exclusivegateway" targetRef="timer"> </sequenceFlow>

		<endEvent id="theEnd" />

	</process>

</definitions>


text:
#ifndef WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_FRAMEWORK_PACKET_LOSS_TEST_H_
#define WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_FRAMEWORK_PACKET_LOSS_TEST_H_

#include <list>

#include "normal_async_test.h"

class PacketLossTest : public NormalAsyncTest
{
public:
    PacketLossTest();
    virtual ~PacketLossTest() {if(_lastFrame) {delete [] _lastFrame; _lastFrame = NULL;}}
    virtual void Encoded(const webrtc::EncodedImage& encodedImage);
    virtual void Decoded(const webrtc::I420VideoFrame& decodedImage);
protected:
    PacketLossTest(std::string name, std::string description);
    PacketLossTest(std::string name,
                   std::string description,
                   double lossRate,
                   bool useNack,
                   unsigned int rttFrames = 0);

    virtual void Setup();
    virtual void Teardown();
    virtual void CodecSpecific_InitBitrate();
    virtual int DoPacketLoss();
    virtual int NextPacket(int size, unsigned char **pkg);
    virtual int ByteLoss(int size, unsigned char *pkg, int bytesToLose);
    virtual void InsertPacket(webrtc::VideoFrame *buf, unsigned char *pkg,
                              int size);
    int _inBufIdx;
    int _outBufIdx;

    // When NACK is being simulated _lossProbabilty is zero,
    // otherwise it is set equal to _lossRate.
    // Desired channel loss rate.
    double _lossRate;
    // Probability used to simulate packet drops.
    double _lossProbability;

    int _totalKept;
    int _totalThrown;
    int _sumChannelBytes;
    std::list<WebRtc_UWord32> _frameQueue;
    WebRtc_UWord8* _lastFrame;
    WebRtc_UWord32 _lastFrameLength;
};

#endif // WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_FRAMEWORK_PACKET_LOSS_TEST_H_


text:
from django.urls import path, re_path
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from oscar.core.application import OscarConfig

from oscar_accounts.api import decorators

class AccountsAPIConfig(OscarConfig):
    name = 'oscar_accounts.api'
    verbose_name = _('Accounts API')
    label = 'oscar_accounts_api'
    namespace = 'oscar_accounts_api'

    def ready(self):
        from oscar_accounts.api import views

        self.accounts_view = views.AccountsView
        self.account_view = views.AccountView
        self.account_redemptions_view = views.AccountRedemptionsView
        self.account_refunds_view = views.AccountRefundsView

        self.transfer_view = views.TransferView
        self.transfer_reverse_view = views.TransferReverseView
        self.transfer_refunds_view = views.TransferRefundsView

    def get_urls(self):
        urls = [
            path('accounts/', self.accounts_view.as_view(), name='accounts'),
            path('accounts/<str:code>/', self.account_view.as_view(), name='account'),
            path(
                'accounts/<str:code>/redemptions/',
                self.account_redemptions_view.as_view(),
                name='account-redemptions'
            ),
            path('accounts/<str:code>/refunds/', self.account_refunds_view.as_view(), name='account-refunds'),
            re_path(
                r'^transfers/(?P<reference>[A-Z0-9]{32})/$',
                self.transfer_view.as_view(),
                name='transfer'
            ),
            re_path(
                r'^transfers/(?P<reference>[A-Z0-9]{32})/reverse/$',
                self.transfer_reverse_view.as_view(),
                name='transfer-reverse'
            ),
            re_path(
                r'^transfers/(?P<reference>[A-Z0-9]{32})/refunds/$',
                self.transfer_refunds_view.as_view(),
                name='transfer-refunds'
            ),
        ]
        return self.post_process_urls(urls)

    def get_url_decorator(self, url_name):
        return lambda x: csrf_exempt(decorators.basicauth(x))


text:
HX711
=====

An Arduino library to interface the Avia Semiconductor HX711 24-Bit Analog-to-Digital Converter (ADC) for Weight Scales.

This is my humble attempt at creating an Arduino library for this ADC:
http://www.dfrobot.com/image/data/SEN0160/hx711_english.pdf

Other libraries exist, including this very good one, which I first used and which is the starting point for my library:
https://github.com/aguegu/ardulibs/tree/master/hx711

# Advantages of this library
Although other libraries exist, I needed a slightly different approach, so here's how my library is different than others:

1. It provides a tare() function, which "resets" the scale to 0. Many other implementations calculate the tare weight when the ADC is initialized only. I needed a way to be able to set the tare weight at any time. Use case: place an empty container on the scale, call tare() to reset the readings to 0, fill the container and get the weight of the content.

2. It provides a power_down() function, to put the ADC into a low power mode. According to the datasheet, "When PD_SCK pin changes from low to high and stays at high for longer than 60μs, HX711 enters power down mode". Use case: battery powered scales. Accordingly, there is a power_up() function to get the chip out of the low power mode.

3. It has a set_gain(byte gain) function that allows you to set the gain factor and select the channel. According to the datasheet, "Channel A can be programmed with a gain of 128 or 64, corresponding to a full-scale differential input voltage of ±20mV or ±40mV respectively, when a 5V supply is connected to AVDD analog power supply pin. Channel B has a fixed gain of 32.". The same function is used to select the channel A or channel B, by passing 128 or 64 for channel A, or 32 for channel B as the parameter. The default value is 128, which means "channel A with a gain factor of 128", so one can simply call set_gain(). Also, the function is called from the constructor.

4. The constructor has an extra parameter "gain" that allows you to set the gain factor and channel. The constructor calls the "set_gain" function mentioned above.

5. The "get_value" and "get_units" functions can receive an extra parameter "times", and they will return the average of multiple readings instead of a single reading.

# How to Calibrate Your Scale

1. Call set_scale() with no parameter.
2. Call tare() with no parameter.
3. Place a known weight on the scale and call get_units(10).
4. Divide the result in step 3 to your known weight. You should get about the parameter you need to pass to set_scale.
5. Adjust the parameter in step 4 until you get an accurate reading.

# How to use
See the example in examples/HX711SerialBegin. Please don't use examples/HX711Serial anymore. It is deprecated because the pin definition within the constructor
is not timing safe. (#29)


text:
require 'rails_helper'

RSpec.describe 'Recoverable', type: :feature do
  def visit_new_password_path
    visit new_user_session_path
    click_link 'Forgot your password?'
  end

  def request_forgot_password(&block)
    visit_new_password_path

    fill_in 'user_email', with: 'user@test.com'
    yield if block_given?

    click_button 'Send me reset password instructions'
  end

  context 'with primary email' do
    it 'sends the password reset email' do
      user = create_user
      visit_new_password_path

      request_forgot_password do
        fill_in 'user_email', with: user.email
      end

      expect(current_path).to eq new_user_session_path
      expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.')
    end

    context 'when not confirmed' do
      it 'shows the error message' do
        user = create_user(confirm: false)
        visit_new_password_path

        request_forgot_password do
          fill_in 'user_email', with: user.email
        end

        expect(current_path).to eq new_user_session_path
        expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.')
      end
    end
  end

  context 'with non-primary email' do
    context 'when confirmed' do
      before do
        user = create_user
        secondary_email = create_email(user)
        visit_new_password_path

        request_forgot_password do
          fill_in 'user_email', with: secondary_email.email
        end
      end

      it 'sends the password reset email' do
        expect(current_path).to eq new_user_session_path
        expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.')
      end

      it 'redirects to password reset page when visiting the link' do
        link = ActionMailer::Base.deliveries.last.body.to_s.scan(/<a\s[^>]*href="([^"]*)"/x)[0][0]
        visit link

        fill_in 'user_password', with: 'abcdefgh'
        fill_in 'user_password_confirmation', with: 'abcdefgh'
        click_button 'Change my password'

        expect(page).to have_selector('div', text: 'Your password has been changed successfully. You are now signed in.')
      end
    end

    context 'when not confirmed' do
      it 'shows the error message' do
        user = create_user
        secondary_email = create_email(user, confirm: false)
        visit_new_password_path

        request_forgot_password do
          fill_in 'user_email', with: secondary_email.email
        end

        expect(current_path).to eq new_user_session_path
        expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.')
      end
    end
  end

  context 'with non-existing email' do
    before do
      visit_new_password_path

      request_forgot_password do
        fill_in 'user_email', with: "#{SecureRandom.base64}@example.com"
      end
    end

    it 'shows email does not exist' do
      expect(current_path).to eq '/users/password'
      expect(page).to have_selector('div', text: 'Email not found')
    end
  end
end


text:
begin
  require_relative 'dummyparser'
  require 'test/unit'
  ripper_test = true
  module TestRipper; end
rescue LoadError
end

class TestRipper::ParserEvents < Test::Unit::TestCase

  def test_event_coverage
    dispatched = Ripper::PARSER_EVENTS
    tested = self.class.instance_methods(false).grep(/\Atest_(\w+)/) {$1.intern}
    assert_empty dispatched-tested
  end

  def parse(str, nm = nil, &bl)
    dp = DummyParser.new(str)
    dp.hook(*nm, &bl) if nm
    dp.parse.to_s
  end

  def compile_error(str)
    parse(str, :compile_error) {|e, msg| return msg}
  end

  def test_program
    thru_program = false
    assert_equal '[void()]', parse('', :on_program) {thru_program = true}
    assert_equal true, thru_program
  end

  def test_stmts_new
    assert_equal '[void()]', parse('')
  end

  def test_stmts_add
    assert_equal '[ref(nil)]', parse('nil')
    assert_equal '[ref(nil),ref(nil)]', parse('nil;nil')
    assert_equal '[ref(nil),ref(nil),ref(nil)]', parse('nil;nil;nil')
  end

  def test_void_stmt
    assert_equal '[void()]', parse('')
    assert_equal '[void()]', parse('; ;')
  end

  def test_var_ref
    assert_equal '[assign(var_field(a),ref(a))]', parse('a=a')
    assert_equal '[ref(nil)]', parse('nil')
    assert_equal '[ref(true)]', parse('true')
  end

  def test_vcall
    assert_equal '[vcall(a)]', parse('a')
  end

  def test_BEGIN
    assert_equal '[BEGIN([void()])]', parse('BEGIN{}')
    assert_equal '[BEGIN([ref(nil)])]', parse('BEGIN{nil}')
  end

  def test_END
    assert_equal '[END([void()])]', parse('END{}')
    assert_equal '[END([ref(nil)])]', parse('END{nil}')
  end

  def test_alias
    assert_equal '[alias(symbol_literal(a),symbol_literal(b))]', parse('alias a b')
  end

  def test_var_alias
    assert_equal '[valias($a,$g)]', parse('alias $a $g')
  end

  def test_alias_error
    assert_equal '[aliaserr(valias($a,$1))]', parse('alias $a $1')
  end

  def test_arglist
    assert_equal '[fcall(m,[])]', parse('m()')
    assert_equal '[fcall(m,[1])]', parse('m(1)')
    assert_equal '[fcall(m,[1,2])]', parse('m(1,2)')
    assert_equal '[fcall(m,[*vcall(r)])]', parse('m(*r)')
    assert_equal '[fcall(m,[1,*vcall(r)])]', parse('m(1,*r)')
    assert_equal '[fcall(m,[1,2,*vcall(r)])]', parse('m(1,2,*r)')
    assert_equal '[fcall(m,[&vcall(r)])]', parse('m(&r)')
    assert_equal '[fcall(m,[1,&vcall(r)])]', parse('m(1,&r)')
    assert_equal '[fcall(m,[1,2,&vcall(r)])]', parse('m(1,2,&r)')
    assert_equal '[fcall(m,[*vcall(a),&vcall(b)])]', parse('m(*a,&b)')
    assert_equal '[fcall(m,[1,*vcall(a),&vcall(b)])]', parse('m(1,*a,&b)')
    assert_equal '[fcall(m,[1,2,*vcall(a),&vcall(b)])]', parse('m(1,2,*a,&b)')
  end

  def test_args_add
    thru_args_add = false
    parse('m(a)', :on_args_add) {thru_args_add = true}
    assert_equal true, thru_args_add
  end

  def test_args_add_block
    thru_args_add_block = false
    parse('m(&b)', :on_args_add_block) {thru_args_add_block = true}
    assert_equal true, thru_args_add_block
  end

  def test_args_add_star
    thru_args_add_star = false
    parse('m(*a)', :on_args_add_star) {thru_args_add_star = true}
    assert_equal true, thru_args_add_star
    thru_args_add_star = false
    parse('m(*a, &b)', :on_args_add_star) {thru_args_add_star = true}
    assert_equal true, thru_args_add_star
  end

  def test_args_new
    thru_args_new = false
    parse('m()', :on_args_new) {thru_args_new = true}
    assert_equal true, thru_args_new
  end

  def test_arg_paren
    # FIXME
  end

  def test_aref
    assert_equal '[aref(vcall(v),[1])]', parse('v[1]')
    assert_equal '[aref(vcall(v),[1,2])]', parse('v[1,2]')
  end

  def test_assoclist_from_args
    thru_assoclist_from_args = false
    parse('{a=>b}', :on_assoclist_from_args) {thru_assoclist_from_args = true}
    assert_equal true, thru_assoclist_from_args
  end

  def test_assocs
    assert_equal '[fcall(m,[assocs(assoc(1,2))])]', parse('m(1=>2)')
    assert_equal '[fcall(m,[assocs(assoc(1,2),assoc(3,4))])]', parse('m(1=>2,3=>4)')
    assert_equal '[fcall(m,[3,assocs(assoc(1,2))])]', parse('m(3,1=>2)')
  end

  def test_assoc_new
    thru_assoc_new = false
    parse('{a=>b}', :on_assoc_new) {thru_assoc_new = true}
    assert_equal true, thru_assoc_new
  end

  def test_assoc_splat
    thru_assoc_splat = false
    parse('m(**h)', :on_assoc_splat) {thru_assoc_splat = true}
    assert_equal true, thru_assoc_splat
  end

  def test_aref_field
    assert_equal '[assign(aref_field(vcall(a),[1]),2)]', parse('a[1]=2')
  end

  def test_arg_ambiguous
    thru_arg_ambiguous = false
    parse('m //', :on_arg_ambiguous) {thru_arg_ambiguous = true}
    assert_equal true, thru_arg_ambiguous
  end

  def test_operator_ambiguous
    thru_operator_ambiguous = false
    parse('a=1; a %[]', :on_operator_ambiguous) {thru_operator_ambiguous = true}
    assert_equal true, thru_operator_ambiguous
  end

  def test_array   # array literal
    assert_equal '[array([1,2,3])]', parse('[1,2,3]')
    assert_equal '[array([abc,def])]', parse('%w[abc def]')
    assert_equal '[array([abc,def])]', parse('%W[abc def]')
  end

  def test_assign   # generic assignment
    assert_equal '[assign(var_field(v),1)]', parse('v=1')
  end

  def test_assign_error
    # for test_coverage
  end

  def test_assign_error_backref
    thru_assign_error = false
    parse('$` = 1', :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
    thru_assign_error = false
    parse('$`, _ = 1', :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
  end

  def test_assign_error_const_qualified
    thru_assign_error = false
    parse('self::X = 1', :on_assign_error) {thru_assign_error = true}
    assert_equal false, thru_assign_error
    parse("def m\n self::X = 1\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
    thru_assign_error = false
    parse("def m\n self::X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
  end

  def test_assign_error_const
    thru_assign_error = false
    parse('X = 1', :on_assign_error) {thru_assign_error = true}
    assert_equal false, thru_assign_error
    parse("def m\n X = 1\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
    thru_assign_error = false
    parse("def m\n X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
  end

  def test_assign_error_const_toplevel
    thru_assign_error = false
    parse('::X = 1', :on_assign_error) {thru_assign_error = true}
    assert_equal false, thru_assign_error
    parse("def m\n ::X = 1\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
    thru_assign_error = false
    parse("def m\n ::X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
    assert_equal true, thru_assign_error
  end

  def test_bare_assoc_hash
    thru_bare_assoc_hash = false
    parse('x[a=>b]', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
    assert_equal true, thru_bare_assoc_hash
    thru_bare_assoc_hash = false
    parse('x[1, a=>b]', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
    assert_equal true, thru_bare_assoc_hash
    thru_bare_assoc_hash = false
    parse('x(a=>b)', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
    assert_equal true, thru_bare_assoc_hash
    thru_bare_assoc_hash = false
    parse('x(1, a=>b)', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
    assert_equal true, thru_bare_assoc_hash
  end

  def test_begin
    thru_begin = false
    parse('begin end', :on_begin) {thru_begin = true}
    assert_equal true, thru_begin
  end

  %w"and or + - * / % ** | ^ & <=> > >= < <= == === != =~ !~ << >> && ||".each do |op|
    define_method("test_binary(#{op})") do
      thru_binary = false
      parse("a #{op} b", :on_binary) {thru_binary = true}
      assert_equal true, thru_binary
    end
  end

  def test_blockarg
    thru_blockarg = false
    parse("def a(&b) end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("def a(x, &b) end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg

    thru_blockarg = false
    parse("proc{|&b|}", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc{|x, &b|}", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc{|&b;y|}", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc{|&b,x;y|}", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg

    thru_blockarg = false
    parse("proc do |&b| end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc do |&b, x| end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc do |&b;y| end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
    thru_blockarg = false
    parse("proc do |&b, x;y| end", :on_blockarg) {thru_blockarg = true}
    assert_equal true, thru_blockarg
  end

  def test_block_var
    thru_block_var = false
    parse("proc{||}", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc{| |}", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc{|x|}", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc{|;y|}", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc{|x;y|}", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var

    thru_block_var = false
    parse("proc do || end", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc do | | end", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc do |x| end", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc do |;y| end", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
    thru_block_var = false
    parse("proc do |x;y| end", :on_block_var) {thru_block_var = true}
    assert_equal true, thru_block_var
  end

  def test_block_var_add_block
    # not used
  end

  def test_block_var_add_star
    # not used
  end

  def test_bodystmt
    thru_bodystmt = false
    parse("class X\nend", :on_bodystmt) {thru_bodystmt = true}
    assert_equal true, thru_bodystmt
  end

  def test_call
    bug2233 = '[ruby-core:26165]'
    tree = nil

    thru_call = false
    assert_nothing_raised {
      tree = parse("self.foo", :on_call) {thru_call = true}
    }
    assert_equal true, thru_call
    assert_equal "[call(ref(self),.,foo)]", tree
    thru_call = false
    assert_nothing_raised(bug2233) {
      tree = parse("foo.()", :on_call) {thru_call = true}
    }
    assert_equal true, thru_call
    assert_equal "[call(vcall(foo),.,call,[])]", tree
  end

  def test_excessed_comma
    thru_excessed_comma = false
    parse("proc{|x,|}", :on_excessed_comma) {thru_excessed_comma = true}
    assert_equal true, thru_excessed_comma
    thru_excessed_comma = false
    parse("proc{|x,y,|}", :on_excessed_comma) {thru_excessed_comma = true}
    assert_equal true, thru_excessed_comma

    thru_excessed_comma = false
    parse("proc do |x,| end", :on_excessed_comma) {thru_excessed_comma = true}
    assert_equal true, thru_excessed_comma
    thru_excessed_comma = false
    parse("proc do |x,y,| end", :on_excessed_comma) {thru_excessed_comma = true}
    assert_equal true, thru_excessed_comma
  end

  def test_heredoc
    bug1921 = '[ruby-core:24855]'
    thru_heredoc_beg = false
    tree = parse("<""<EOS\nheredoc\nEOS\n", :on_heredoc_beg) {thru_heredoc_beg = true}
    assert_equal true, thru_heredoc_beg
    assert_match(/string_content\(\),heredoc\n/, tree, bug1921)
    heredoc = nil
    parse("<""<EOS\nheredoc1\nheredoc2\nEOS\n", :on_string_add) {|e, n, s| heredoc = s}
    assert_equal("heredoc1\nheredoc2\n", heredoc, bug1921)
    heredoc = nil
    parse("<""<-EOS\nheredoc1\nheredoc2\n\tEOS\n", :on_string_add) {|e, n, s| heredoc = s}
    assert_equal("heredoc1\nheredoc2\n", heredoc, bug1921)
  end

  def test_massign
    thru_massign = false
    parse("a, b = 1, 2", :on_massign) {thru_massign = true}
    assert_equal true, thru_massign
  end

  def test_mlhs_add
    thru_mlhs_add = false
    parse("a, b = 1, 2", :on_mlhs_add) {thru_mlhs_add = true}
    assert_equal true, thru_mlhs_add
  end

  def test_mlhs_add_star
    bug2232 = '[ruby-core:26163]'
    bug4364 = '[ruby-core:35078]'

    thru_mlhs_add_star = false
    tree = parse("a, *b = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
    assert_equal true, thru_mlhs_add_star
    assert_match(/mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\),b\)/, tree)
    thru_mlhs_add_star = false
    tree = parse("a, *b, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
    assert_equal true, thru_mlhs_add_star
    assert_match(/mlhs_add\(mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\),b\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug2232)
    thru_mlhs_add_star = false
    tree = parse("a, *, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
    assert_equal true, thru_mlhs_add_star
    assert_match(/mlhs_add\(mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\)\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
    thru_mlhs_add_star = false
    tree = parse("*b, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
    assert_equal true, thru_mlhs_add_star
    assert_match(/mlhs_add\(mlhs_add_star\(mlhs_new\(\),b\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
    thru_mlhs_add_star = false
    tree = parse("*, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
    assert_equal true, thru_mlhs_add_star
    assert_match(/mlhs_add\(mlhs_add_star\(mlhs_new\(\)\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
  end

  def test_mlhs_new
    thru_mlhs_new = false
    parse("a, b = 1, 2", :on_mlhs_new) {thru_mlhs_new = true}
    assert_equal true, thru_mlhs_new
  end

  def test_mlhs_paren
    thru_mlhs_paren = false
    parse("a, b = 1, 2", :on_mlhs_paren) {thru_mlhs_paren = true}
    assert_equal false, thru_mlhs_paren
    thru_mlhs_paren = false
    parse("(a, b) = 1, 2", :on_mlhs_paren) {thru_mlhs_paren = true}
    assert_equal true, thru_mlhs_paren
  end

  def test_brace_block
    thru_brace_block = false
    parse('proc {}', :on_brace_block) {thru_brace_block = true}
    assert_equal true, thru_brace_block
  end

  def test_break
    thru_break = false
    parse('proc {break}', :on_break) {thru_break = true}
    assert_equal true, thru_break
  end

  def test_case
    thru_case = false
    parse('case foo when true; end', :on_case) {thru_case = true}
    assert_equal true, thru_case
  end

  def test_class
    thru_class = false
    parse('class Foo; end', :on_class) {thru_class = true}
    assert_equal true, thru_class
  end

  def test_class_name_error
    thru_class_name_error = false
    parse('class foo; end', :on_class_name_error) {thru_class_name_error = true}
    assert_equal true, thru_class_name_error
  end

  def test_command
    thru_command = false
    parse('foo a b', :on_command) {thru_command = true}
    assert_equal true, thru_command
  end

  def test_command_call
    thru_command_call = false
    parse('foo.bar a, b', :on_command_call) {thru_command_call = true}
    assert_equal true, thru_command_call
  end

  def test_const_ref
    thru_const_ref = false
    parse('class A;end', :on_const_ref) {thru_const_ref = true}
    assert_equal true, thru_const_ref
    thru_const_ref = false
    parse('module A;end', :on_const_ref) {thru_const_ref = true}
    assert_equal true, thru_const_ref
  end

  def test_const_path_field
    thru_const_path_field = false
    parse('foo::X = 1', :on_const_path_field) {thru_const_path_field = true}
    assert_equal true, thru_const_path_field
  end

  def test_const_path_ref
    thru_const_path_ref = false
    parse('foo::X', :on_const_path_ref) {thru_const_path_ref = true}
    assert_equal true, thru_const_path_ref
  end

  def test_def
    thru_def = false
    parse('def foo; end', :on_def) {
      thru_def = true
    }
    assert_equal true, thru_def
    assert_equal '[def(foo,[],bodystmt([void()]))]', parse('def foo ;end')
  end

  def test_defined
    thru_defined = false
    parse('defined?(x)', :on_defined) {thru_defined = true}
    assert_equal true, thru_defined
  end

  def test_defs
    thru_defs = false
    parse('def foo.bar; end', :on_defs) {thru_defs = true}
    assert_equal true, thru_defs
  end

  def test_do_block
    thru_do_block = false
    parse('proc do end', :on_do_block) {thru_do_block = true}
    assert_equal true, thru_do_block
  end

  def test_dot2
    thru_dot2 = false
    parse('a..b', :on_dot2) {thru_dot2 = true}
    assert_equal true, thru_dot2
  end

  def test_dot3
    thru_dot3 = false
    parse('a...b', :on_dot3) {thru_dot3 = true}
    assert_equal true, thru_dot3
  end

  def test_dyna_symbol
    thru_dyna_symbol = false
    parse(':"#{foo}"', :on_dyna_symbol) {thru_dyna_symbol = true}
    assert_equal true, thru_dyna_symbol

    thru_dyna_symbol = false
    parse('{"#{foo}": 1}', :on_dyna_symbol) {thru_dyna_symbol = true}
    assert_equal true, thru_dyna_symbol
  end

  def test_else
    thru_else = false
    parse('if foo; bar else zot end', :on_else) {thru_else = true}
    assert_equal true, thru_else
  end

  def test_elsif
    thru_elsif = false
    parse('if foo; bar elsif qux; zot end', :on_elsif) {thru_elsif = true}
    assert_equal true, thru_elsif
  end

  def test_ensure
    thru_ensure = false
    parse('begin foo ensure bar end', :on_ensure) {thru_ensure = true}
    assert_equal true, thru_ensure
  end

  def test_fcall
    thru_fcall = false
    parse('foo()', :on_fcall) {thru_fcall = true}
    assert_equal true, thru_fcall
  end

  def test_field
    thru_field = false
    parse('foo.x = 1', :on_field) {thru_field = true}
    assert_equal true, thru_field
  end

  def test_for
    thru_for = false
    parse('for i in foo; end', :on_for) {thru_for = true}
    assert_equal true, thru_for
  end

  def test_hash
    thru_hash = false
    parse('{1=>2}', :on_hash) {thru_hash = true}
    assert_equal true, thru_hash
    thru_hash = false
    parse('{a: 2}', :on_hash) {thru_hash = true}
    assert_equal true, thru_hash
  end

  def test_if
    thru_if = false
    parse('if false; end', :on_if) {thru_if = true}
    assert_equal true, thru_if
  end

  def test_if_mod
    thru_if_mod = false
    parse('nil if nil', :on_if_mod) {thru_if_mod = true}
    assert_equal true, thru_if_mod
  end

  def test_ifop
    thru_ifop = false
    parse('a ? b : c', :on_ifop) {thru_ifop = true}
    assert_equal true, thru_ifop
  end

  def test_lambda
    thru_lambda = false
    parse('->{}', :on_lambda) {thru_lambda = true}
    assert_equal true, thru_lambda
  end

  def test_magic_comment
    thru_magic_comment = false
    parse('# -*- bug-5753: ruby-dev:44984 -*-', :on_magic_comment) {|*x|thru_magic_comment = x}
    assert_equal [:on_magic_comment, "bug_5753", "ruby-dev:44984"], thru_magic_comment
  end

  def test_method_add_block
    thru_method_add_block = false
    parse('a {}', :on_method_add_block) {thru_method_add_block = true}
    assert_equal true, thru_method_add_block
    thru_method_add_block = false
    parse('a do end', :on_method_add_block) {thru_method_add_block = true}
    assert_equal true, thru_method_add_block
  end

  def test_method_add_arg
    thru_method_add_arg = false
    parse('a()', :on_method_add_arg) {thru_method_add_arg = true}
    assert_equal true, thru_method_add_arg
    thru_method_add_arg = false
    parse('a {}', :on_method_add_arg) {thru_method_add_arg = true}
    assert_equal true, thru_method_add_arg
    thru_method_add_arg = false
    parse('a.b(1)', :on_method_add_arg) {thru_method_add_arg = true}
    assert_equal true, thru_method_add_arg
    thru_method_add_arg = false
    parse('a::b(1)', :on_method_add_arg) {thru_method_add_arg = true}
    assert_equal true, thru_method_add_arg
  end

  def test_module
    thru_module = false
    parse('module A; end', :on_module) {thru_module = true}
    assert_equal true, thru_module
  end

  def test_mrhs_add
    thru_mrhs_add = false
    parse('a = a, b', :on_mrhs_add) {thru_mrhs_add = true}
    assert_equal true, thru_mrhs_add
  end

  def test_mrhs_add_star
    thru_mrhs_add_star = false
    parse('a = a, *b', :on_mrhs_add_star) {thru_mrhs_add_star = true}
    assert_equal true, thru_mrhs_add_star
  end

  def test_mrhs_new
    thru_mrhs_new = false
    parse('a = *a', :on_mrhs_new) {thru_mrhs_new = true}
    assert_equal true, thru_mrhs_new
  end

  def test_mrhs_new_from_args
    thru_mrhs_new_from_args = false
    parse('a = a, b', :on_mrhs_new_from_args) {thru_mrhs_new_from_args = true}
    assert_equal true, thru_mrhs_new_from_args
  end

  def test_next
    thru_next = false
    parse('a {next}', :on_next) {thru_next = true}
    assert_equal true, thru_next
  end

  def test_opassign
    thru_opassign = false
    parse('a += b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a -= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a *= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a /= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a %= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a **= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a &= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a |= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a <<= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a >>= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a &&= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a ||= b', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
    thru_opassign = false
    parse('a::X ||= c 1', :on_opassign) {thru_opassign = true}
    assert_equal true, thru_opassign
  end

  def test_opassign_error
    thru_opassign = []
    events = [:on_opassign]
    parse('$~ ||= 1', events) {|a,*b|
      thru_opassign << a
    }
    assert_equal events, thru_opassign
  end

  def test_param_error
    thru_param_error = false
    parse('def foo(A) end', :on_param_error) {thru_param_error = true}
    assert_equal true, thru_param_error
    thru_param_error = false
    parse('def foo($a) end', :on_param_error) {thru_param_error = true}
    assert_equal true, thru_param_error
    thru_param_error = false
    parse('def foo(@a) end', :on_param_error) {thru_param_error = true}
    assert_equal true, thru_param_error
    thru_param_error = false
    parse('def foo(@@a) end', :on_param_error) {thru_param_error = true}
    assert_equal true, thru_param_error
  end

  def test_params
    thru_params = false
    parse('a {||}', :on_params) {thru_params = true}
    assert_equal true, thru_params
    thru_params = false
    parse('a {|x|}', :on_params) {thru_params = true}
    assert_equal true, thru_params
    thru_params = false
    parse('a {|*x|}', :on_params) {thru_params = true}
    assert_equal true, thru_params
  end

  def test_paren
    thru_paren = false
    parse('()', :on_paren) {thru_paren = true}
    assert_equal true, thru_paren
  end

  def test_parse_error
    thru_parse_error = false
    parse('<>', :on_parse_error) {thru_parse_error = true}
    assert_equal true, thru_parse_error
  end

  def test_qwords_add
    thru_qwords_add = false
    parse('%w[a]', :on_qwords_add) {thru_qwords_add = true}
    assert_equal true, thru_qwords_add
  end

  def test_qsymbols_add
    thru_qsymbols_add = false
    parse('%i[a]', :on_qsymbols_add) {thru_qsymbols_add = true}
    assert_equal true, thru_qsymbols_add
  end

  def test_symbols_add
    thru_symbols_add = false
    parse('%I[a]', :on_symbols_add) {thru_symbols_add = true}
    assert_equal true, thru_symbols_add
  end

  def test_qwords_new
    thru_qwords_new = false
    parse('%w[]', :on_qwords_new) {thru_qwords_new = true}
    assert_equal true, thru_qwords_new
  end

  def test_qsymbols_new
    thru_qsymbols_new = false
    parse('%i[]', :on_qsymbols_new) {thru_qsymbols_new = true}
    assert_equal true, thru_qsymbols_new
  end

  def test_symbols_new
    thru_symbols_new = false
    parse('%I[]', :on_symbols_new) {thru_symbols_new = true}
    assert_equal true, thru_symbols_new
  end

  def test_redo
    thru_redo = false
    parse('redo', :on_redo) {thru_redo = true}
    assert_equal true, thru_redo
  end

  def test_regexp_add
    thru_regexp_add = false
    parse('/foo/', :on_regexp_add) {thru_regexp_add = true}
    assert_equal true, thru_regexp_add
  end

  def test_regexp_literal
    thru_regexp_literal = false
    parse('//', :on_regexp_literal) {thru_regexp_literal = true}
    assert_equal true, thru_regexp_literal
  end

  def test_regexp_new
    thru_regexp_new = false
    parse('//', :on_regexp_new) {thru_regexp_new = true}
    assert_equal true, thru_regexp_new
  end

  def test_rescue
    thru_rescue = false
    parsed = parse('begin; 1; rescue => e; 2; end', :on_rescue) {thru_rescue = true}
    assert_equal true, thru_rescue
    assert_match(/1.*rescue/, parsed)
    assert_match(/rescue\(,var_field\(e\),\[2\]\)/, parsed)
  end

  def test_rescue_class
    thru_rescue = false
    parsed = parse('begin; 1; rescue RuntimeError => e; 2; end', :on_rescue) {thru_rescue = true}
    assert_equal true, thru_rescue
    assert_match(/1.*rescue/, parsed)
    assert_match(/rescue\(\[ref\(RuntimeError\)\],var_field\(e\),\[2\]\)/, parsed)
  end

  def test_rescue_mod
    thru_rescue_mod = false
    parsed = parse('1 rescue 2', :on_rescue_mod) {thru_rescue_mod = true}
    assert_equal true, thru_rescue_mod
    bug4716 = '[ruby-core:36248]'
    assert_equal "[rescue_mod(1,2)]", parsed, bug4716
  end

  def test_rest_param
    thru_rest_param = false
    parse('def a(*) end', :on_rest_param) {thru_rest_param = true}
    assert_equal true, thru_rest_param
    thru_rest_param = false
    parse('def a(*x) end', :on_rest_param) {thru_rest_param = true}
    assert_equal true, thru_rest_param
  end

  def test_retry
    thru_retry = false
    parse('retry', :on_retry) {thru_retry = true}
    assert_equal true, thru_retry
  end

  def test_return
    thru_return = false
    parse('return a', :on_return) {thru_return = true}
    assert_equal true, thru_return
  end

  def test_return0
    thru_return0 = false
    parse('return', :on_return0) {thru_return0 = true}
    assert_equal true, thru_return0
  end

  def test_sclass
    thru_sclass = false
    parse('class << a; end', :on_sclass) {thru_sclass = true}
    assert_equal true, thru_sclass
  end

  def test_string_add
    thru_string_add = false
    parse('"aa"', :on_string_add) {thru_string_add = true}
    assert_equal true, thru_string_add
  end

  def test_string_concat
    thru_string_concat = false
    parse('"a" "b"', :on_string_concat) {thru_string_concat = true}
    assert_equal true, thru_string_concat
  end

  def test_string_content
    thru_string_content = false
    parse('""', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('"a"', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('%[a]', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('\'a\'', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('%<a>', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('%!a!', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('%q!a!', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
    thru_string_content = false
    parse('%Q!a!', :on_string_content) {thru_string_content = true}
    assert_equal true, thru_string_content
  end

  def test_string_dvar
    thru_string_dvar = false
    parse('"#$a"', :on_string_dvar) {thru_string_dvar = true}
    assert_equal true, thru_string_dvar
    thru_string_dvar = false
    parse('\'#$a\'', :on_string_dvar) {thru_string_dvar = true}
    assert_equal false, thru_string_dvar
    thru_string_dvar = false
    parse('"#@a"', :on_string_dvar) {thru_string_dvar = true}
    assert_equal true, thru_string_dvar
    thru_string_dvar = false
    parse('\'#@a\'', :on_string_dvar) {thru_string_dvar = true}
    assert_equal false, thru_string_dvar
    thru_string_dvar = false
    parse('"#@@a"', :on_string_dvar) {thru_string_dvar = true}
    assert_equal true, thru_string_dvar
    thru_string_dvar = false
    parse('\'#@@a\'', :on_string_dvar) {thru_string_dvar = true}
    assert_equal false, thru_string_dvar
    thru_string_dvar = false
    parse('"#$1"', :on_string_dvar) {thru_string_dvar = true}
    assert_equal true, thru_string_dvar
    thru_string_dvar = false
    parse('\'#$1\'', :on_string_dvar) {thru_string_dvar = true}
    assert_equal false, thru_string_dvar
  end

  def test_string_embexpr
    thru_string_embexpr = false
    parse('"#{}"', :on_string_embexpr) {thru_string_embexpr = true}
    assert_equal true, thru_string_embexpr
    thru_string_embexpr = false
    parse('\'#{}\'', :on_string_embexpr) {thru_string_embexpr = true}
    assert_equal false, thru_string_embexpr
  end

  def test_string_literal
    thru_string_literal = false
    parse('""', :on_string_literal) {thru_string_literal = true}
    assert_equal true, thru_string_literal
  end

  def test_super
    thru_super = false
    parse('super()', :on_super) {thru_super = true}
    assert_equal true, thru_super
  end

  def test_symbol
    thru_symbol = false
    parse(':a', :on_symbol) {thru_symbol = true}
    assert_equal true, thru_symbol
    thru_symbol = false
    parse(':$a', :on_symbol) {thru_symbol = true}
    assert_equal true, thru_symbol
    thru_symbol = false
    parse(':@a', :on_symbol) {thru_symbol = true}
    assert_equal true, thru_symbol
    thru_symbol = false
    parse(':@@a', :on_symbol) {thru_symbol = true}
    assert_equal true, thru_symbol
    thru_symbol = false
    parse(':==', :on_symbol) {thru_symbol = true}
    assert_equal true, thru_symbol
  end

  def test_symbol_literal
    thru_symbol_literal = false
    parse(':a', :on_symbol_literal) {thru_symbol_literal = true}
    assert_equal true, thru_symbol_literal
  end

  def test_top_const_field
    thru_top_const_field = false
    parse('::A=1', :on_top_const_field) {thru_top_const_field = true}
    assert_equal true, thru_top_const_field
  end

  def test_top_const_ref
    thru_top_const_ref = false
    parse('::A', :on_top_const_ref) {thru_top_const_ref = true}
    assert_equal true, thru_top_const_ref
  end

  def test_unary
    thru_unary = false
    parse('not a 1, 2', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('not (a)', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('!a', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('-10', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('-10*2', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('-10.1', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('-10.1*2', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('-a', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('+a', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('~a', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
    thru_unary = false
    parse('not()', :on_unary) {thru_unary = true}
    assert_equal true, thru_unary
  end

  def test_undef
    thru_undef = false
    parse('undef a', :on_undef) {thru_undef = true}
    assert_equal true, thru_undef
    thru_undef = false
    parse('undef <=>', :on_undef) {thru_undef = true}
    assert_equal true, thru_undef
    thru_undef = false
    parse('undef a, b', :on_undef) {thru_undef = true}
    assert_equal true, thru_undef
  end

  def test_unless
    thru_unless = false
    parse('unless a; end', :on_unless) {thru_unless = true}
    assert_equal true, thru_unless
  end

  def test_unless_mod
    thru_unless_mod = false
    parse('nil unless a', :on_unless_mod) {thru_unless_mod = true}
    assert_equal true, thru_unless_mod
  end

  def test_until
    thru_until = false
    parse('until a; end', :on_until) {thru_until = true}
    assert_equal true, thru_until
  end

  def test_until_mod
    thru_until_mod = false
    parse('nil until a', :on_until_mod) {thru_until_mod = true}
    assert_equal true, thru_until_mod
  end

  def test_var_field
    thru_var_field = false
    parse('a = 1', :on_var_field) {thru_var_field = true}
    assert_equal true, thru_var_field
    thru_var_field = false
    parse('a += 1', :on_var_field) {thru_var_field = true}
    assert_equal true, thru_var_field
  end

  def test_when
    thru_when = false
    parse('case a when b; end', :on_when) {thru_when = true}
    assert_equal true, thru_when
    thru_when = false
    parse('case when a; end', :on_when) {thru_when = true}
    assert_equal true, thru_when
  end

  def test_while
    thru_while = false
    parse('while a; end', :on_while) {thru_while = true}
    assert_equal true, thru_while
  end

  def test_while_mod
    thru_while_mod = false
    parse('nil while a', :on_while_mod) {thru_while_mod = true}
    assert_equal true, thru_while_mod
  end

  def test_word_add
    thru_word_add = false
    parse('%W[a]', :on_word_add) {thru_word_add = true}
    assert_equal true, thru_word_add
  end

  def test_word_new
    thru_word_new = false
    parse('%W[a]', :on_word_new) {thru_word_new = true}
    assert_equal true, thru_word_new
  end

  def test_words_add
    thru_words_add = false
    parse('%W[a]', :on_words_add) {thru_words_add = true}
    assert_equal true, thru_words_add
  end

  def test_words_new
    thru_words_new = false
    parse('%W[]', :on_words_new) {thru_words_new = true}
    assert_equal true, thru_words_new
  end

  def test_xstring_add
    thru_xstring_add = false
    parse('`x`', :on_xstring_add) {thru_xstring_add = true}
    assert_equal true, thru_xstring_add
  end

  def test_xstring_literal
    thru_xstring_literal = false
    parse('``', :on_xstring_literal) {thru_xstring_literal = true}
    assert_equal true, thru_xstring_literal
  end

  def test_xstring_new
    thru_xstring_new = false
    parse('``', :on_xstring_new) {thru_xstring_new = true}
    assert_equal true, thru_xstring_new
  end

  def test_yield
    thru_yield = false
    parse('yield a', :on_yield) {thru_yield = true}
    assert_equal true, thru_yield
  end

  def test_yield0
    thru_yield0 = false
    parse('yield', :on_yield0) {thru_yield0 = true}
    assert_equal true, thru_yield0
  end

  def test_zsuper
    thru_zsuper = false
    parse('super', :on_zsuper) {thru_zsuper = true}
    assert_equal true, thru_zsuper
  end

  def test_local_variables
    cmd = 'command(w,[regexp_literal(regexp_add(regexp_new(),25 # ),/)])'
    div = 'binary(ref(w),/,25)'
    bug1939 = '[ruby-core:24923]'

    assert_equal("[#{cmd}]", parse('w /25 # /'), bug1939)
    assert_equal("[assign(var_field(w),1),#{div}]", parse("w = 1; w /25 # /"), bug1939)
    assert_equal("[fcall(p,[],&block([w],[#{div}]))]", parse("p{|w|w /25 # /\n}"), bug1939)
    assert_equal("[def(p,[w],bodystmt([#{div}]))]", parse("def p(w)\nw /25 # /\nend"), bug1939)
  end

  def test_block_variables
    assert_equal("[fcall(proc,[],&block([],[void()]))]", parse("proc{|;y|}"))
    if defined?(Process::RLIMIT_AS)
      assert_in_out_err(["-I#{File.dirname(__FILE__)}", "-rdummyparser"],
                        'Process.setrlimit(Process::RLIMIT_AS,100*1024*1024); puts DummyParser.new("proc{|;y|!y}").parse',
                        ["[fcall(proc,[],&block([],[unary(!,ref(y))]))]"], [], '[ruby-dev:39423]')
    end
  end

  def test_unterminated_regexp
    assert_equal("unterminated regexp meets end of file", compile_error('/'))
  end

  def test_invalid_instance_variable_name
    assert_equal("`@1' is not allowed as an instance variable name", compile_error('@1'))
    assert_equal("`@%' is not allowed as an instance variable name", compile_error('@%'))
  end

  def test_invalid_class_variable_name
    assert_equal("`@@1' is not allowed as a class variable name", compile_error('@@1'))
    assert_equal("`@@%' is not allowed as a class variable name", compile_error('@@%'))
  end

  def test_invalid_global_variable_name
    assert_equal("`$%' is not allowed as a global variable name", compile_error('$%'))
  end
end if ripper_test


text: . msu require aliases


text:
package gforms

import (
	"bytes"
	"net/http"
	"net/url"
	"reflect"
	"time"
	"bitbucket.org/spaaza/go-sdk"
)

type Form func(...*http.Request) *FormInstance

// cleaned data for all fields.
type CleanedData map[string]interface{}

// FormValidator is a function that will run only if all field cleaning and
// validation passes. It receives the CleanedData, providing an opportunity to
// validate multiple values together, and return an array of top level error strings.
type FormValidator func(cleanedData CleanedData) []string

// FormInstance made by Form.
type FormInstance struct {
	fieldInstances *FieldInterfaces
	Data           Data
	CleanedData    CleanedData
	ParseError     error
	errors         []string
	Validator      FormValidator
}

// Create a new form instance from `http.Request`.
func (f Form) FromRequest(r *http.Request) *FormInstance {
	return f(r)
}

// Create a new form instance from `url.Values`.
func (f Form) FromUrlValues(uv url.Values) *FormInstance {
	fi := f()
	fi.parseUrlValues(uv)
	return fi
}

// Get a `FieldInterface` for the given field name.
func (f *FormInstance) GetField(name string) (FieldInterface, bool) {
	v, ok := f.fieldInstances.nameMap[name]
	return v, ok
}

// Get all `FieldInstance` on `FormInstance`.
func (f *FormInstance) Fields() []FieldInterface {
	return f.fieldInstances.list
}

func (f *FormInstance) SetErrors(errors []string) {
	f.errors = errors
}

// Return field errors if any fields have error after calling `FormInstance#IsValid`.
// Also includes top level form errors.
func (f *FormInstance) Errors() Errors {
	errs := map[string][]string{}
	var err []string
	for _, field := range f.fieldInstances.list {
		name := field.GetModel().GetName()
		err = field.Errors()
		if len(err) > 0 {
			errs[name] = err
		}
	}
	formErr := f.FormErrors()
	if len(err) > 0 {
		errs["form"] = formErr
	}
	return errs
}

func (f *FormInstance) FormErrors() []string {
	return f.errors;
}

// Validation request data. If any fields have errors, this method returns false.
func (f *FormInstance) IsValid() bool {
	isValid := true
	f.CleanedData = CleanedData{}

	// validate fields
	for _, field := range f.fieldInstances.list {
		var err error
		name := field.GetModel().GetName()
		err = field.Clean(f.Data)
		if err != nil {
			field.SetErrors([]string{err.Error()})
			isValid = false
			continue
		}

		errs := field.Validate(f)
		if len(errs) > 0 {
			field.SetErrors(errs)
			isValid = false
			continue
		}

		if !field.GetV().IsNil {
			f.CleanedData[name] = field.GetV().Value
		}
	}

	// validate top level form
	if isValid && f.Validator != nil {
		formErrs := f.Validator(f.CleanedData)
		if len(formErrs) > 0 {
			isValid = false
			f.SetErrors(formErrs)
		}
	}

	return isValid
}

func (f *FormInstance) parseRequest(req *http.Request) error {
	data, err := bindRequest(req)
	if err != nil {
		return err
	}
	if data == nil {
		return nil
	}
	f.Data = *data
	return nil
}

func (f *FormInstance) parseUrlValues(uv url.Values) error {
	data, err := bindUrlValues(uv)
	if err != nil {
		return err
	}
	if data == nil {
		return nil
	}
	f.Data = *data
	return nil
}

// Get html of each FieldInstance.
func (f *FormInstance) Html() string {
	var html bytes.Buffer
	for _, field := range f.fieldInstances.list {
		html.WriteString(field.Html() + "\r\n")
	}
	return html.String()
}

// Define a new form with specified fields.
func DefineForm(fs *Fields) Form {
	return func(r ...*http.Request) *FormInstance {
		f := new(FormInstance)
		f.fieldInstances = newFieldInterfaces(fs)
		if len(r) > 0 {
			f.ParseError = f.parseRequest(r[0])
		}
		return f
	}
}

// maps cleanedData to specified model.
func (fi *FormInstance) MapTo(model interface{}) {
	if fi.CleanedData == nil {
		panic("MapTo method should be called after calling IsValid() method.")
	}
	if reflect.TypeOf(model).Kind() != reflect.Ptr {
		panic("Argument should be specified pointer type.")
	}
	mType := reflect.TypeOf(model).Elem()
	mValue := reflect.ValueOf(model).Elem()

	for i := 0; i < mValue.NumField(); i++ {
		typeField := mType.Field(i)
		tag := typeField.Tag.Get("gforms")
		if tag == "" {
			tag = typeField.Name
		} else if tag == "-" {
			continue
		}
		v, ok := fi.CleanedData[tag]
		if ok {
			valueField := mValue.Field(i)
			switch valueField.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				value, ok := v.(int)
				if !ok {
					value = 0
				}
				valueField.SetInt(int64(value))
			case reflect.Float32, reflect.Float64:
				value, ok := v.(float64)
				if !ok {
					value = 0.0
				}
				valueField.SetFloat(value)
			case reflect.String:
				value, ok := v.(string)
				if !ok {
					va, ok := v.([]string)
					if ok && len(va) > 0 {
						value = va[0]
					} else {
						value = ""
					}
				}
				valueField.SetString(value)
			case reflect.Slice:
				value, ok := v.([]string)
				if !ok {
					value = []string{}
				}
				valueField.Set(reflect.ValueOf(value))
			case reflect.Bool:
				value, ok := v.(bool)
				if !ok {
					value = false
				}
				valueField.SetBool(value)
			case reflect.Struct:
				switch typeField.Type.String() {
				case "time.Time":
					value, ok := v.(time.Time)
					if !ok {
						value = time.Time{}
					}
					valueField.Set(reflect.ValueOf(value))
				case "spaazaSDK.CustomTime": // FIXME: This is bad!
				    value, ok := v.(time.Time)
				    if !ok {
				    	value = time.Time{}
				    }
				    valueField.Set(reflect.ValueOf(spaazaSDK.CustomTime{value}))
				case "spaazaSDK.MailingList": // FIXME: This is bad bad!
					value, ok := v.(bool)
					if !ok {
						value = false
					}
					valueField.Set(reflect.ValueOf(spaazaSDK.MailingList{value}))
				case "spaazaSDK.OptInProgramme": // FIXME: This is bad bad bad!
					value, ok := v.(bool)
					if !ok {
						value = false
					}
					valueField.Set(reflect.ValueOf(spaazaSDK.OptInProgramme{value}))
				}
			}
		}
	}
}


text:
require 'spec_helper'

# Using request spec b/c Authlogic won't work with controller spec
describe QuestioningsController, type: :request do
  before do
    @user = create(:user, role_name: 'coordinator')
    login(@user)
  end

  describe 'update' do
    context 'when published' do
      before do
        @form = create(:form, question_types: %w(text text))
        @qing = @form.questionings[1]
        @form.publish!
      end

      it 'changing name should succeed' do
        put(questioning_path(@qing, mode: 'm', mission_name: get_mission.compact_name),
          'questioning' => {
            'question_attributes' => {
              'id' => @qing.question_id,
              'name_en' => 'Foo'
            }
          }
        )
        expect(response).to be_redirect
        expect(@qing.reload.name_en).to eq('Foo')
      end

      it 'changing required flag should be unauthorized' do
        put(questioning_path(@qing, mode: 'm', mission_name: get_mission.compact_name),
          'questioning' => { 'required' => '1' })
        expect(response).to redirect_to(unauthorized_path)
      end

      it 'changing hidden flag should be unauthorized' do
        put(questioning_path(@qing, mode: 'm', mission_name: get_mission.compact_name),
          'questioning' => { 'hidden' => '1' })
        expect(response).to redirect_to(unauthorized_path)
      end

      it 'changing condition should be unauthorized' do
        put(questioning_path(@qing, mode: 'm', mission_name: get_mission.compact_name),
          'questioning' => {
            'condition_attributes' => {
              'ref_qing_id' => @form.questionings[0].id,
              'op' => 'eq',
              'value' => 'foo'
            }
          }
        )
        expect(response).to redirect_to(unauthorized_path)
      end
    end
  end
end


text:
from django.utils import timezone

from website.mails import mails
from website.notifications import utils
from website.reviews import signals as reviews_signals

# Handle email notifications including: update comment, accept, and reject of submission.
@reviews_signals.reviews_email.connect
def reviews_notification(self, creator, template, context, action):
    # Avoid AppRegistryNotReady error
    from website.notifications.emails import notify_global_event
    recipients = list(action.target.node.contributors)
    time_now = action.created if action is not None else timezone.now()
    node = action.target.node
    notify_global_event(
        event='global_reviews',
        sender_user=creator,
        node=node,
        timestamp=time_now,
        recipients=recipients,
        template=template,
        context=context
    )

# Handle email notifications for a new submission.
@reviews_signals.reviews_email_submit.connect
def reviews_submit_notification(self, recipients, context):
    # Avoid AppRegistryNotReady error
    from website.notifications.emails import get_user_subscriptions
    from website import settings

    event_type = utils.find_subscription_type('global_reviews')
    if context['reviewable'].provider._id == 'osf':
        context['logo'] = settings.OSF_PREPRINTS_LOGO
    else:
        context['logo'] = context['reviewable'].provider._id

    for recipient in recipients:
        user_subscriptions = get_user_subscriptions(recipient, event_type)
        context['no_future_emails'] = user_subscriptions['none']
        context['is_creator'] = recipient == context['reviewable'].node.creator
        context['provider_name'] = context['reviewable'].provider.name
        mails.send_mail(
            recipient.username,
            mails.REVIEWS_SUBMISSION_CONFIRMATION,
            mimetype='html',
            user=recipient,
            **context
        )

# Handle email notifications to notify moderators of new submissions.
@reviews_signals.reviews_email_submit_moderators_notifications.connect
def reviews_submit_notification_moderators(self, timestamp, context):
    # imports moved here to avoid AppRegistryNotReady error
    from osf.models import NotificationSubscription
    from website.profile.utils import get_profile_image_url
    from website.notifications import emails
    from website import settings

    # Get NotificationSubscription instance, which contains reference to all subscribers
    provider_subscription = NotificationSubscription.load('{}_new_pending_submissions'.format(context['reviewable'].provider._id))
    # Set message
    context['message'] = u'submitted {}.'.format(context['reviewable'].node.title)
    # Set url for profile image of the submitter
    context['profile_image_url'] = get_profile_image_url(context['referrer'])
    # Set submission url
    context['reviews_submission_url'] = '{}reviews/preprints/{}/{}'.format(settings.DOMAIN, context['reviewable'].provider._id, context['reviewable']._id)
    # Store emails to be sent to subscribers instantly (at a 5 min interval)
    emails.store_emails(provider_subscription.email_transactional.all().values_list('guids___id', flat=True),
                        'email_transactional',
                        'new_pending_submissions',
                        context['referrer'],
                        context['reviewable'].node,
                        timestamp,
                        abstract_provider=context['reviewable'].provider,
                        **context)

    # Store emails to be sent to subscribers daily
    emails.store_emails(provider_subscription.email_digest.all().values_list('guids___id', flat=True),
                        'email_digest',
                        'new_pending_submissions',
                        context['referrer'],
                        context['reviewable'].node,
                        timestamp,
                        abstract_provider=context['reviewable'].provider,
                        **context)


text:
namespace Core.Framework.MEF.Contracts.Web
{
    /// <summary>
    /// Defines the contract for providing metadata for a route registrar.
    /// </summary>
    public interface IRouteRegistrarMetadata
    {
        #region Properties
        /// <summary>
        /// Gets the order in which the registrar must be processed.
        /// </summary>
        int Order { get; }
        #endregion
    }
}


text:
declare module Adaptive {
    /**
       @enum {Adaptive.ICapabilitiesSensor} Adaptive.ICapabilitiesSensor
       Enumeration ICapabilitiesSensor
    */
    class ICapabilitiesSensor {
        value: string;
        constructor(value: string);
        toString(): string;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Accelerometer='Accelerometer']
        */
        static Accelerometer: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [AmbientLight='AmbientLight']
        */
        static AmbientLight: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Barometer='Barometer']
        */
        static Barometer: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Geolocation='Geolocation']
        */
        static Geolocation: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Gyroscope='Gyroscope']
        */
        static Gyroscope: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Magnetometer='Magnetometer']
        */
        static Magnetometer: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Proximity='Proximity']
        */
        static Proximity: ICapabilitiesSensor;
        /**
           @property {Adaptive.ICapabilitiesSensor} [Unknown='Unknown']
        */
        static Unknown: ICapabilitiesSensor;
        /**
           @method
           @static
           Convert JSON parsed object to enumeration.
           @return {Adaptive.ICapabilitiesSensor}
        */
        static toObject(object: any): ICapabilitiesSensor;
    }
}


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

Jobs

Should I Move?

  A: I'm thinking of moving to Texas.
 B: Why? You love California.
 A: I do, but there's a great teaching job in Texas.
 B: How much would you get?
 A: I would get $70,000 a year.
 B: How much do you make now?
 A: I earn $60,000 a year.
 B: I still don't think you should move.
 A: Really? Why not?
 B: All your friends and family are here.
 A: Are there any other reasons?
 B: I think you'll earn $70,000 if you're patient.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package org.apache.hadoop.hdds.scm.storage;

import org.apache.hadoop.hdds.scm.container.common.helpers
    .BlockNotCommittedException;
import org.apache.ratis.shaded.com.google.protobuf.ByteString;
import org.apache.hadoop.hdds.scm.XceiverClientSpi;
import org.apache.hadoop.hdds.scm.container.common.helpers
    .StorageContainerException;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ContainerCommandRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ContainerCommandResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .CloseContainerRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .DatanodeBlockID;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .GetKeyRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .GetKeyResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .GetSmallFileRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .GetSmallFileResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.KeyData;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .PutKeyRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .PutSmallFileRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ReadChunkRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ReadChunkResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ReadContainerRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ReadContainerResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Type;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .WriteChunkRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.KeyValue;
import org.apache.hadoop.hdds.client.BlockID;

import java.io.IOException;

/**
 * Implementation of all container protocol calls performed by Container
 * clients.
 */
public final class ContainerProtocolCalls  {

  /**
   * There is no need to instantiate this class.
   */
  private ContainerProtocolCalls() {
  }

  /**
   * Calls the container protocol to get a container key.
   *
   * @param xceiverClient client to perform call
   * @param datanodeBlockID blockID to identify container
   * @param traceID container protocol call args
   * @return container protocol get key response
   * @throws IOException if there is an I/O error while performing the call
   */
  public static GetKeyResponseProto getKey(XceiverClientSpi xceiverClient,
      DatanodeBlockID datanodeBlockID, String traceID) throws IOException {
    GetKeyRequestProto.Builder readKeyRequest = GetKeyRequestProto
        .newBuilder()
        .setBlockID(datanodeBlockID);
    String id = xceiverClient.getPipeline().getLeader().getUuidString();

    ContainerCommandRequestProto request = ContainerCommandRequestProto
        .newBuilder()
        .setCmdType(Type.GetKey)
        .setContainerID(datanodeBlockID.getContainerID())
        .setTraceID(traceID)
        .setDatanodeUuid(id)
        .setGetKey(readKeyRequest)
        .build();
    ContainerCommandResponseProto response = xceiverClient.sendCommand(request);
    validateContainerResponse(response);

    return response.getGetKey();
  }

  /**
   * Calls the container protocol to get the length of a committed block.
   *
   * @param xceiverClient client to perform call
   * @param blockID blockId for the Block
   * @param traceID container protocol call args
   * @return container protocol getLastCommittedBlockLength response
   * @throws IOException if there is an I/O error while performing the call
   */
  public static ContainerProtos.GetCommittedBlockLengthResponseProto
      getCommittedBlockLength(
          XceiverClientSpi xceiverClient, BlockID blockID, String traceID)
      throws IOException {
    ContainerProtos.GetCommittedBlockLengthRequestProto.Builder
        getBlockLengthRequestBuilder =
        ContainerProtos.GetCommittedBlockLengthRequestProto.newBuilder().
            setBlockID(blockID.getDatanodeBlockIDProtobuf());
    String id = xceiverClient.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto request =
        ContainerCommandRequestProto.newBuilder()
            .setCmdType(Type.GetCommittedBlockLength)
            .setContainerID(blockID.getContainerID())
            .setTraceID(traceID)
            .setDatanodeUuid(id)
            .setGetCommittedBlockLength(getBlockLengthRequestBuilder).build();
    ContainerCommandResponseProto response = xceiverClient.sendCommand(request);
    validateContainerResponse(response);
    return response.getGetCommittedBlockLength();
  }

  /**
   * Calls the container protocol to put a container key.
   *
   * @param xceiverClient client to perform call
   * @param containerKeyData key data to identify container
   * @param traceID container protocol call args
   * @throws IOException if there is an I/O error while performing the call
   */
  public static void putKey(XceiverClientSpi xceiverClient,
      KeyData containerKeyData, String traceID) throws IOException {
    PutKeyRequestProto.Builder createKeyRequest = PutKeyRequestProto
        .newBuilder()
        .setKeyData(containerKeyData);
    String id = xceiverClient.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto request = ContainerCommandRequestProto
        .newBuilder()
        .setCmdType(Type.PutKey)
        .setContainerID(containerKeyData.getBlockID().getContainerID())
        .setTraceID(traceID)
        .setDatanodeUuid(id)
        .setPutKey(createKeyRequest)
        .build();
    ContainerCommandResponseProto response = xceiverClient.sendCommand(request);
    validateContainerResponse(response);
  }

  /**
   * Calls the container protocol to read a chunk.
   *
   * @param xceiverClient client to perform call
   * @param chunk information about chunk to read
   * @param blockID ID of the block
   * @param traceID container protocol call args
   * @return container protocol read chunk response
   * @throws IOException if there is an I/O error while performing the call
   */
  public static ReadChunkResponseProto readChunk(XceiverClientSpi xceiverClient,
        ChunkInfo chunk, BlockID blockID, String traceID) throws IOException {
    ReadChunkRequestProto.Builder readChunkRequest = ReadChunkRequestProto
        .newBuilder()
        .setBlockID(blockID.getDatanodeBlockIDProtobuf())
        .setChunkData(chunk);
    String id = xceiverClient.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto request = ContainerCommandRequestProto
        .newBuilder()
        .setCmdType(Type.ReadChunk)
        .setContainerID(blockID.getContainerID())
        .setTraceID(traceID)
        .setDatanodeUuid(id)
        .setReadChunk(readChunkRequest)
        .build();
    ContainerCommandResponseProto response = xceiverClient.sendCommand(request);
    validateContainerResponse(response);
    return response.getReadChunk();
  }

  /**
   * Calls the container protocol to write a chunk.
   *
   * @param xceiverClient client to perform call
   * @param chunk information about chunk to write
   * @param blockID ID of the block
   * @param data the data of the chunk to write
   * @param traceID container protocol call args
   * @throws IOException if there is an I/O error while performing the call
   */
  public static void writeChunk(XceiverClientSpi xceiverClient, ChunkInfo chunk,
      BlockID blockID, ByteString data, String traceID)
      throws IOException {
    WriteChunkRequestProto.Builder writeChunkRequest = WriteChunkRequestProto
        .newBuilder()
        .setBlockID(blockID.getDatanodeBlockIDProtobuf())
        .setChunkData(chunk)
        .setData(data);
    String id = xceiverClient.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto request = ContainerCommandRequestProto
        .newBuilder()
        .setCmdType(Type.WriteChunk)
        .setContainerID(blockID.getContainerID())
        .setTraceID(traceID)
        .setDatanodeUuid(id)
        .setWriteChunk(writeChunkRequest)
        .build();
    ContainerCommandResponseProto response = xceiverClient.sendCommand(request);
    validateContainerResponse(response);
  }

  /**
   * Allows writing a small file using single RPC. This takes the container
   * name, key name and data to write sends all that data to the container using
   * a single RPC. This API is designed to be used for files which are smaller
   * than 1 MB.
   *
   * @param client - client that communicates with the container.
   * @param blockID - ID of the block
   * @param data - Data to be written into the container.
   * @param traceID - Trace ID for logging purpose.
   * @throws IOException
   */
  public static void writeSmallFile(XceiverClientSpi client,
      BlockID blockID, byte[] data, String traceID)
      throws IOException {

    KeyData containerKeyData =
        KeyData.newBuilder().setBlockID(blockID.getDatanodeBlockIDProtobuf())
            .build();
    PutKeyRequestProto.Builder createKeyRequest =
        PutKeyRequestProto.newBuilder()
            .setKeyData(containerKeyData);

    KeyValue keyValue =
        KeyValue.newBuilder().setKey("OverWriteRequested").setValue("true")
            .build();
    ChunkInfo chunk =
        ChunkInfo.newBuilder().setChunkName(blockID.getLocalID()
            + "_chunk").setOffset(0).setLen(data.length).
            addMetadata(keyValue).build();

    PutSmallFileRequestProto putSmallFileRequest =
        PutSmallFileRequestProto.newBuilder().setChunkInfo(chunk)
            .setKey(createKeyRequest).setData(ByteString.copyFrom(data))
            .build();

    String id = client.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto request =
        ContainerCommandRequestProto.newBuilder()
            .setCmdType(Type.PutSmallFile)
            .setContainerID(blockID.getContainerID())
            .setTraceID(traceID)
            .setDatanodeUuid(id)
            .setPutSmallFile(putSmallFileRequest)
            .build();
    ContainerCommandResponseProto response = client.sendCommand(request);
    validateContainerResponse(response);
  }

  /**
   * createContainer call that creates a container on the datanode.
   * @param client  - client
   * @param containerID - ID of container
   * @param traceID - traceID
   * @throws IOException
   */
  public static void createContainer(XceiverClientSpi client, long containerID,
      String traceID) throws IOException {
    ContainerProtos.CreateContainerRequestProto.Builder createRequest =
        ContainerProtos.CreateContainerRequestProto
            .newBuilder();
    createRequest.setContainerType(ContainerProtos.ContainerType
        .KeyValueContainer);

    String id = client.getPipeline().getLeader().getUuidString();
    ContainerCommandRequestProto.Builder request =
        ContainerCommandRequestProto.newBuilder();
    request.setCmdType(ContainerProtos.Type.CreateContainer);
    request.setContainerID(containerID);
    request.setCreateContainer(createRequest.build());
    request.setDatanodeUuid(id);
    request.setTraceID(traceID);
    ContainerCommandResponseProto response = client.sendCommand(
        request.build());
    validateContainerResponse(response);
  }

  /**
   * Deletes a container from a pipeline.
   *
   * @param client
   * @param force whether or not to forcibly delete the container.
   * @param traceID
   * @throws IOException
   */
  public static void deleteContainer(XceiverClientSpi client, long containerID,
      boolean force, String traceID) throws IOException {
    ContainerProtos.DeleteContainerRequestProto.Builder deleteRequest =
        ContainerProtos.DeleteContainerRequestProto.newBuilder();
    deleteRequest.setForceDelete(force);
    String id = client.getPipeline().getLeader().getUuidString();

    ContainerCommandRequestProto.Builder request =
        ContainerCommandRequestProto.newBuilder();
    request.setCmdType(ContainerProtos.Type.DeleteContainer);
    request.setContainerID(containerID);
    request.setDeleteContainer(deleteRequest);
    request.setTraceID(traceID);
    request.setDatanodeUuid(id);
    ContainerCommandResponseProto response =
        client.sendCommand(request.build());
    validateContainerResponse(response);
  }

  /**
   * Close a container.
   *
   * @param client
   * @param containerID
   * @param traceID
   * @throws IOException
   */
  public static void closeContainer(XceiverClientSpi client,
      long containerID, String traceID) throws IOException {
    String id = client.getPipeline().getLeader().getUuidString();

    ContainerCommandRequestProto.Builder request =
        ContainerCommandRequestProto.newBuilder();
    request.setCmdType(Type.CloseContainer);
    request.setContainerID(containerID);
    request.setCloseContainer(CloseContainerRequestProto.getDefaultInstance());
    request.setTraceID(traceID);
    request.setDatanodeUuid(id);
    ContainerCommandResponseProto response =
        client.sendCommand(request.build());
    validateContainerResponse(response);
  }

  /**
   * readContainer call that gets meta data from an existing container.
   *
   * @param client - client
   * @param traceID - trace ID
   * @throws IOException
   */
  public static ReadContainerResponseProto readContainer(
      XceiverClientSpi client, long containerID,
      String traceID) throws IOException {
    String id = client.getPipeline().getLeader().getUuidString();

    ContainerCommandRequestProto.Builder request =
        ContainerCommandRequestProto.newBuilder();
    request.setCmdType(Type.ReadContainer);
    request.setContainerID(containerID);
    request.setReadContainer(ReadContainerRequestProto.getDefaultInstance());
    request.setDatanodeUuid(id);
    request.setTraceID(traceID);
    ContainerCommandResponseProto response =
        client.sendCommand(request.build());
    validateContainerResponse(response);

    return response.getReadContainer();
  }

  /**
   * Reads the data given the blockID.
   *
   * @param client
   * @param blockID - ID of the block
   * @param traceID - trace ID
   * @return GetSmallFileResponseProto
   * @throws IOException
   */
  public static GetSmallFileResponseProto readSmallFile(XceiverClientSpi client,
      BlockID blockID, String traceID) throws IOException {
    GetKeyRequestProto.Builder getKey = GetKeyRequestProto
        .newBuilder()
        .setBlockID(blockID.getDatanodeBlockIDProtobuf());
    ContainerProtos.GetSmallFileRequestProto getSmallFileRequest =
        GetSmallFileRequestProto
            .newBuilder().setKey(getKey)
            .build();
    String id = client.getPipeline().getLeader().getUuidString();

    ContainerCommandRequestProto request = ContainerCommandRequestProto
        .newBuilder()
        .setCmdType(Type.GetSmallFile)
        .setContainerID(blockID.getContainerID())
        .setTraceID(traceID)
        .setDatanodeUuid(id)
        .setGetSmallFile(getSmallFileRequest)
        .build();
    ContainerCommandResponseProto response = client.sendCommand(request);
    validateContainerResponse(response);

    return response.getGetSmallFile();
  }

  /**
   * Validates a response from a container protocol call.  Any non-successful
   * return code is mapped to a corresponding exception and thrown.
   *
   * @param response container protocol call response
   * @throws IOException if the container protocol call failed
   */
  private static void validateContainerResponse(
      ContainerCommandResponseProto response
  ) throws StorageContainerException {
    if (response.getResult() == ContainerProtos.Result.SUCCESS) {
      return;
    } else if (response.getResult()
        == ContainerProtos.Result.BLOCK_NOT_COMMITTED) {
      throw new BlockNotCommittedException(response.getMessage());
    }
    throw new StorageContainerException(
        response.getMessage(), response.getResult());
  }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from tensorboardX import x2num, SummaryWriter
try:
    import chainer
    chainer_installed = True
except ImportError:
    print('Chainer is not installed, skipping test')
    chainer_installed = False
import numpy as np
import unittest

if chainer_installed:
    chainer.Variable
    tensors = [chainer.Variable(np.random.rand(3, 10, 10)),
               chainer.Variable(np.random.rand(1)),
               chainer.Variable(np.random.rand(1, 2, 3, 4, 5))]

    class ChainerTest(unittest.TestCase):
        def test_chainer_np(self):
            for tensor in tensors:
                # regular variable
                assert isinstance(x2num.make_np(tensor), np.ndarray)

            # python primitive type
            assert(isinstance(x2num.make_np(0), np.ndarray))
            assert(isinstance(x2num.make_np(0.1), np.ndarray))

        def test_chainer_img(self):
            shapes = [(77, 3, 13, 7), (77, 1, 13, 7), (3, 13, 7), (1, 13, 7), (13, 7)]
            for s in shapes:
                x = chainer.Variable(np.random.random_sample(s))
                # assert x2num.make_np(x, 'IMG').shape[2] == 3

        def test_chainer_write(self):
            with SummaryWriter() as w:
                w.add_scalar('scalar', chainer.Variable(np.random.rand(1)), 0)