text:
// Product.cs
//

using System;
using System.ComponentModel;

namespace Store {

    public sealed class Product : Model {

        private string _id;
        private string _description;
        private Uri _imageUri;
        private decimal _price;
        private Uri _productUri;
        private string _title;

        public string Description {
            get {
                return _description;
            }
            set {
                if (_description != value) {
                    _description = value;
                    RaisePropertyChanged("Description");
                }
            }
        }

        public string ID {
            get {
                return _id;
            }
            set {
                if (_id != value) {
                    _id = value;
                }
            }
        }

        public Uri ImageUri {
            get {
                return _imageUri;
            }
            set {
                if (_imageUri != value) {
                    _imageUri = value;
                    RaisePropertyChanged("ImageUri");
                }
            }
        }

        public decimal Price {
            get {
                return _price;
            }
            set {
                if (_price != value) {
                    _price = value;
                    RaisePropertyChanged("Price");
                }
            }
        }

        public Uri ProductUri {
            get {
                return _productUri;
            }
            set {
                if (_productUri != value) {
                    _productUri = value;
                    RaisePropertyChanged("ProductUri");
                }
            }
        }

        public string Title {
            get {
                return _title;
            }
            set {
                if (_title != value) {
                    _title = value;
                    RaisePropertyChanged("Title");
                }
            }
        }
    }
}


text:
import fs from 'fs';

export default function fileExistsWait(file, maxMsWait = 20000) {
  return new Promise((resolve, reject) => {
    const endTime = +new Date() + maxMsWait;

    const check = () => {
      fs.stat(file, (err, stats) => {
        if (stats && stats.isFile()) {
          resolve();
        } else if (err && err.code === 'ENOENT' && endTime > +new Date()) {
          setTimeout(check, 1000);
        } else {
          reject();
        }
      });
    };

    check();
  });
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef SKY_ENGINE_CORE_CSS_STYLEPROPERTYSET_H_
#define SKY_ENGINE_CORE_CSS_STYLEPROPERTYSET_H_

#include "gen/sky/core/CSSPropertyNames.h"
#include "sky/engine/core/css/CSSPrimitiveValue.h"
#include "sky/engine/core/css/CSSProperty.h"
#include "sky/engine/core/css/PropertySetCSSStyleDeclaration.h"
#include "sky/engine/core/css/parser/CSSParserMode.h"
#include "sky/engine/wtf/ListHashSet.h"
#include "sky/engine/wtf/Vector.h"
#include "sky/engine/wtf/text/WTFString.h"

namespace blink {

class CSSStyleDeclaration;
class Element;
class ImmutableStylePropertySet;
class KURL;
class MutableStylePropertySet;
class StylePropertyShorthand;
class StyleSheetContents;

class StylePropertySet : public RefCounted<StylePropertySet> {
    friend class PropertyReference;
public:

    // Override RefCounted's deref() to ensure operator delete is called on
    // the appropriate subclass type.
    void deref();

    class PropertyReference {
    public:
        PropertyReference(const StylePropertySet& propertySet, unsigned index)
            : m_propertySet(propertySet)
            , m_index(index)
        {
        }

        CSSPropertyID id() const { return static_cast<CSSPropertyID>(propertyMetadata().m_propertyID); }
        CSSPropertyID shorthandID() const { return propertyMetadata().shorthandID(); }

        bool isInherited() const { return propertyMetadata().m_inherited; }
        bool isImplicit() const { return propertyMetadata().m_implicit; }

        String cssName() const;
        String cssText() const;

        const CSSValue* value() const { return propertyValue(); }
        // FIXME: We should try to remove this mutable overload.
        CSSValue* value() { return const_cast<CSSValue*>(propertyValue()); }

        // FIXME: Remove this.
        CSSProperty toCSSProperty() const { return CSSProperty(propertyMetadata(), const_cast<CSSValue*>(propertyValue())); }

        const StylePropertyMetadata& propertyMetadata() const;

    private:
        const CSSValue* propertyValue() const;

        const StylePropertySet& m_propertySet;
        unsigned m_index;
    };

    unsigned propertyCount() const;
    bool isEmpty() const;
    PropertyReference propertyAt(unsigned index) const { return PropertyReference(*this, index); }
    int findPropertyIndex(CSSPropertyID) const;
    bool hasProperty(CSSPropertyID property) const { return findPropertyIndex(property) != -1; }

    PassRefPtr<CSSValue> getPropertyCSSValue(CSSPropertyID) const;
    String getPropertyValue(CSSPropertyID) const;

    CSSPropertyID getPropertyShorthand(CSSPropertyID) const;
    bool isPropertyImplicit(CSSPropertyID) const;

    PassRefPtr<MutableStylePropertySet> copyBlockProperties() const;

    CSSParserMode cssParserMode() const { return static_cast<CSSParserMode>(m_cssParserMode); }

    PassRefPtr<MutableStylePropertySet> mutableCopy() const;
    PassRefPtr<ImmutableStylePropertySet> immutableCopyIfNeeded() const;

    PassRefPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;

    String asText() const;

    bool isMutable() const { return m_isMutable; }

    static unsigned averageSizeInBytes();

#ifndef NDEBUG
    void showStyle();
#endif

    bool propertyMatches(CSSPropertyID, const CSSValue*) const;

protected:

    enum { MaxArraySize = (1 << 28) - 1 };

    StylePropertySet(CSSParserMode cssParserMode)
        : m_cssParserMode(cssParserMode)
        , m_isMutable(true)
        , m_arraySize(0)
    { }

    StylePropertySet(CSSParserMode cssParserMode, unsigned immutableArraySize)
        : m_cssParserMode(cssParserMode)
        , m_isMutable(false)
        , m_arraySize(std::min(immutableArraySize, unsigned(MaxArraySize)))
    { }

    unsigned m_cssParserMode : 3;
    mutable unsigned m_isMutable : 1;
    unsigned m_arraySize : 28;

    friend class PropertySetCSSStyleDeclaration;
};

class ImmutableStylePropertySet : public StylePropertySet {
public:
    ~ImmutableStylePropertySet();
    static PassRefPtr<ImmutableStylePropertySet> create(const CSSProperty* properties, unsigned count, CSSParserMode);

    unsigned propertyCount() const { return m_arraySize; }

    const RawPtr<CSSValue>* valueArray() const;
    const StylePropertyMetadata* metadataArray() const;
    int findPropertyIndex(CSSPropertyID) const;

    void* operator new(std::size_t, void* location)
    {
        return location;
    }

    void* m_storage;

private:
    ImmutableStylePropertySet(const CSSProperty*, unsigned count, CSSParserMode);
};

inline const RawPtr<CSSValue>* ImmutableStylePropertySet::valueArray() const
{
    return reinterpret_cast<const RawPtr<CSSValue>*>(const_cast<const void**>(&(this->m_storage)));
}

inline const StylePropertyMetadata* ImmutableStylePropertySet::metadataArray() const
{
    return reinterpret_cast<const StylePropertyMetadata*>(&reinterpret_cast<const char*>(&(this->m_storage))[m_arraySize * sizeof(RawPtr<CSSValue>)]);
}

DEFINE_TYPE_CASTS(ImmutableStylePropertySet, StylePropertySet, set, !set->isMutable(), !set.isMutable());

class MutableStylePropertySet : public StylePropertySet {
public:
    ~MutableStylePropertySet() { }
    static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = HTMLStandardMode);
    static PassRefPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);

    unsigned propertyCount() const { return m_propertyVector.size(); }

    void addParsedProperties(const Vector<CSSProperty, 256>&);
    void addParsedProperty(const CSSProperty&);

    // These expand shorthand properties into multiple properties.
    bool setProperty(CSSPropertyID, const String& value, StyleSheetContents* contextStyleSheet = 0);
    void setProperty(CSSPropertyID, PassRefPtr<CSSValue>);

    // These do not. FIXME: This is too messy, we can do better.
    bool setProperty(CSSPropertyID, CSSValueID identifier);
    bool setProperty(CSSPropertyID, CSSPropertyID identifier);
    void appendProperty(const CSSProperty&);
    void setProperty(const CSSProperty&, CSSProperty* slot = 0);

    bool removeProperty(CSSPropertyID, String* returnText = 0);
    void removeBlockProperties();
    bool removePropertiesInSet(const CSSPropertyID* set, unsigned length);
    void removeEquivalentProperties(const StylePropertySet*);
    void removeEquivalentProperties(const CSSStyleDeclaration*);

    void clear();
    void parseDeclaration(const String& styleDeclaration, StyleSheetContents* contextStyleSheet);

    CSSStyleDeclaration* ensureCSSStyleDeclaration();
    int findPropertyIndex(CSSPropertyID) const;

private:
    explicit MutableStylePropertySet(CSSParserMode);
    explicit MutableStylePropertySet(const StylePropertySet&);
    MutableStylePropertySet(const CSSProperty* properties, unsigned count);

    bool removeShorthandProperty(CSSPropertyID);
    CSSProperty* findCSSPropertyWithID(CSSPropertyID);
    OwnPtr<PropertySetCSSStyleDeclaration> m_cssomWrapper;

    friend class StylePropertySet;

    Vector<CSSProperty, 4> m_propertyVector;
};

DEFINE_TYPE_CASTS(MutableStylePropertySet, StylePropertySet, set, set->isMutable(), set.isMutable());

inline MutableStylePropertySet* toMutableStylePropertySet(const RefPtr<StylePropertySet>& set)
{
    return toMutableStylePropertySet(set.get());
}

inline const StylePropertyMetadata& StylePropertySet::PropertyReference::propertyMetadata() const
{
    if (m_propertySet.isMutable())
        return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).metadata();
    return toImmutableStylePropertySet(m_propertySet).metadataArray()[m_index];
}

inline const CSSValue* StylePropertySet::PropertyReference::propertyValue() const
{
    if (m_propertySet.isMutable())
        return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).value();
    return toImmutableStylePropertySet(m_propertySet).valueArray()[m_index];
}

inline unsigned StylePropertySet::propertyCount() const
{
    if (m_isMutable)
        return toMutableStylePropertySet(this)->m_propertyVector.size();
    return m_arraySize;
}

inline bool StylePropertySet::isEmpty() const
{
    return !propertyCount();
}

#if !ENABLE(OILPAN)
inline void StylePropertySet::deref()
{
    if (!derefBase())
        return;

    if (m_isMutable)
        delete toMutableStylePropertySet(this);
    else
        delete toImmutableStylePropertySet(this);
}
#endif // !ENABLE(OILPAN)

inline int StylePropertySet::findPropertyIndex(CSSPropertyID propertyID) const
{
    if (m_isMutable)
        return toMutableStylePropertySet(this)->findPropertyIndex(propertyID);
    return toImmutableStylePropertySet(this)->findPropertyIndex(propertyID);
}

} // namespace blink

#endif  // SKY_ENGINE_CORE_CSS_STYLEPROPERTYSET_H_


text:
import re

import django, logging, warnings
from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.models import formset_factory, modelformset_factory
from django.middleware.csrf import _get_new_csrf_key
from django.shortcuts import render_to_response
from django.template import (
    Context, RequestContext, loader
)
from django.test import RequestFactory
from django.utils.translation import ugettext_lazy as _

from .base import CrispyTestCase
from .forms import (
    TestForm, TestForm2, TestForm3, CheckboxesTestForm,
    TestForm4, CrispyTestModel, TestForm5
)
from .utils import override_settings
from crispy_forms.bootstrap import InlineCheckboxes
from crispy_forms.compatibility import PY2
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
    Layout, Fieldset, MultiField, Row, Column, HTML, ButtonHolder,
    Div, Submit
)
from crispy_forms.utils import render_crispy_form

class TestFormLayout(CrispyTestCase):
    urls = 'crispy_forms.tests.urls'

    def test_invalid_unicode_characters(self):
        # Adds a BooleanField that uses non valid unicode characters "ñ"
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                'españa'
            )
        )

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.CRISPY_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda: template.render(c))
        del settings.CRISPY_FAIL_SILENTLY

    def test_unicode_form_field(self):
        class UnicodeForm(forms.Form):
            def __init__(self, *args, **kwargs):
                super(UnicodeForm, self).__init__(*args, **kwargs)
                self.fields['contraseña'] = forms.CharField()

            helper = FormHelper()
            helper.layout = Layout(u'contraseña')

        if PY2:
            self.assertRaises(Exception, lambda: render_crispy_form(UnicodeForm()))
        else:
            html = render_crispy_form(UnicodeForm())
            self.assertTrue('id="id_contraseña"' in html)

    def test_meta_extra_fields_with_missing_fields(self):
        class FormWithMeta(TestForm):
            class Meta:
                fields = ('email', 'first_name', 'last_name')

        form = FormWithMeta()
        # We remove email field on the go
        del form.fields['email']

        form_helper = FormHelper()
        form_helper.layout = Layout(
            'first_name',
        )

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': form, 'form_helper': form_helper})
        html = template.render(c)
        self.assertFalse('email' in html)

    def test_layout_unresolved_field(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                'typo'
            )
        )

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.CRISPY_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda:template.render(c))
        del settings.CRISPY_FAIL_SILENTLY

    def test_double_rendered_field(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                'is_company',
                'is_company',
            )
        )

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.CRISPY_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda:template.render(c))
        del settings.CRISPY_FAIL_SILENTLY

    def test_context_pollution(self):
        class ExampleForm(forms.Form):
            comment = forms.CharField()

        form = ExampleForm()
        form2 = TestForm()

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {{ form.as_ul }}
            {% crispy form2 %}
            {{ form.as_ul }}
        """)
        c = Context({'form': form, 'form2': form2})
        html = template.render(c)

        self.assertEqual(html.count('name="comment"'), 2)
        self.assertEqual(html.count('name="is_company"'), 1)

    def test_layout_fieldset_row_html_with_unicode_fieldnames(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Fieldset(
                    u'Company Data',
                    u'is_company',
                    css_id = "fieldset_company_data",
                    css_class = "fieldsets",
                    title = "fieldset_title",
                    test_fieldset = "123"
                ),
                Fieldset(
                    u'User Data',
                    u'email',
                    Row(
                        u'password1',
                        u'password2',
                        css_id = "row_passwords",
                        css_class = "rows",
                    ),
                    HTML('test link'),
                    HTML(u"""
                        {% if flag %}{{ message }}{% endif %}
                    """),
                    u'first_name',
                    u'last_name',
                )
            )
        )

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({
            'form': TestForm(),
            'form_helper': form_helper,
            'flag': True,
            'message': "Hello!",
        })
        html = template.render(c)

        self.assertTrue('id="fieldset_company_data"' in html)
        self.assertTrue('class="fieldsets' in html)
        self.assertTrue('title="fieldset_title"' in html)
        self.assertTrue('test-fieldset="123"' in html)
        self.assertTrue('id="row_passwords"' in html)
        self.assertEqual(html.count('<label'), 6)

        if self.current_template_pack == 'uni_form':
            self.assertTrue('class="formRow rows"' in html)
        else:
            self.assertTrue('class="row rows"' in html)
        self.assertTrue('Hello!' in html)
        self.assertTrue('testLink' in html)

    def test_change_layout_dynamically_delete_field(self):
        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)

        form = TestForm()
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Fieldset(
                    u'Company Data',
                    'is_company',
                    'email',
                    'password1',
                    'password2',
                    css_id = "multifield_info",
                ),
                Column(
                    'first_name',
                    'last_name',
                    css_id = "column_name",
                )
            )
        )

        # We remove email field on the go
        # Layout needs to be adapted for the new form fields
        del form.fields['email']
        del form_helper.layout.fields[0].fields[1]

        c = Context({'form': form, 'form_helper': form_helper})
        html = template.render(c)
        self.assertFalse('email' in html)

    def test_formset_layout(self):
        TestFormSet = formset_factory(TestForm, extra=3)
        formset = TestFormSet()
        helper = FormHelper()
        helper.form_id = 'thisFormsetRocks'
        helper.form_class = 'formsets-that-rock'
        helper.form_method = 'POST'
        helper.form_action = 'simpleAction'
        helper.layout = Layout(
            Fieldset("Item {{ forloop.counter }}",
                'is_company',
                'email',
            ),
            HTML("{% if forloop.first %}Note for first form only{% endif %}"),
            Row('password1', 'password2'),
            Fieldset("",
                'first_name',
                'last_name'
            )
        )

        html = render_crispy_form(
            form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()}
        )

        # Check formset fields
        django_version = django.VERSION[:3]
        hidden_count = 4  # before Django 1.7 added MIN_NUM_FORM_COUNT
        if django_version < (1, 5):
            self.assertEqual(html.count(
                'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"'
            ), 1)
            self.assertEqual(html.count(
                'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"'
            ), 1)
            if (django_version >= (1, 4) and django_version < (1, 4, 4)) or django_version < (1, 3, 6):
                self.assertEqual(html.count(
                    'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"'
                ), 1)
            else:
                self.assertEqual(html.count(
                    'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"'
                ), 1)
        else:
            self.assertEqual(html.count(
                'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"'
            ), 1)
            self.assertEqual(html.count(
                'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"'
            ), 1)
            self.assertEqual(html.count(
                'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"'
            ), 1)
            if hasattr(forms.formsets, 'MIN_NUM_FORM_COUNT'):
                self.assertEqual(html.count(
                    'id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"'
                ), 1)
                hidden_count += 1
        self.assertEqual(html.count("hidden"), hidden_count)

        # Check form structure
        self.assertEqual(html.count('<form'), 1)
        self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1)
        self.assertTrue('formsets-that-rock' in html)
        self.assertTrue('method="post"' in html)
        self.assertTrue('id="thisFormsetRocks"' in html)
        self.assertTrue('action="%s"' % reverse('simpleAction') in html)

        # Check form layout
        self.assertTrue('Item 1' in html)
        self.assertTrue('Item 2' in html)
        self.assertTrue('Item 3' in html)
        self.assertEqual(html.count('Note for first form only'), 1)
        if self.current_template_pack == 'uni_form':
            self.assertEqual(html.count('formRow'), 3)
        else:
            self.assertEqual(html.count('row'), 3)

    def test_modelformset_layout(self):
        CrispyModelFormSet = modelformset_factory(CrispyTestModel, form=TestForm4, extra=3)
        formset = CrispyModelFormSet(queryset=CrispyTestModel.objects.none())
        helper = FormHelper()
        helper.layout = Layout(
            'email'
        )

        html = render_crispy_form(form=formset, helper=helper)
        self.assertEqual(html.count("id_form-0-id"), 1)
        self.assertEqual(html.count("id_form-1-id"), 1)
        self.assertEqual(html.count("id_form-2-id"), 1)

        django_version = django.VERSION[:3]
        if django_version < (1, 5):
            self.assertEqual(html.count(
                'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"'
            ), 1)
            self.assertEqual(html.count(
                'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"'
            ), 1)
            if (django_version >= (1, 4) and django_version < (1, 4, 4)) or django_version < (1, 3, 6):
                self.assertEqual(html.count(
                    'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"'
                ), 1)
            else:
                self.assertEqual(html.count(
                    'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"'
                ), 1)
        else:
            self.assertEqual(html.count(
                'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"'
            ), 1)
            self.assertEqual(html.count(
                'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"'
            ), 1)
            self.assertEqual(html.count(
                'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"'
            ), 1)

        self.assertEqual(html.count('name="form-0-email"'), 1)
        self.assertEqual(html.count('name="form-1-email"'), 1)
        self.assertEqual(html.count('name="form-2-email"'), 1)
        self.assertEqual(html.count('name="form-3-email"'), 0)
        self.assertEqual(html.count('password'), 0)

    def test_i18n(self):
        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form.helper %}
        """)
        form = TestForm()
        form_helper = FormHelper()
        form_helper.layout = Layout(
            HTML(_("i18n text")),
            Fieldset(
                _("i18n legend"),
                'first_name',
                'last_name',
            )
        )
        form.helper = form_helper

        html = template.render(Context({'form': form}))
        self.assertEqual(html.count('i18n legend'), 1)

    @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
    def test_l10n(self):
        form = TestForm5(data={'pk': 1000})
        html = render_crispy_form(form)

        # Make sure values are unlocalized
        self.assertTrue('value="1,000"' not in html)

        # Make sure label values are NOT localized
        self.assertTrue(html.count('1000'), 2)

    def test_default_layout(self):
        test_form = TestForm2()
        self.assertEqual(test_form.helper.layout.fields, [
            'is_company', 'email', 'password1', 'password2',
            'first_name', 'last_name', 'datetime_field',
        ])

    def test_default_layout_two(self):
        test_form = TestForm3()
        self.assertEqual(test_form.helper.layout.fields, ['email'])

    def test_modelform_layout_without_meta(self):
        test_form = TestForm4()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout('email')
        html = render_crispy_form(test_form)

        self.assertTrue('email' in html)
        self.assertFalse('password' in html)

    def test_specialspaceless_not_screwing_intended_spaces(self):
        # see issue #250
        test_form = TestForm()
        test_form.fields['email'].widget = forms.Textarea()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout(
            'email',
            HTML("first span second span")
        )
        html = render_crispy_form(test_form)
        self.assertTrue('first span second span' in html)

class TestUniformFormLayout(TestFormLayout):

    def test_layout_composition(self):
        if settings.CRISPY_TEMPLATE_PACK != 'uni_form':
            warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK)
            return
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Layout(
                    MultiField("Some company data",
                        'is_company',
                        'email',
                        css_id = "multifield_info",
                    ),
                ),
                Column(
                    'first_name',
                    # 'last_name', Missing a field on purpose
                    css_id = "column_name",
                    css_class = "columns",
                ),
                ButtonHolder(
                    Submit('Save', 'Save', css_class='button white'),
                ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                )
            )
        )

        template = loader.get_template_from_string(u"""
                {% load crispy_forms_tags %}
                {% crispy form form_helper %}
            """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="Save"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertFalse('last_name' in html)

    def test_second_layout_multifield_column_buttonholder_submit_div(self):
        if settings.CRISPY_TEMPLATE_PACK != 'uni_form':
            warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK)
            return
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                MultiField("Some company data",
                    'is_company',
                    'email',
                    css_id = "multifield_info",
                    title = "multifield_title",
                    multifield_test = "123"
                ),
                Column(
                    'first_name',
                    'last_name',
                    css_id = "column_name",
                    css_class = "columns",
                ),
                ButtonHolder(
                    Submit('Save the world', '{{ value_var }}', css_class='button white', data_id='test', data_name='test'),
                    Submit('store', 'Store results')
                ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                    test_markup="123"
                )
            )
        )

        template = loader.get_template_from_string(u"""
                {% load crispy_forms_tags %}
                {% crispy form form_helper %}
            """)
        c = Context({'form': TestForm(), 'form_helper': form_helper, 'value_var': "Save"})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('title="multifield_title"' in html)
        self.assertTrue('multifield-test="123"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('button white' in html)
        self.assertTrue('data-id="test"' in html)
        self.assertTrue('data-name="test"' in html)
        self.assertTrue('name="save-the-world"' in html)
        self.assertTrue('value="Save"' in html)
        self.assertTrue('name="store"' in html)
        self.assertTrue('value="Store results"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertTrue('test-markup="123"' in html)

class TestBootstrapFormLayout(TestFormLayout):

    def test_keepcontext_context_manager(self):
        # Test case for issue #180
        # Apparently it only manifest when using render_to_response this exact way
        form = CheckboxesTestForm()
        form.helper = FormHelper()
        # We use here InlineCheckboxes as it updates context in an unsafe way
        form.helper.layout = Layout(
            'checkboxes',
            InlineCheckboxes('alphacheckboxes'),
            'numeric_multiple_checkboxes'
        )
        request_factory = RequestFactory()
        request = request_factory.get('/')
        context = RequestContext(request, {'form': form})

        response = render_to_response('crispy_render_template.html', context)

        if self.current_template_pack == 'bootstrap':
            self.assertEqual(response.content.count(b'checkbox inline'), 3)
        elif self.current_template_pack == 'bootstrap3':
            self.assertEqual(response.content.count(b'checkbox-inline'), 3)

class TestBootstrap3FormLayout(TestFormLayout):

    def test_form_inline(self):
        form = TestForm()
        form.helper = FormHelper()
        form.helper.form_class = 'form-inline'
        form.helper.field_template = 'bootstrap3/layout/inline_field.html'
        form.helper.layout = Layout(
            'email',
            'password1',
            'last_name',
        )

        html = render_crispy_form(form)
        self.assertEqual(html.count('class="form-inline"'), 1)
        self.assertEqual(html.count('class="form-group"'), 3)
        self.assertEqual(html.count('<label for="id_email" class="sr-only'), 1)
        self.assertEqual(html.count('id="div_id_email" class="form-group"'), 1)
        self.assertEqual(html.count('placeholder="email"'), 1)
        self.assertEqual(html.count(' <input'), 3)


text:
import collections
import csv
import operator
import fnmatch
import functools

import click
import requests

from archery.utils.report import JinjaReport

# TODO(kszucs): use archery.report.JinjaReport instead
class Report:

    ROW_HEADERS = [
        "task_name",
        "task_status",
        "build_links",
        "crossbow_branch_url",
        "ci_system",
        "extra_params",
        "template",
        "arrow_commit",
    ]

    def __init__(self, job, task_filters=None):
        self.job = job

        tasks = sorted(job.tasks.items())
        if task_filters:
            filtered = set()
            for pattern in task_filters:
                filtered |= set(fnmatch.filter(job.tasks.keys(), pattern))

            tasks = [(name, task) for name, task in tasks if name in filtered]

        self._tasks = dict(tasks)

    @property
    def repo_url(self):
        url = self.job.queue.remote_url
        return url[:-4] if url.endswith('.git') else url

    def url(self, query):
        return '{}/branches/all?query={}'.format(self.repo_url, query)

    def branch_url(self, branch):
        return '{}/tree/{}'.format(self.repo_url, branch)

    def task_url(self, task):
        if task.status().build_links:
            # show link to the actual build, some CI providers implement
            # the statuses API others implement the checks API, retrieve any.
            return task.status().build_links[0]
        else:
            # show link to the branch if no status build link was found.
            return self.branch_url(task.branch)

    @property
    @functools.lru_cache(maxsize=1)
    def tasks_by_state(self):
        tasks_by_state = collections.defaultdict(dict)
        for task_name, task in self.job.tasks.items():
            state = task.status().combined_state
            tasks_by_state[state][task_name] = task
        return tasks_by_state

    @property
    def contains_failures(self):
        return any(self.tasks_by_state[state] for state in (
            "error", "failure"))

    @property
    def tasks(self):
        return self._tasks

    def show(self):
        raise NotImplementedError()

    @property
    def rows(self):
        """
        Produces a generator that allow us to iterate over
        the job tasks as a list of rows.
        Row headers are defined at Report.ROW_HEADERS.
        """
        for task_name, task in sorted(self.job.tasks.items()):
            task_status = task.status()
            row = [
                task_name,
                task_status.combined_state,
                task_status.build_links,
                self.branch_url(task.branch),
                task.ci,
                # We want this to be serialized as a dict instead
                # of an orderedict.
                {k: v for k, v in task.params.items()},
                task.template,
                # Arrow repository commit
                self.job.target.head
            ]
            yield row

class ConsoleReport(Report):
    """Report the status of a Job to the console using click"""

    # output table's header template
    HEADER = '[{state:>7}] {branch:<52} {content:>16}'
    DETAILS = ' └ {url}'

    # output table's row template for assets
    ARTIFACT_NAME = '{artifact:>69} '
    ARTIFACT_STATE = '[{state:>7}]'

    # state color mapping to highlight console output
    COLORS = {
        # from CombinedStatus
        'error': 'red',
        'failure': 'red',
        'pending': 'yellow',
        'success': 'green',
        # custom state messages
        'ok': 'green',
        'missing': 'red'
    }

    def lead(self, state, branch, n_uploaded, n_expected):
        line = self.HEADER.format(
            state=state.upper(),
            branch=branch,
            content='uploaded {} / {}'.format(n_uploaded, n_expected)
        )
        return click.style(line, fg=self.COLORS[state.lower()])

    def header(self):
        header = self.HEADER.format(
            state='state',
            branch='Task / Branch',
            content='Artifacts'
        )
        delimiter = '-' * len(header)
        return '{}\n{}'.format(header, delimiter)

    def artifact(self, state, pattern, asset):
        if asset is None:
            artifact = pattern
            state = 'pending' if state == 'pending' else 'missing'
        else:
            artifact = asset.name
            state = 'ok'

        name_ = self.ARTIFACT_NAME.format(artifact=artifact)
        state_ = click.style(
            self.ARTIFACT_STATE.format(state=state.upper()),
            self.COLORS[state]
        )
        return name_ + state_

    def show(self, outstream, asset_callback=None, validate_patterns=True):
        echo = functools.partial(click.echo, file=outstream)

        # write table's header
        echo(self.header())

        # write table's body
        for task_name, task in self.tasks.items():
            # write summary of the uploaded vs total assets
            status = task.status()
            assets = task.assets(validate_patterns=validate_patterns)

            # mapping of artifact pattern to asset or None of not uploaded
            n_expected = len(task.artifacts)
            n_uploaded = len(assets.uploaded_assets())
            echo(self.lead(status.combined_state, task_name, n_uploaded,
                           n_expected))

            # show link to the actual build, some of the CI providers implement
            # the statuses API others implement the checks API, so display both
            for link in status.build_links:
                echo(self.DETAILS.format(url=link))

            # write per asset status
            for artifact_pattern, asset in assets.items():
                if asset_callback is not None:
                    asset_callback(task_name, task, asset)
                echo(self.artifact(status.combined_state, artifact_pattern,
                                   asset))

class ChatReport(JinjaReport):
    templates = {
        'text': 'chat_nightly_report.txt.j2',
    }
    fields = [
        'report',
        'extra_message_success',
        'extra_message_failure',
    ]

class ReportUtils:

    @classmethod
    def send_message(cls, webhook, message):
        resp = requests.post(webhook, json={
            "blocks": [
                {
                    "type": "section",
                    "text": {
                            "type": "mrkdwn",
                            "text": message
                    }
                }
            ]
        }
        )
        return resp

    @classmethod
    def send_email(cls, smtp_user, smtp_password, smtp_server, smtp_port,
                   recipient_email, message):
        import smtplib

        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.ehlo()
        server.login(smtp_user, smtp_password)
        server.sendmail(smtp_user, recipient_email, message)
        server.close()

    @classmethod
    def write_csv(cls, report, add_headers=True):
        with open(f'{report.job.branch}.csv', 'w') as csvfile:
            task_writer = csv.writer(csvfile)
            if add_headers:
                task_writer.writerow(report.ROW_HEADERS)
            task_writer.writerows(report.rows)

class EmailReport(JinjaReport):
    templates = {
        'text': 'email_nightly_report.txt.j2',
    }
    fields = [
        'report',
        'sender_name',
        'sender_email',
        'recipient_email',
    ]

class CommentReport(Report):

    _markdown_badge = '[![{title}]({badge})]({url})'

    badges = {
        'github': _markdown_badge.format(
            title='Github Actions',
            url='https://github.com/{repo}/actions?query=branch:{branch}',
            badge=(
                'https://github.com/{repo}/workflows/Crossbow/'
                'badge.svg?branch={branch}'
            ),
        ),
        'azure': _markdown_badge.format(
            title='Azure',
            url=(
                'https://dev.azure.com/{repo}/_build/latest'
                '?definitionId=1&branchName={branch}'
            ),
            badge=(
                'https://dev.azure.com/{repo}/_apis/build/status/'
                '{repo_dotted}?branchName={branch}'
            )
        ),
        'travis': _markdown_badge.format(
            title='TravisCI',
            url='https://app.travis-ci.com/github/{repo}/branches',
            badge='https://img.shields.io/travis/{repo}/{branch}.svg'
        ),
        'circle': _markdown_badge.format(
            title='CircleCI',
            url='https://circleci.com/gh/{repo}/tree/{branch}',
            badge=(
                'https://img.shields.io/circleci/build/github'
                '/{repo}/{branch}.svg'
            )
        ),
        'appveyor': _markdown_badge.format(
            title='Appveyor',
            url='https://ci.appveyor.com/project/{repo}/history',
            badge='https://img.shields.io/appveyor/ci/{repo}/{branch}.svg'
        ),
        'drone': _markdown_badge.format(
            title='Drone',
            url='https://cloud.drone.io/{repo}',
            badge='https://img.shields.io/drone/build/{repo}/{branch}.svg'
        ),
    }

    def __init__(self, job, crossbow_repo):
        self.crossbow_repo = crossbow_repo
        super().__init__(job)

    def show(self):
        url = 'https://github.com/{repo}/branches/all?query={branch}'
        sha = self.job.target.head

        msg = 'Revision: {}\n\n'.format(sha)
        msg += 'Submitted crossbow builds: [{repo} @ {branch}]'
        msg += '({})\n'.format(url)
        msg += '\n|Task|Status|\n|----|------|'

        tasks = sorted(self.job.tasks.items(), key=operator.itemgetter(0))
        for key, task in tasks:
            branch = task.branch

            try:
                template = self.badges[task.ci]
                badge = template.format(
                    repo=self.crossbow_repo,
                    repo_dotted=self.crossbow_repo.replace('/', '.'),
                    branch=branch
                )
            except KeyError:
                badge = 'unsupported CI service `{}`'.format(task.ci)

            msg += '\n|{}|{}|'.format(key, badge)

        return msg.format(repo=self.crossbow_repo, branch=self.job.branch)


text:
Every modal is made up of modal sections.  You can define 3 different types of sections:

* `main` - A larger section
* `subsection` - A smaller section
* `default` - The default section, it is sized in between main and subsection.

Usually a modal will consist of no more than 2 sections.  For a simple modal, use just the default section
```js
import Button from '../misc/Button'

import Modal from './Modal'
import ModalSection from './ModalSection'
import ModalBody from './ModalBody'
import ModalFooter from './ModalFooter'
import ModalHeader from './ModalHeader'
;
initialState = { isOpen: false };

<div>
  <Button color onClick={() => setState({ isOpen: true })}>Open Me!</Button>
  <Modal isOpen={state.isOpen} toggle={() => setState({ isOpen: false })}>
    <ModalSection>
      <h1>Default section</h1>
    </ModalSection>
  </Modal>
</div>
```

For more complex modals, use main and sub sections.  Use a smaller modal size to fit all the sections on the screen.
```js
import Button from '../misc/Button'

import Modal from './Modal'
import ModalSection from './ModalSection'
import ModalBody from './ModalBody'
import ModalFooter from './ModalFooter'
import ModalHeader from './ModalHeader'
;
initialState = { isOpen: false };

<div>
  <Button color onClick={() => setState({ isOpen: true })}>Open Me!</Button>
  <Modal small isOpen={state.isOpen} toggle={() => setState({ isOpen: false })}>
    <ModalSection main>
      <h1>Main section</h1>
    </ModalSection>
    <ModalSection subsection>
      <h1>Sub section</h1>
    </ModalSection>
    <ModalSection subsection>
      <h1>Sub section</h1>
    </ModalSection>
  </Modal>
</div>
```

You can change colors of the subsections as well by providing the `colored` option
```js
import Button from '../misc/Button'

import Modal from './Modal'
import ModalSection from './ModalSection'
import ModalBody from './ModalBody'
import ModalFooter from './ModalFooter'
import ModalHeader from './ModalHeader'
;
initialState = { isOpen: false };

<div>
  <Button color onClick={() => setState({ isOpen: true })}>Open Me!</Button>
  <Modal small isOpen={state.isOpen} toggle={() => setState({ isOpen: false })}>
    <ModalSection main>
      <h1>Main section</h1>
      <ModalFooter>
        <Button float color onClick={() => alert('Clicked!')}>Footer Button</Button>
      </ModalFooter>
    </ModalSection>
    <ModalSection subsection>
      <h1>Sub section</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </ModalSection>
    <ModalSection subsection colored>
      <h1>Sub section</h1>
    </ModalSection>
  </Modal>
</div>
```


text:
define(['promenade/object', 'underscore', 'promise', 'backbone'],
        function (PromenadeObject, _, Promise, Backbone) {
  'use strict';

  var ControllerAction = PromenadeObject.extend({
    initialize: function (options) {
      this._controller = options.controller;
      this._parentAction = options.parentAction;
      this._fragment = '';
      this._verb = '';
      this._type = '';
      this._handler = '';
      this._children = [];
      this._queryParameters = {};
    },

    hasVerb: function () {
      return !!this._verb;
    },

    getVerb: function () {
      return this._verb;
    },

    setVerb: function (verb) {
      this._verb = verb;
    },

    hasHandler: function () {
      return !!this._handler;
    },

    setHandler: function (handler) {
      this._handler = handler;
    },

    getHandler: function () {
      return this._handler;
    },

    hasType: function () {
      return !!this.getType();
    },

    setType: function (type) {
      this._type = type;
    },

    getType: function () {
      return this._type;
    },

    hasParentAction: function () {
      return !!this.getParentAction();
    },

    getParentAction: function () {
      return this._parentAction;
    },

    getPathnameRoot: function () {
      var pathnameRoot = '';

      if (this.hasParentAction()) {
        pathnameRoot += this.getParentAction().getPathname();
      }

      return pathnameRoot;
    },

    getPathname: function () {
      var pathnameParts = [];
      var pathnameRoot = this.getPathnameRoot();

      if (pathnameRoot) {
        pathnameParts.push(this.getPathnameRoot());
      }

      if (this.hasFragment()) {
        pathnameParts.push(this.getFragment());
      }

      if (this.hasParameter()) {
        pathnameParts.push(this.getParameter());
      }

      return pathnameParts.join('/');
    },

    getRoute: function () {
      return this.getPathname();
    },

    hasFragment: function () {
      return !!this.getFragment();
    },

    getFragment: function () {
      return this._fragment;
    },

    setFragment: function (fragment) {
      this._fragment = fragment;
    },

    hasParameter: function() {
      return this.getVerb() === ControllerAction.verbs.SHOW && this.hasType();
    },

    getParameter: function() {
      return this.hasParameter() ? ':' + this.getType() : '';
    },

    fork: function () {
      var child = new ControllerAction({
        controller: this._controller,
        parentAction: this
      });
      this._children.push(child);
      return child;
    },

    getNestedMediator: function () {
      var action = this.fork();

      return action.getMediator();
    },

    getChildren: function () {
      return this._children;
    },

    allowQueryParameter: function (key, type) {
      this._queryParameters[key] = type;
    },

    toBackboneRoute: function() {
      return {
        fragment: this.getRoute(),
        handler: this.createRouteHandlerForController()
      };
    },

    createRouteHandlerForController: function () {
      var action = this;
      var controller = this._controller;
      var actionHandler = action.getHandler();
      var controllerHandler = controller[actionHandler];
      var parameterValueActions;
      var queryValueGenerators;

      if (!controllerHandler) {
        return function () {
          throw new Error('Controller route #' + actionHandler + ' does not exist.');
        };
      }

      parameterValueActions = action.getParameterValueLineage();
      queryValueGenerators = action.getQueryValueGenerators();

      return function () {
        var rawParameters = Array.prototype.slice.call(arguments);
        var rawQueryString = action.fragmentHasSearchString() ? rawParameters.pop() : '';
        var rawQueryHash = action.parseQueryString(rawQueryString);
        var queryValues = {};

        var parameterValuePromises = _.map(parameterValueActions, function (action) {
          var generator;
          var value;

          generator = action.getFragmentValueGenerator();

          if (action.getVerb() === ControllerAction.verbs.SHOW) {
            value = rawParameters.shift();
          }

          return generator(controller.app, value);
        });

        var queryValuePromises = _.map(rawQueryHash, function (value, key) {
          var generator = queryValueGenerators[key];

          if (!generator) {
            return value;
          }

          return generator(controller.app, value).then(function (result) {
            queryValues[key] = result;
          });
        });

        var parameterValuesBecomeAvailable = Promise.all(parameterValuePromises);
        var queryValuesBecomeAvailable = Promise.all(queryValuePromises);

        controller.setActive();

        return parameterValuesBecomeAvailable.then(function (parameters) {
          return queryValuesBecomeAvailable.then(function () {
            var result;

            if (!controller.isActive()) {
              return;
            }

            parameters.push(queryValues);

            controller.currentAction = action;
            result = controller[actionHandler].apply(controller, parameters);
            controller.trigger('after:route', controller, action, result);

            return result;
          });
        });
      };
    },

    getParameterValueLineage: function () {
      var action = this;
      var lineage = [];

      while (action.hasParentAction()) {
        if (action.getVerb() !== ControllerAction.verbs.HANDLE) {
          lineage.unshift(action);
        }

        action = action.getParentAction();
      }

      return lineage;
    },

    flatten: function () {
      var actions = [this];
      var children = this.getChildren();
      var index;
      var child;

      for (index = 0; index < children.length; ++index) {
        child = children[index];
        actions = actions.concat(child.flatten());
      }

      return actions;
    },

    createGeneratorFunction: function (verb, type) {
      return function (app, value) {
        var model = app.getResource(type);

        if (!model) {
          return Promise.resolve(value);
        }

        if (verb === ControllerAction.verbs.SHOW) {
          model = model.get(value);
        } else if (_.result(model, 'needsSync') === true) {
          model.fetch();
        }

        if (_.result(model, 'isSyncing') === true) {
          model = _.result(model, 'syncs') || model;
        }

        return Promise.resolve(model);
      };
    },

    getQueryValueGenerators: function () {
      var parentAction = this.getParentAction();
      var generators;
      var key;
      var type;

      if (parentAction) {
        generators = parentAction.getQueryValueGenerators();
      } else {
        generators = {};
      }

      for (key in this._queryParameters) {
        type = this._queryParameters[key];
        generators[key] = this.createGeneratorFunction(ControllerAction.verbs.SHOW, type);
      }

      return generators;
    },

    getFragmentValueGenerator: function () {
      return this.createGeneratorFunction(this.getVerb(), this.getType());
    },

    parseMediatorArguments: function (fragment, handler, options, callback) {
      var args = {};
      args.fragment = fragment;

      if (_.isString(handler)) {
        args.handler = handler;
        if (_.isFunction(options)) {
          args.callback = options;
        } else {
          args.options = options;
          args.callback = callback;
        }
      }

      if (_.isFunction(handler)) {
        args.callback = handler;
      } else if (_.isObject(handler)) {
        args.options = handler;
        if (_.isFunction(options)) {
          args.callback = options;
        }
      }

      args.options = args.options || {};

      return args;
    },

    getMediator: function () {
      var parentAction = this;
      var parseArguments = function (args) {
        return parentAction.parseMediatorArguments.apply(parentAction, args);
      };

      return {
        show: function () {
          var args = parseArguments(arguments);
          var action = parentAction.fork();
          var fragment = args.fragment;
          var handler = args.handler;
          var options = args.options;
          var callback = args.callback;
          var type = options.type || args.fragment;

          action.setFragment(fragment);
          action.setType(type);
          action.setVerb(ControllerAction.verbs.SHOW);
          action.setHandler(handler);

          if (callback) {
            callback.call(action.getMediator());
          }
        },
        index: function () {
          var args = parseArguments(arguments);
          var action = parentAction.fork();
          var fragment = args.fragment;
          var handler = args.handler;
          var options = args.options;
          var callback = args.callback;
          var type = options.type || fragment;

          action.setFragment(fragment);
          action.setType(type);
          action.setVerb(ControllerAction.verbs.INDEX);
          action.setHandler(handler);

          if (callback) {
            callback.call(action.getMediator());
          }
        },
        handle: function () {
          var args = parseArguments(arguments);
          var action = parentAction.fork();
          var fragment = args.fragment;
          var handler = args.handler;
          var callback = args.callback;

          action.setFragment(fragment);
          action.setVerb(ControllerAction.verbs.HANDLE);
          action.setHandler(handler);

          if (callback) {
            callback.call(action.getMediator());
          }
        },
        query: function () {
          var args = parseArguments(arguments);
          var action = parentAction;
          var queryKey = args.fragment;
          var options = args.options;
          var type = options.type || queryKey;

          action.allowQueryParameter(queryKey, type);
        },
        getRelatedAction: function () {
          return parentAction;
        }
      };
    },

    fragmentHasSearchString: function() {
      var controller = this._controller;
      var matcher = ControllerAction.SEARCH_STRING_MATCHER;

      return matcher.test(controller.getFragment());
    },

    parseQueryString: function(queryString) {
      var parts;

      if (queryString) {
        parts = queryString.split('&');
      } else {
        parts = [];
      }

      return _.reduce(parts, function(queryHash, part) {
        var keyValue = part.split('=');
        var key = keyValue[0];
        var value = keyValue[1];

        if (typeof value === 'undefined') {
          value = true;
        }

        queryHash[key] = value;

        return queryHash;
      }, {});
    }
  }, {
    verbs: {
      SHOW: 'show',
      INDEX: 'index',
      HANDLE: 'handle'
    },
    SEARCH_STRING_MATCHER: /[^?]*\?.+$/
  });

  return ControllerAction;
});


text:
var ConversationV1 = require('watson-developer-cloud/conversation/v1');

require('dotenv').config()

var conversation = new ConversationV1({
  username: process.env.CONVERSATION_USERNAME,
  password: process.env.CONVERSATION_PASSWORD,
  version_date: ConversationV1.VERSION_DATE_2017_05_26
});

conversation.message({
  input: { text: 'hello' },
  workspace_id: process.env.WORKSPACE_ID
 }, function(err, response) {
     if (err) {
       console.error(err);
     } else {
       console.log(JSON.stringify(response, null, 2));
     }
});


text:
using BoletoNet.Enums;
using System;
using System.Collections.Generic;

namespace BoletoNet
{
    #region Enumerado

    public enum EnumCodigoMovimento_BancoBrasil
    {
        EntradaConfirmada = 2,
        EntradaRejeitada = 3,
        TransferenciaCarteiraEntrada = 4,
        TransferenciaCarteiraBaixa = 5,
        Liquidacao = 6,
        Baixa = 9,
        TitulosCarteiraEmSer = 11,
        ConfirmacaoRecebimentoInstrucaoAbatimento = 12,
        ConfirmacaoRecebimentoInstrucaoCancelamentoAbatimento = 13,
        ConfirmacaoRecebimentoInstrucaoAlteracaoVencimento = 14,
        FrancoPagamento = 15,
        LiquidacaoAposBaixa = 17,
        ConfirmacaoRecebimentoInstrucaoProtesto = 19,
        ConfirmacaoRecebimentoInstrucaoSustacaoProtesto = 20,
        RemessaCartorio = 23,
        RetiradaCartorioManutencaoCarteira = 24,
        ProtestadoBaixado = 25,
        InstrucaoRejeitada = 26,
        ConfirmaçãoPedidoAlteracaoOutrosDados = 27,
        DebitoTarifas = 28,
        OcorrenciaSacado = 29,
        AlteracaoDadosRejeitada = 30,
    }

    #endregion

    public class CodigoMovimento_BancoBrasil : AbstractCodigoMovimento, ICodigoMovimento
    {
        #region Construtores

        public CodigoMovimento_BancoBrasil()
        {
            try
            {
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

        public CodigoMovimento_BancoBrasil(int codigo)
        {
            try
            {
                this.carregar(codigo);
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

        #endregion

        #region Metodos Privados

        private void carregar(int codigo)
        {
            try
            {
                this.Banco = new Banco_Brasil();

                switch ((EnumCodigoMovimento_BancoBrasil)codigo)
                {
                    case EnumCodigoMovimento_BancoBrasil.EntradaConfirmada:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.EntradaConfirmada;
                        this.Descricao = "Entrada confirmada";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.EntradaRejeitada:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.EntradaRejeitada;
                        this.Descricao = "Entrada rejeitada";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraEntrada:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraEntrada;
                        this.Descricao = "Transferência de carteira/entrada";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraBaixa:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraBaixa;
                        this.Descricao = "Transferência de carteira/baixa";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.Liquidacao:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.Liquidacao;
                        this.Descricao = "Liquidação normal";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.Baixa:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.Baixa;
                        this.Descricao = "Baixa";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.TitulosCarteiraEmSer:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TitulosCarteiraEmSer;
                        this.Descricao = "Títulos em carteira em ser";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAbatimento:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAbatimento;
                        this.Descricao = "Confirmação recebimento instrução de abatimento";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoCancelamentoAbatimento:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoCancelamentoAbatimento;
                        this.Descricao = "Confirmação recebimento instrução de cancelamento de abatimento";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAlteracaoVencimento:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAlteracaoVencimento;
                        this.Descricao = "Confirmação recebimento instrução alteração de vencimento";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.FrancoPagamento:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.FrancoPagamento;
                        this.Descricao = "Franco pagamento";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.LiquidacaoAposBaixa:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.LiquidacaoAposBaixa;
                        this.Descricao = "Liquidação após baixa";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoProtesto:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoProtesto;
                        this.Descricao = "Confirmação de recebimento de instrução de protesto";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoSustacaoProtesto:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoSustacaoProtesto;
                        this.Descricao = "Confirmação de recebimento de instrução de sustação de protesto";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.RemessaCartorio:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.RemessaCartorio;
                        this.Descricao = "Remessa a cartório/aponte em cartório";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.RetiradaCartorioManutencaoCarteira:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.RetiradaCartorioManutencaoCarteira;
                        this.Descricao = "Retirada de cartório e manutenção em carteira";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ProtestadoBaixado:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ProtestadoBaixado;
                        this.Descricao = "Protestado e baixado/baixa por ter sido protestado";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.InstrucaoRejeitada:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.InstrucaoRejeitada;
                        this.Descricao = "Instrução rejeitada";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.ConfirmaçãoPedidoAlteracaoOutrosDados:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmaçãoPedidoAlteracaoOutrosDados;
                        this.Descricao = "Confirmação do pedido de alteração de outros dados";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.DebitoTarifas:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.DebitoTarifas;
                        this.Descricao = "Debito de tarifas/custas";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.OcorrenciaSacado:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.OcorrenciaSacado;
                        this.Descricao = "Ocorrencias do sacado";
                        break;
                    case EnumCodigoMovimento_BancoBrasil.AlteracaoDadosRejeitada:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.AlteracaoDadosRejeitada;
                        this.Descricao = "Alteração de dados rejeitada";
                        break;
                    default:
                        this.Codigo = 0;
                        this.Descricao = "( Selecione )";
                        break;
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

        private void Ler(int codigo)
        {
            try
            {
                switch (codigo)
                {
                    case 2:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.EntradaConfirmada;
                        this.Descricao = "Entrada confirmada";
                        break;
                    case 3:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.EntradaRejeitada;
                        this.Descricao = "Entrada rejeitada";
                        break;
                    case 4:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraEntrada;
                        this.Descricao = "Transferência de carteira/entrada";
                        break;
                    case 5:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraBaixa;
                        this.Descricao = "Transferência de carteira/baixa";
                        break;
                    case 6:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.Liquidacao;
                        this.Descricao = "Liquidação";
                        break;
                    case 9:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.Baixa;
                        this.Descricao = "Baixa";
                        break;
                    case 11:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.TitulosCarteiraEmSer;
                        this.Descricao = "Títulos em carteira em ser";
                        break;
                    case 12:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAbatimento;
                        this.Descricao = "Confirmação recebimento instrução de abatimento";
                        break;
                    case 13:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoCancelamentoAbatimento;
                        this.Descricao = "Confirmação recebimento instrução de cancelamento de abatimento";
                        break;
                    case 14:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAlteracaoVencimento;
                        this.Descricao = "Confirmação recebimento instrução alteração de vencimento";
                        break;
                    case 15:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.FrancoPagamento;
                        this.Descricao = "Franco pagamento";
                        break;
                    case 17:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.LiquidacaoAposBaixa;
                        this.Descricao = "Liquidação após baixa";
                        break;
                    case 19:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoProtesto;
                        this.Descricao = "Confirmação de recebimento de instrução de protesto";
                        break;
                    case 20:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoSustacaoProtesto;
                        this.Descricao = "Confirmação de recebimento de instrução de sustação de protesto";
                        break;
                    case 23:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.RemessaCartorio;
                        this.Descricao = "Remessa a cartório/aponte em cartório";
                        break;
                    case 24:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.RetiradaCartorioManutencaoCarteira;
                        this.Descricao = "Retirada de cartório e manutenção em carteira";
                        break;
                    case 25:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ProtestadoBaixado;
                        this.Descricao = "Protestado e baixado/baixa por ter sido protestado";
                        break;
                    case 26:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.InstrucaoRejeitada;
                        this.Descricao = "Instrução rejeitada";
                        break;
                    case 27:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.ConfirmaçãoPedidoAlteracaoOutrosDados;
                        this.Descricao = "Confirmação do pedido de alteração de outros dados";
                        break;
                    case 28:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.DebitoTarifas;
                        this.Descricao = "Debito de tarifas/custas";
                        break;
                    case 29:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.OcorrenciaSacado;
                        this.Descricao = "Ocorrencias do sacado";
                        break;
                    case 30:
                        this.Codigo = (int)EnumCodigoMovimento_BancoBrasil.AlteracaoDadosRejeitada;
                        this.Descricao = "Alteração de dados rejeitada";
                        break;
                    default:
                        this.Codigo = 0;
                        this.Descricao = "( Selecione )";
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

        public override TipoOcorrenciaRetorno ObterCorrespondenteFebraban()
        {
            return ObterCorrespondenteFebraban(correspondentesFebraban, (EnumCodigoMovimento_BancoBrasil)Codigo);
        }

        private readonly Dictionary<EnumCodigoMovimento_BancoBrasil, TipoOcorrenciaRetorno> correspondentesFebraban = new Dictionary<EnumCodigoMovimento_BancoBrasil, TipoOcorrenciaRetorno>()
        {
            { EnumCodigoMovimento_BancoBrasil.EntradaConfirmada, TipoOcorrenciaRetorno.EntradaConfirmada },
            { EnumCodigoMovimento_BancoBrasil.EntradaRejeitada                                     , TipoOcorrenciaRetorno.EntradaRejeitada                                       },
            { EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraEntrada                         , TipoOcorrenciaRetorno.TransferenciaDeCarteiraEntrada                           },
            { EnumCodigoMovimento_BancoBrasil.TransferenciaCarteiraBaixa                           , TipoOcorrenciaRetorno.TransferenciaDeCarteiraBaixa                             },
            { EnumCodigoMovimento_BancoBrasil.Liquidacao                                           , TipoOcorrenciaRetorno.Liquidacao                                             },
            { EnumCodigoMovimento_BancoBrasil.Baixa                                                , TipoOcorrenciaRetorno.Baixa                                                  },
            { EnumCodigoMovimento_BancoBrasil.TitulosCarteiraEmSer                                 , TipoOcorrenciaRetorno.TitulosEmCarteira                                   },
            { EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAbatimento            , TipoOcorrenciaRetorno.ConfirmacaoRecebimentoInstrucaoDeAbatimento              },
            { EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoCancelamentoAbatimento, TipoOcorrenciaRetorno.ConfirmacaoRecebimentoInstrucaoDeCancelamentoAbatimento  },
            { EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoAlteracaoVencimento   , TipoOcorrenciaRetorno.ConfirmacaoRecebimentoInstrucaoAlteracaoDeVencimento     },
            { EnumCodigoMovimento_BancoBrasil.FrancoPagamento                                      , TipoOcorrenciaRetorno.FrancoDePagamento                                        },
            { EnumCodigoMovimento_BancoBrasil.LiquidacaoAposBaixa                                  , TipoOcorrenciaRetorno.LiquidacaoAposBaixaOuLiquidacaoTituloNaoRegistrado },
            { EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoProtesto              , TipoOcorrenciaRetorno.ConfirmacaoRecebimentoInstrucaoDeProtesto                },
            { EnumCodigoMovimento_BancoBrasil.ConfirmacaoRecebimentoInstrucaoSustacaoProtesto      , TipoOcorrenciaRetorno.ConfirmacaoRecebimentoInstrucaoDeSustacaoCancelamentoDeProtesto        },
            { EnumCodigoMovimento_BancoBrasil.RemessaCartorio                                      , TipoOcorrenciaRetorno.RemessaACartorio                                        },
            { EnumCodigoMovimento_BancoBrasil.RetiradaCartorioManutencaoCarteira                   , TipoOcorrenciaRetorno.RetiradaDeCartorioEManutencaoEmCarteira                     },
            { EnumCodigoMovimento_BancoBrasil.ProtestadoBaixado                                    , TipoOcorrenciaRetorno.ProtestadoEBaixado                                      },
            { EnumCodigoMovimento_BancoBrasil.InstrucaoRejeitada                                   , TipoOcorrenciaRetorno.InstrucaoRejeitada                                     },
            { EnumCodigoMovimento_BancoBrasil.ConfirmaçãoPedidoAlteracaoOutrosDados                , TipoOcorrenciaRetorno.ConfirmacaoDoPedidoDeAlteracaoDeOutrosDados                  },
            { EnumCodigoMovimento_BancoBrasil.DebitoTarifas                                        , TipoOcorrenciaRetorno.DebitoDeTarifasCustas                                          },
            { EnumCodigoMovimento_BancoBrasil.OcorrenciaSacado                                     , TipoOcorrenciaRetorno.OcorrenciasDoPagador                                       },
            { EnumCodigoMovimento_BancoBrasil.AlteracaoDadosRejeitada                              , TipoOcorrenciaRetorno.AlteracaoDeDadosRejeitada }
        };

        #endregion
    }
}


text:
SYNONYM

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

#### Published in
Australas. Chem. Druggist 8:12. 1885

#### Original name
null

### Remarks
null


text:
BOOST_FIXTURE_TEST_SUITE(sigma_protocol_tests, ZerocoinTestingSetup200)

BOOST_AUTO_TEST_CASE(one_out_of_n)
{
    auto params = sigma::Params::get_default();
    int N = 16384;
    int n = params->get_n();
    int m = params->get_m();
    int index = 0;

    secp_primitives::GroupElement g;
    g.randomize();
    std::vector<secp_primitives::GroupElement> h_gens;
    h_gens.resize(n * m);
    for(int i = 0; i < n * m; ++i ){
        h_gens[i].randomize();
    }
    secp_primitives::Scalar r;
    r.randomize();
    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);

    std::vector<secp_primitives::GroupElement> commits;
    for(int i = 0; i < N; ++i){
        if(i == index){
            secp_primitives::GroupElement c;
            secp_primitives::Scalar zero(uint64_t(0));
            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);
            commits.push_back(c);

        }
        else{
            commits.push_back(secp_primitives::GroupElement());
            commits[i].randomize();
        }
    }
    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);

    prover.proof(commits, index, r, true, proof);

    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);

    BOOST_CHECK(verifier.verify(commits, proof, true));
}

BOOST_AUTO_TEST_CASE(one_out_of_n_padding)
{
    auto params = sigma::Params::get_default();
    int N = 10000;
    int n = params->get_n();
    int m = params->get_m();
    int index = 9999;

    secp_primitives::GroupElement g;
    g.randomize();
    std::vector<secp_primitives::GroupElement> h_gens;
    h_gens.resize(n * m);
    for(int i = 0; i < n * m; ++i ){
        h_gens[i].randomize();
    }
    secp_primitives::Scalar r;
    r.randomize();
    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);

    std::vector<secp_primitives::GroupElement> commits;
    for(int i = 0; i < N; ++i){
        if(i == index){
            secp_primitives::GroupElement c;
            secp_primitives::Scalar zero(uint64_t(0));
            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);
            commits.push_back(c);

        }
        else{
            commits.push_back(secp_primitives::GroupElement());
            commits[i].randomize();
        }
    }
    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);

    prover.proof(commits, index, r, true, proof);

    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);

    BOOST_CHECK(verifier.verify(commits, proof, true));

    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proofNew(n, m);
    prover.proof(commits, 11111, r, true, proofNew);
    BOOST_CHECK(verifier.verify(commits, proofNew, true));
}

BOOST_AUTO_TEST_CASE(prove_and_verify_in_different_set)
{
    auto params = sigma::Params::get_default();
    int N = 16384;
    int n = params->get_n();
    int m = params->get_m();
    int index = 0;

    secp_primitives::GroupElement g;
    g.randomize();
    std::vector<secp_primitives::GroupElement> h_gens;
    h_gens.resize(n * m);
    for(int i = 0; i < n * m; ++i ){
        h_gens[i].randomize();
    }
    secp_primitives::Scalar r;
    r.randomize();
    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);

    std::vector<secp_primitives::GroupElement> commits;
    for(int i = 0; i < N; ++i){
        if(i == index){
            secp_primitives::GroupElement c;
            secp_primitives::Scalar zero(uint64_t(0));
            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);
            commits.push_back(c);

        }
        else{
            commits.push_back(secp_primitives::GroupElement());
            commits[i].randomize();
        }
    }

    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);

    prover.proof(commits, index, r, true, proof);

    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);

    // Add more commit
    secp_primitives::GroupElement c;
    secp_primitives::Scalar zero(uint64_t(0));
    c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);
    commits.push_back(c);

    BOOST_CHECK(!verifier.verify(commits, proof, true));
}

BOOST_AUTO_TEST_CASE(prove_coin_out_of_index)
{
    auto params = sigma::Params::get_default();
    int N = 16384;
    int n = params->get_n();
    int m = params->get_m();

    secp_primitives::GroupElement g;
    g.randomize();
    std::vector<secp_primitives::GroupElement> h_gens;
    h_gens.resize(n * m);
    for(int i = 0; i < n * m; ++i ){
        h_gens[i].randomize();
    }
    secp_primitives::Scalar r;
    r.randomize();
    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);

    std::vector<secp_primitives::GroupElement> commits;
    for(int i = 0; i < N; ++i){
        commits.push_back(secp_primitives::GroupElement());
        commits[i].randomize();
    }

    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);

    prover.proof(commits, commits.size(), r, true, proof);

    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);
    BOOST_CHECK(!verifier.verify(commits, proof, true));
}

BOOST_AUTO_TEST_CASE(prove_coin_not_in_set)
{
    auto params = sigma::Params::get_default();
    int N = 16384;
    int n = params->get_n();
    int m = params->get_m();
    int index = 0;
    secp_primitives::GroupElement g;
    g.randomize();
    std::vector<secp_primitives::GroupElement> h_gens;
    h_gens.resize(n * m);
    for(int i = 0; i < n * m; ++i ){
        h_gens[i].randomize();
    }
    secp_primitives::Scalar r;
    r.randomize();
    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);

    std::vector<secp_primitives::GroupElement> commits;
    for(int i = 0; i < N; ++i){
        commits.push_back(secp_primitives::GroupElement());
        commits[i].randomize();
    }

    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);

    prover.proof(commits, index, r, true, proof);

    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);
    BOOST_CHECK(!verifier.verify(commits, proof, true));
}

BOOST_AUTO_TEST_SUITE_END()


text:
package io.quarkus.devtools.codestarts.quarkus;

import static io.quarkus.devtools.codestarts.quarkus.QuarkusCodestartCatalog.Language.JAVA;
import static io.quarkus.devtools.codestarts.quarkus.QuarkusCodestartCatalog.Language.KOTLIN;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.devtools.testing.codestarts.QuarkusCodestartTest;

public class RESTClientCodestartTest {

    @RegisterExtension
    public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder()
            .codestarts("rest-client")
            .languages(JAVA, KOTLIN)
            .build();

    @Test
    void testContent() throws Throwable {
        codestartTest.checkGeneratedSource("org.acme.MyRemoteService");
    }

    @Test
    @EnabledIfSystemProperty(named = "build-projects", matches = "true")
    void buildAllProjectsForLocalUse() throws Throwable {
        codestartTest.buildAllProjects();
    }

}


text:
package com.dci.intellij.dbn.ddl;

import com.dci.intellij.dbn.common.util.DocumentUtil;
import com.dci.intellij.dbn.ddl.options.DDLFileSettings;
import com.dci.intellij.dbn.editor.DBContentType;
import com.dci.intellij.dbn.vfs.DatabaseEditableObjectFile;
import com.dci.intellij.dbn.vfs.SourceCodeFile;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.vfs.VirtualFile;

import java.util.List;

public class ObjectToDDLContentSynchronizer implements Runnable {
    DatabaseEditableObjectFile databaseFile;
    private DBContentType sourceContentType;

    public ObjectToDDLContentSynchronizer(DBContentType sourceContentType, DatabaseEditableObjectFile databaseFile) {
        this.sourceContentType = sourceContentType;
        this.databaseFile = databaseFile;
    }

    public void run() {
        assert !sourceContentType.isBundle();
        DDLFileManager ddlFileManager = DDLFileManager.getInstance(databaseFile.getProject());
        List<VirtualFile> ddlFiles = databaseFile.getBoundDDLFiles();
        DDLFileSettings ddlFileSettings = DDLFileSettings.getInstance(databaseFile.getProject());
        String postfix = ddlFileSettings.getGeneralSettings().getStatementPostfix().value();

        if (ddlFiles != null && !ddlFiles.isEmpty()) {
            for (VirtualFile ddlFile : ddlFiles) {
                DDLFileType ddlFileType = ddlFileManager.getDDLFileTypeForExtension(ddlFile.getExtension());
                DBContentType fileContentType = ddlFileType.getContentType();

                StringBuilder buffer = new StringBuilder();
                if (fileContentType.isBundle()) {
                    DBContentType[] contentTypes = fileContentType.getSubContentTypes();
                    for (DBContentType contentType : contentTypes) {
                        SourceCodeFile virtualFile = (SourceCodeFile) databaseFile.getContentFile(contentType);
                        String statement = virtualFile.createDDLStatement();
                        if (statement.trim().length() > 0) {
                            buffer.append(statement);
                            if (postfix.length() > 0) {
                                buffer.append("\n");
                                buffer.append(postfix);
                            }
                            buffer.append("\n");
                        }
                        if (contentType != contentTypes[contentTypes.length - 1]) buffer.append("\n");
                    }
                } else {
                    SourceCodeFile virtualFile = (SourceCodeFile) databaseFile.getContentFile(fileContentType);
                    buffer.append(virtualFile.createDDLStatement());
                    if (postfix.length() > 0) {
                        buffer.append("\n");
                        buffer.append(postfix);
                    }
                    buffer.append("\n");
                }
                Document document = DocumentUtil.getDocument(ddlFile);
                document.setReadOnly(false);
                document.setText(buffer.toString());
                document.setReadOnly(true);
            }
        }
    }
}


text:
/**
 *Clase que se encarga de contener los métodos de las clases que estan relacionadas
 *con ProgramaCurso para que el usuario pueda realizar las peticiones,
 * accediendo así al subsistema
 */
package ec.edu.espe.educat.dao;

import ec.edu.espe.edu.educat.model.ProgramaCurso;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @version 1.0
 * @author Diego Yandun
 */
@Stateless
public class ProgramaCursoFacade extends AbstractFacade<ProgramaCurso> implements ProgramaCursoFacadeLocal {

    @PersistenceContext(unitName = "com.mycompany_EducaT05-ejb_ejb_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ProgramaCursoFacade() {
        super(ProgramaCurso.class);
    }

}


text:
class ArmasController < ApplicationController
  before_action :set_arma, only: [:show, :update, :destroy]

  # GET /armas
  def index
    @armas = Arma.all

    render json: @armas
  end

  # GET /armas/1
  def show
    render json: @arma
  end

  # POST /armas
  def create
    @arma = Arma.new(arma_params)

    if @arma.save
      render json: @arma, status: :created, location: @arma
    else
      render json: @arma.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /armas/1
  def update
    if @arma.update(arma_params)
      render json: @arma
    else
      render json: @arma.errors, status: :unprocessable_entity
    end
  end

  # DELETE /armas/1
  def destroy
    @arma.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_arma
      @arma = Arma.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def arma_params
      params.require(:arma).permit(:arma_nombre, :arma_id)
    end
end


text:
[![npm](https://img.shields.io/badge/npmjs-1.0.3-brightgreen.svg)](https://www.npmjs.com/package/hexo-generator-searchdb)

Generate search data for Hexo 3.0. This plugin is used for generating a `search.xml` file, which contains all the neccessary data of your articles that you can use to write a local search engine for your blog.

[Demo](http://wzpan.github.io/hexo-theme-freemind/404.html) - check out the search engine in this 404 page.

## Install

``` bash
$ npm install hexo-generator-searchdb --save
```

## Options

You can configure this plugin in your root `_config.yml`. All the arguments are optional.

``` yaml
search:
  path: search.xml
  field: post
  format: html
  limit: 10000
```

- **path** - file path. Default is `search.xml` .
- **field** - the search scope you want to search, you can chose:
  * **post** (Default) - will only covers all the posts of your blog.
  * **page** - will only covers all the pages of your blog.
  * **all** - will covers all the posts and pages of your blog.
- **format** - the form of the page contents, options are:
  * **html** (Default) - original html string being minified.
  * **raw** - markdown text of each posts or pages.
  * **excerpt** - only collect excerpt.
  * **more** - act as you think.
- **limit** - define the maximum number of posts being indexed, always prefer the newest.


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Commentaire
 *
 * @ORM\Table(name="commentaire")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CommentaireRepository")
 */
class Commentaire {

    public function __construct() {
        $this->date = new \DateTime;
    }

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="contenu", type="text")
     */
    private $contenu;

    /**
     * @var Article
     *
     * @ORM\ManyToOne (targetEntity="Article", inversedBy="commentaires")
     * @ORM\JoinColumn (nullable=false)
     */
    private $article;

    /**
     * @var User
     *
     * @ORM\ManyToOne (targetEntity="User")
     *
     */
    private $user;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;

    /**
     * Get id
     *
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set contenu
     *
     * @param string $contenu
     *
     * @return Commentaire
     */
    public function setContenu($contenu) {
        $this->contenu = $contenu;

        return $this;
    }

    /**
     * Get contenu
     *
     * @return string
     */
    public function getContenu() {
        return $this->contenu;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     *
     * @return Commentaire
     */
    public function setDate($date) {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate() {
        return $this->date;
    }

    /**
     * Set article
     *
     * @param \AppBundle\Entity\Article $article
     *
     * @return Commentaire
     */
    public function setArticle(\AppBundle\Entity\Article $article) {
        $this->article = $article;

        return $this;
    }

    /**
     * Get article
     *
     * @return \AppBundle\Entity\Article
     */
    public function getArticle() {
        return $this->article;
    }

    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     *
     * @return Commentaire
     */
    public function setUser(\AppBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}