text:
<?php
/**
 * Unit tests for CForm object.
 *
 * @access      private
 * @package     Creovel
 * @subpackage  UnitTest
 * @license     http://creovel.org/license MIT License
 * @since       Class available since Release 0.4.5
 * @author      Nesbert Hidalgo
 **/
require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'env.php';

class CFormTest extends PHPUnit_Extensions_OutputTestCase
{
    /**
     * @var    CForm
     * @access protected
     */
    protected $f;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     *
     * @access protected
     */
    protected function setUp()
    {
        $this->f = new CForm;

        $this->date_select = '<select name="date[month]" id="date_month">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="date[day]" id="date_day">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
';
        $i = (date('Y') - 3);
        $years = array();
        while ($i <= (date('Y') + 3)) { $years[$i] = $i; $i++; }

        $this->date_select .= CForm::select("date[year]", date('Y'), $years);

        $this->time_select = '<select name="date[hour]" id="date_hour">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6" selected="selected">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="date[minute]" id="date_minute">
<option value="00">00</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30" selected="selected">30</option>
<option value="31">31</option>
<option value="32">32</option>
<option value="33">33</option>
<option value="34">34</option>
<option value="35">35</option>
<option value="36">36</option>
<option value="37">37</option>
<option value="38">38</option>
<option value="39">39</option>
<option value="40">40</option>
<option value="41">41</option>
<option value="42">42</option>
<option value="43">43</option>
<option value="44">44</option>
<option value="45">45</option>
<option value="46">46</option>
<option value="47">47</option>
<option value="48">48</option>
<option value="49">49</option>
<option value="50">50</option>
<option value="51">51</option>
<option value="52">52</option>
<option value="53">53</option>
<option value="54">54</option>
<option value="55">55</option>
<option value="56">56</option>
<option value="57">57</option>
<option value="58">58</option>
<option value="59">59</option>
</select>
<select name="date[ampm]" id="date_ampm">
<option value="AM">AM</option>
<option value="PM" selected="selected">PM</option>
</select>
';
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     *
     * @access protected
     */
    protected function tearDown()
    {
    }

    public function testName_to_id()
    {
        $this->assertEquals('first_name', CForm::name_to_id('first_name'));
        $this->assertEquals('name_first', CForm::name_to_id('name[first]'));
    }

    public function testAdd_error()
    {
        CForm::add_error('first_name', 'First name is required');
        $this->assertEquals(
            'First name is required',
            $GLOBALS['CREOVEL']['VALIDATION_ERRORS']['first_name']
            );
    }

    public function testField_has_error()
    {
        CForm::add_error('first_name', 'First name is required');
        $this->assertTrue(CForm::field_has_error('first_name'));
    }

    public function testHas_error()
    {
        CForm::add_error('first_name', 'First name is required');
        $this->assertTrue(CForm::has_error());
    }

    public function testError_count()
    {
        CForm::add_error('first_name', 'First name is required');
        CForm::add_error('last_name', 'Last name is required');
        $this->assertEquals(2, CForm::error_count());
    }

    public function testError_messages_for()
    {
        CForm::add_error('first_name', 'First name is required');
        $o = '

1 error has prohibited this Form from being saved.

First name is required

';

        $this->expectOutputString($o);
        echo CForm::error_messages_for();
    }

    public function testStart_form()
    {
        $this->expectOutputString('<form method="post" id="form_a" name="form_a" action="a/b">
');
        echo CForm::start_form(
                array('controller'=>'a', 'action'=>'b')
                );
    }

    public function testEnd_form()
    {
        $this->assertEquals("</form>\n", CForm::end_form());
    }

    public function testInput()
    {
        $this->assertEquals(
            '<input type="text" id="a" name="a" />'."\n",
            CForm::input('text', 'a'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="b" />'."\n",
            CForm::input('text', 'a', 'b'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="b" class="c" />'."\n",
            CForm::input('text', 'a', 'b', array('class' => 'c')));
        $this->assertEquals(
            '<input type="checkbox" id="a_d" name="a" value="d" class="c" />'."\n",
            CForm::input('checkbox', 'a', 'b', array('class' => 'c'), 'd'));
        $this->assertEquals(
            '<input type="checkbox" id="a_d" name="a" value="d" class="c" checked="checked" />'."\n",
            CForm::input('checkbox', 'a', 'd', array('class' => 'c'), 'd'));
        $this->assertEquals(
            '<input type="checkbox" id="a_d" name="a" value="d" class="c" checked="checked" /> APPEND'."\n",
            CForm::input('checkbox', 'a', 'd', array('class' => 'c'), 'd', 'APPEND'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0" />'."\n",
            CForm::input('text', 'a', '0'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0" />'."\n",
            CForm::input('text', 'a', 0));
        $this->assertEquals(
            '<input type="text" id="a" name="a" />'."\n",
            CForm::input('text', 'a', null));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="123" />'."\n",
            CForm::input('text', 'a', 123));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0" />'."\n",
            CForm::input('text', 'a', 0.0));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0.01" />'."\n",
            CForm::input('text', 'a', 0.01));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0.00" />'."\n",
            CForm::input('text', 'a', '0.00'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="0.000" />'."\n",
            CForm::input('text', 'a', '0.000'));
    }

    /**
     * @depends testInput
     */
    public function testText_field()
    {
        $this->assertEquals(
            '<input type="text" id="a" name="a" />'."\n",
            CForm::text_field('a'));
        $this->assertEquals(
            '<input type="text" id="a" name="a" value="b" />'."\n",
            CForm::text_field('a', 'b'));
    }

    /**
     * @depends testInput
     */
    public function testHidden_field()
    {
        $this->assertEquals(
            '<input type="hidden" id="a" name="a" />'."\n",
            CForm::hidden_field('a'));
        $this->assertEquals(
            '<input type="hidden" id="a" name="a" value="b" />'."\n",
            CForm::hidden_field('a', 'b'));
    }

    /**
     * @depends testInput
     */
    public function testPassword_field()
    {
        $this->assertEquals(
            '<input type="password" id="a" name="a" autocomplete="off" />'."\n",
            CForm::password_field('a'));
        $this->assertEquals(
            '<input type="password" id="a" name="a" value="b" autocomplete="off" />'."\n",
            CForm::password_field('a', 'b'));
    }

    /**
     * @depends testInput
     */
    public function testRadio_button()
    {
        $this->assertEquals(
            '<input type="radio" id="a" name="a" value="" checked="checked" />'."\n",
            CForm::radio_button('a'));
        $this->assertEquals(
            '<input type="radio" id="a" name="a" value="" />'."\n",
            CForm::radio_button('a', 'b'));
        $this->assertEquals(
            '<input type="radio" id="a" name="a" value="" class="c" />'."\n",
            CForm::radio_button('a', 'b', array('class' => 'c')));
        $this->assertEquals(
            '<input type="radio" id="a_b" name="a" value="b" checked="checked" />'."\n",
            CForm::radio_button('a', 'b', null, 'b'));
        $this->assertEquals(
            '<input type="radio" id="a_b" name="a" value="b" checked="checked" /> TEST'."\n",
            CForm::radio_button('a', 'b', null, 'b', 'TEST'));
    }

    /**
     * @depends testInput
     */
    public function testCheck_box()
    {
        $this->assertEquals(
            '<input type="checkbox" id="a" name="a" value="" checked="checked" />'."\n",
            CForm::check_box('a'));
        $this->assertEquals(
            '<input type="checkbox" id="a" name="a" value="" />'."\n",
            CForm::check_box('a', 'b'));
        $this->assertEquals(
            '<input type="checkbox" id="a" name="a" value="" class="c" />'."\n",
            CForm::check_box('a', 'b', array('class' => 'c')));
        $this->assertEquals(
            '<input type="checkbox" id="a_b" name="a" value="b" checked="checked" />'."\n",
            CForm::check_box('a', 'b', null, 'b'));
        $this->assertEquals(
            '<input type="checkbox" id="a_b" name="a" value="b" checked="checked" /> TEST'."\n",
            CForm::check_box('a', 'b', null, 'b', 'TEST'));
    }

    /**
     * @depends testInput
     */
    public function testSubmit()
    {
        $this->assertEquals(
            '<input type="submit" value="Submit" />'."\n",
            CForm::submit());
        $this->assertEquals(
            '<input type="submit" value="Click Here" class="b" />'."\n",
            CForm::submit('Click Here', array('class' => 'b')));
    }

    /**
     * @depends testInput
     */
    public function testButton()
    {
        $this->assertEquals(
            '<input type="button" value="Button" />'."\n",
            CForm::button());
        $this->assertEquals(
            '<input type="button" value="Click Here" class="b" />'."\n",
            CForm::button('Click Here', array('class' => 'b')));
    }

    public function testTextarea()
    {
        $this->assertEquals(
            '<textarea id="a" name="a"></textarea>'."\n",
            CForm::textarea('a'));
        $this->assertEquals(
            '<textarea id="a" name="a" class="c">b</textarea>'."\n",
            CForm::textarea('a', 'b', array('class' => 'c')));
    }

    /**
     * @depends testInput
     */
    public function testText_area()
    {
        $this->assertEquals(
            '<textarea id="a" name="a"></textarea>'."\n",
            CForm::text_area('a'));
        $this->assertEquals(
            '<textarea id="a" name="a" class="c">b</textarea>'."\n",
            CForm::text_area('a', 'b', array('class' => 'c')));
    }

    public function testLabel()
    {
        $this->assertEquals(
            'A'."\n",
            CForm::label('a'));
        $this->assertEquals(
            'b'."\n",
            CForm::label('a', 'b', array('class' => 'c')));
    }

    public function testSelect()
    {
        $this->assertEquals(
            '<select name="a" id="a">
<option value="x">option x</option>
<option value="y">option y</option>
<option value="z">option z</option>
</select>
',
            CForm::select('a', 'b', array(
                    'x' => 'option x',
                    'y' => 'option y',
                    'z' => 'option z'
                    )));
        $this->assertEquals(
            '<select name="a" id="a">
<option value="x">option x</option>
<option value="y">option y</option>
<option value="z" selected="selected">option z</option>
</select>
',
            CForm::select('a', 'z', array(
                    'x' => 'option x',
                    'y' => 'option y',
                    'z' => 'option z'
                    )));
    }

    /**
     * @depends testSelect
     */
    public function testSelect_states()
    {
                $this->assertEquals(
                    '<select name="state" id="state">
<option value="" selected="selected">Please select...</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>

',
                    CForm::select_states());
    }

    /**
     * @depends testSelect
     */
    public function testSelect_countries()
    {
        $this->assertEquals(
            '<select name="country" id="country">
<option value="" selected="selected">Please select...</option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua and Barbuda</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option>
<option value="BH">Bahrain</option>
<option value="BD">Bangladesh</option>
<option value="BB">Barbados</option>
<option value="BY">Belarus</option>
<option value="BE">Belgium</option>
<option value="BZ">Belize</option>
<option value="BJ">Benin</option>
<option value="BM">Bermuda</option>
<option value="BT">Bhutan</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet Island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BN">Brunei Darussalam</option>
<option value="BG">Bulgaria</option>
<option value="BF">Burkina Faso</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
<option value="CM">Cameroon</option>
<option value="CA">Canada</option>
<option value="CV">Cape Verde</option>
<option value="KY">Cayman Islands</option>
<option value="CF">Central African Republic</option>
<option value="TD">Chad</option>
<option value="CL">Chile</option>
<option value="CN">China</option>
<option value="CX">Christmas Island</option>
<option value="CC">Cocos (Keeling) Islands</option>
<option value="CO">Colombia</option>
<option value="KM">Comoros</option>
<option value="CG">Congo</option>
<option value="CD">Congo, Democratic Republic of the</option>
<option value="CK">Cook Islands</option>
<option value="CR">Costa Rica</option>
<option value="CI">Cote d\'Ivoire</option>
<option value="HR">Croatia</option>
<option value="CU">Cuba</option>
<option value="CY">Cyprus</option>
<option value="CZ">Czech Republic</option>
<option value="DK">Denmark</option>
<option value="DJ">Djibouti</option>
<option value="DM">Dominica</option>
<option value="DO">Dominican Republic</option>
<option value="TP">East Timor</option>
<option value="EC">Ecuador</option>
<option value="EG">Egypt</option>
<option value="SV">El Salvador</option>
<option value="GQ">Equatorial Guinea</option>
<option value="ER">Eritrea</option>
<option value="EE">Estonia</option>
<option value="ET">Ethiopia</option>
<option value="FK">Falkland Islands (Malvinas)</option>
<option value="FO">Faroe Islands</option>
<option value="FJ">Fiji</option>
<option value="FI">Finland</option>
<option value="FR">France</option>
<option value="GF">French Guiana</option>
<option value="PF">French Polynesia</option>
<option value="TF">French Southern Territories</option>
<option value="GA">Gabon</option>
<option value="GM">Gambia</option>
<option value="GE">Georgia</option>
<option value="DE">Germany</option>
<option value="GH">Ghana</option>
<option value="GI">Gibraltar</option>
<option value="GR">Greece</option>
<option value="GL">Greenland</option>
<option value="GD">Grenada</option>
<option value="GP">Guadeloupe</option>
<option value="GU">Guam</option>
<option value="GT">Guatemala</option>
<option value="GN">Guinea</option>
<option value="GW">Guinea-Bissau</option>
<option value="GY">Guyana</option>
<option value="HT">Haiti</option>
<option value="HM">Heard Island and McDonald Islands</option>
<option value="VA">Holy See (Vatican City)</option>
<option value="HN">Honduras</option>
<option value="HK">Hong Kong</option>
<option value="HU">Hungary</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran, Islamic Republic of</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JO">Jordan</option>
<option value="KZ">Kazakstan</option>
<option value="KE">Kenya</option>
<option value="KI">Kiribati</option>
<option value="KP">Korea, Democratic People\'s Republic of</option>
<option value="KR">Korea, Republic of</option>
<option value="KW">Kuwait</option>
<option value="KG">Kyrgyzstan</option>
<option value="LA">Lao People\'s Democratic Republic</option>
<option value="LV">Latvia</option>
<option value="LB">Lebanon</option>
<option value="LS">Lesotho</option>
<option value="LR">Liberia</option>
<option value="LY">Libyan Arab Jamahiriya</option>
<option value="LI">Liechtenstein</option>
<option value="LT">Lithuania</option>
<option value="LU">Luxembourg</option>
<option value="MO">Macau</option>
<option value="MK">Macedonia, The Former Yugoslav Republic of</option>
<option value="MG">Madagascar</option>
<option value="MW">Malawi</option>
<option value="MY">Malaysia</option>
<option value="MV">Maldives</option>
<option value="ML">Mali</option>
<option value="MT">Malta</option>
<option value="MH">Marshall Islands</option>
<option value="MQ">Martinique</option>
<option value="MR">Mauritania</option>
<option value="MU">Mauritius</option>
<option value="YT">Mayotte</option>
<option value="MX">Mexico</option>
<option value="FM">Micronesia, Federated States of</option>
<option value="MD">Moldova, Republic of</option>
<option value="MC">Monaco</option>
<option value="MN">Mongolia</option>
<option value="MS">Montserrat</option>
<option value="MA">Morocco</option>
<option value="MZ">Mozambique</option>
<option value="MM">Myanmar</option>
<option value="NA">Namibia</option>
<option value="NR">Nauru</option>
<option value="NP">Nepal</option>
<option value="NL">Netherlands</option>
<option value="AN">Netherlands Antilles</option>
<option value="NC">New Caledonia</option>
<option value="NZ">New Zealand</option>
<option value="NI">Nicaragua</option>
<option value="NE">Niger</option>
<option value="NG">Nigeria</option>
<option value="NU">Niue</option>
<option value="NF">Norfolk Island</option>
<option value="MP">Northern Mariana Islands</option>
<option value="NO">Norway</option>
<option value="OM">Oman</option>
<option value="PK">Pakistan</option>
<option value="PW">Palau</option>
<option value="PS">Palestinian Territory, Occupied</option>
<option value="PA">PANAMA</option>
<option value="PG">Papua New Guinea</option>
<option value="PY">Paraguay</option>
<option value="PE">Peru</option>
<option value="PH">Philippines</option>
<option value="PN">Pitcairn</option>
<option value="PL">Poland</option>
<option value="PT">Portugal</option>
<option value="PR">Puerto Rico</option>
<option value="QA">Qatar</option>
<option value="RE">Reunion</option>
<option value="RO">Romania</option>
<option value="RU">Russian Federation</option>
<option value="RW">Rwanda</option>
<option value="SH">Saint Helena</option>
<option value="KN">Saint Kitts and Nevis</option>
<option value="LC">Saint Lucia</option>
<option value="PM">Saint Pierre and Miquelon</option>
<option value="VC">Saint Vincent and the Grenadines</option>
<option value="WS">Samoa</option>
<option value="SM">San Marino</option>
<option value="ST">Sao Tome and Principe</option>
<option value="SA">Saudi Arabia</option>
<option value="SN">Senegal</option>
<option value="SC">Seychelles</option>
<option value="SL">Sierra Leone</option>
<option value="SG">Singapore</option>
<option value="SK">Slovakia</option>
<option value="SI">Slovenia</option>
<option value="SB">Solomon Islands</option>
<option value="SO">Somalia</option>
<option value="ZA">South Africa</option>
<option value="GS">South Georgia and the South Sandwich Islands</option>
<option value="ES">Spain</option>
<option value="LK">Sri Lanka</option>
<option value="SD">Sudan</option>
<option value="SR">Suriname</option>
<option value="SJ">Svalbard and Jan Mayen</option>
<option value="SZ">Swaziland</option>
<option value="SE">Sweden</option>
<option value="CH">Switzerland</option>
<option value="SY">Syrian Arab Republic</option>
<option value="TW">Taiwan, Province of China</option>
<option value="TJ">Tajikistan</option>
<option value="TZ">Tanzania, United Republic of</option>
<option value="TH">Thailand</option>
<option value="TG">Togo</option>
<option value="TK">Tokelau</option>
<option value="TO">Tonga</option>
<option value="TT">Trinidad and Tobago</option>
<option value="TN">Tunisia</option>
<option value="TR">Turkey</option>
<option value="TM">Turkmenistan</option>
<option value="TC">Turks and Caicos Islands</option>
<option value="TV">Tuvalu</option>
<option value="UG">Uganda</option>
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US">United States</option>
<option value="UM">United States Minor Outlying Islands</option>
<option value="UY">Uruguay</option>
<option value="UZ">Uzbekistan</option>
<option value="VU">Vanuatu</option>
<option value="VE">Venezuela</option>
<option value="VN">Viet Nam</option>
<option value="VG">Virgin Islands, British</option>
<option value="VI">Virgin Islands, U.S.</option>
<option value="WF">Wallis and Futuna</option>
<option value="EH">Western Sahara</option>
<option value="YE">Yemen</option>
<option value="YU">Yugoslavia</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
',
            CForm::select_countries());
    }

    /**
     * @depends testSelect
     */
    public function testSelect_redirect()
    {
        $this->assertEquals(
            '<select name="shortcut" id="shortcut" onchange="location.href=this.options[this.selectedIndex].value;">
<option value="http://apple.com">Apple</option>
<option value="https://google.com">Google</option>
</select>
',
            CForm::select_redirect(
                'shortcut',
                array(
                    'http://apple.com' => 'Apple',
                    'https://google.com' => 'Google'
                    )
                ));
    }

    /**
     * @todo Implement testDate_select().
     */
    public function testDate_select()
    {
        $this->assertEquals(
            $this->date_select,
            CForm::date_select(
                'date',
                date('Y').'-01-01'
                ));
    }

    /**
     * @depends testSelect
     */
    public function testTime_select()
    {

        $this->assertEquals($this->time_select, CForm::time_select('date', '2010-01-01 18:30:00'));
        $this->assertEquals($this->time_select, CForm::time_select('date', '18:30'));
        $this->assertEquals($this->time_select, CForm::time_select('date', '6:30 pm'));
        $this->assertEquals($this->time_select, CForm::time_select('date', '01-01-01 6:30 pm'));
        $this->assertEquals($this->time_select, CForm::time_select('date', array(
            'hour' => '18',
            'minute' => '30'
            )));
    }

    /**
     * @depends testSelect
     */
    public function testDate_time_select()
    {
        $this->assertEquals($this->date_select.' @ '.$this->time_select, CForm::date_time_select('date', date('Y').'-01-01 18:30:00'));
    }

    public function testGet_timestamp_from_post()
    {
        $key = 'date';
        $_POST[$key]['month'] = 6;
        $_POST[$key]['day'] = 22;
        $_POST[$key]['year'] = 2001;
        $_POST[$key]['hour'] = 11;
        $_POST[$key]['minute'] = 30;
        $_POST[$key]['ampm'] = 'pm';
        $this->assertEquals(993277800, CForm::get_timestamp_from_post($key));
    }

    /**
     * @depends testSelect
     */
    public function testGet_timestamp_from_array()
    {
        $key = 'date';
        $_POST[$key]['month'] = 6;
        $_POST[$key]['day'] = 22;
        $_POST[$key]['year'] = 2001;
        $_POST[$key]['hour'] = 11;
        $_POST[$key]['minute'] = 30;
        $_POST[$key]['ampm'] = 'pm';
        $this->assertEquals(993277800, CForm::get_timestamp_from_array($_POST[$key]));
    }

    /**
     * @depends testSelect
     */
    public function testSelect_time_zone()
    {
        $t = '<select name="a" id="a">
<option value="" selected="selected">Please select...</option>
<option value="US & Canada">US/Pacific</option>
<option value="-10:00 Hawaii">US/Hawaii</option>
<option value="-09:00 Alaska">US/Alaska</option>
<option value="-08:00 Pacific Time">US/Pacific</option>
<option value="-08:00 Pacific Time (Yukon)">Canada/Yukon</option>
<option value="-07:00 Arizona">US/Arizona</option>
<option value="-07:00 Mountain Time">US/Mountain</option>
<option value="-06:00 Central Time">US/Central</option>
<option value="-06:00 Saskatchewan">Canada/Saskatchewan</option>
<option value="-06:00 Saskatchewan (East)">Canada/East-Saskatchewan</option>
<option value="-05:00 Eastern Time">US/Eastern</option>
<option value="-05:00 Eastern Time (Michigan)">US/Michigan</option>
<option value="-05:00 Indiana (East)">US/East-Indiana</option>
<option value="-05:00 Indiana (Starke)">US/Indiana-Starke</option>
<option value="-04:00 Atlantic Time (Canada)">Canada/Atlantic</option>
<option value="-03:30 Newfoundland">Canada/Newfoundland</option>
<option value="International">GMT</option>
<option value="-12:00 Eniwetok, Kwajalein">Pacific/Kwajalein</option>
<option value="-11:00 Midway Island, Samoa">US/Samoa</option>
<option value="-06:00 Central America">Etc/GMT-6</option>
<option value="-06:00 Mexico City">America/Mexico_City</option>
<option value="-05:00 Bogota, Lima, Quito">America/Bogota</option>
<option value="-04:00 Caracas, La Paz">America/Caracas</option>
<option value="-04:00 Santiago">America/Santiago</option>
<option value="-03:00 Brasilia">Brazil/West</option>
<option value="-03:00 Greenland">Etc/GMT-3</option>
<option value="-02:00 Mid-Atlantic">Etc/GMT-2</option>
<option value="-01:00 Azores">Atlantic/Azores</option>
<option value="-01:00 Cape Verde Is.">Atlantic/Cape_Verde</option>
<option value="GMT Casablanca, Monrovia">Africa/Casablanca</option>
<option value="Greenwich Mean Time GMT: Dublin, Edinburgh, Lisbon, London">GMT</option>
<option value="+01:00 Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna">Etc/GMT+1</option>
<option value="+01:00 Belgrade, Bratislava, Budapest, Ljubljana, Prague">Etc/GMT+1</option>
<option value="+01:00 Brussels, Copenhagen, Madrid, Paris">Etc/GMT+1</option>
<option value="+01:00 Sarajevo, Skopje, Sofija, Vilnius, Warsaw, Zagreb">Etc/GMT+1</option>
<option value="+01:00 West Central Africa">Etc/GMT+1</option>
<option value="+02:00 Athens, Istanbul, Minsk">Etc/GMT+2</option>
<option value="+02:00 Bucharest">Etc/GMT+2</option>
<option value="+02:00 Cairo">Etc/GMT+2</option>
<option value="+02:00 Harare, Pretoria">Etc/GMT+2</option>
<option value="+02:00 Helsinki, Riga, Tallinn">Etc/GMT+2</option>
<option value="+02:00 Jerusalem">Etc/GMT+2</option>
<option value="+03:00 Baghdad">Etc/GMT+3</option>
<option value="+03:00 Kuwait, Riyadh">Etc/GMT+3</option>
<option value="+03:00 Moscow, St. Petersburg, Volgograd">Etc/GMT+3</option>
<option value="+03:00 Nairobi">Etc/GMT+3</option>
<option value="+03:30 Tehran">Etc/GMT+3</option>
<option value="+04:00 Abu Dhabi, Muscat">Etc/GMT+4</option>
<option value="+04:00 Baku, bilisi, erevan">Etc/GMT+4</option>
<option value="+04:30 Kabul">Asia/Kabul</option>
<option value="+05:00 Ekaterinburg">Etc/GMT+5</option>
<option value="+05:00Islamabad, Karachi, Tashkent">Etc/GMT+5</option>
<option value="+05:30 Calcutta, Chennai, Mumbai, New Delhi">Asia/Calcutta</option>
<option value="+05:45 Kathmandu">Asia/Katmandu</option>
<option value="+06:00 Almatay, Novosibirsk">Etc/GMT+6</option>
<option value="+06:00 Astana, Dhaki">Etc/GMT+6</option>
<option value="+06:00 Sri Jayawardenepura">Etc/GMT+6</option>
<option value="+06:30 Rangoon">Asia/Rangoon</option>
<option value="+07:00 Bangkok, Hanoi, Jakarta">Etc/GMT+7</option>
<option value="+07:00 Krasnoyarsk">Etc/GMT+7</option>
<option value="+08:00Beijing, Chongqing, Hong Kong, Urumqi">Etc/GMT+8</option>
<option value="+08:00 Irkutsk, Ulaan Bataar">Etc/GMT+8</option>
<option value="+08:00 Kuala Lumpur, Singapore">Etc/GMT+8</option>
<option value="+08:00 Perth">Etc/GMT+8</option>
<option value="+08:00Taipei">Etc/GMT+8</option>
<option value="+09:00 Osaka, Sapporo, Tokyo">Etc/GMT+9</option>
<option value="+09:00 Seoul">Etc/GMT+9</option>
<option value="+09:00 Yakutsk">Etc/GMT+9</option>
<option value="+09:30 Adelaide">Etc/GMT+9</option>
<option value="+09:30 Darwin">Australia/Darwin</option>
<option value="+10:00 Brisbane">Etc/GMT+10</option>
<option value="+10:00 Canberra, Melbourne, Sydney">Etc/GMT+10</option>
<option value="+10:00 Guam, Port Moresby">Etc/GMT+10</option>
<option value="+10:00 Hobart">Etc/GMT+10</option>
<option value="+10:00 Vladivostok">Etc/GMT+10</option>
<option value="+11:00 Magadan, Solomon Is., New Caledonia">Etc/GMT+11</option>
<option value="+12:00 Auckland, ellington">Etc/GMT+12</option>
<option value="+12:00 Fiji, Kamchatka, Marshall Is.">Etc/GMT+12</option>
</select>
';
        $this->assertEquals($t, CForm::select_time_zone('a'));
    }

    public function testCheckbox_select()
    {
        $ops = array(
            'w' => 'Apple',
            'x' => 'Microsoft',
            'y' => 'Yahoo!',
            'z' => 'Google',
            );
        $t  = '<divclass="checks-css">

<input type="checkbox" id="a_w" name="a" value="w" checked="checked" /> Apple

<input type="checkbox" id="a_x" name="a" value="x" /> Microsoft

<input type="checkbox" id="a_y" name="a" value="y" checked="checked" /> Yahoo!

<input type="checkbox" id="a_z" name="a" value="z" /> Google

';
        $this->assertEquals($t, CForm::checkbox_select('a', array('w','y'), $ops, array('class' => 'checks-css')));
    }

    /**
     * @todo Implement testRadio_select().
     */
    public function testRadio_select()
    {
        $ops = array(
            'w' => 'Apple',
            'x' => 'Microsoft',
            'y' => 'Yahoo!',
            'z' => 'Google',
            );
        $t  = '<divclass="checks-css">

<input type="radio" id="a_w" name="a" value="w" checked="checked" /> Apple

<input type="radio" id="a_x" name="a" value="x" /> Microsoft

<input type="radio" id="a_y" name="a" value="y" /> Yahoo!

<input type="radio" id="a_z" name="a" value="z" /> Google

';
        $this->assertEquals($t, CForm::radio_select('a', array('w'), $ops, array('class' => 'checks-css')));

    }
}
?>


text:
ACCEPTED

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

#### Published in
Flora, Jena 57: (1874)

#### Original name
Ptychographa xylographoides Nyl.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
extern void CallApplication(void);

void HandleUpdate() {
	ConfigureDevice();
	Updater();
}

void main(void) {
	if(CheckForceUpdate()) {
		HandleUpdate();
	} else {
		CallApplication();
	}
}


text:
module InyxEmployeesRails
  class Engine < ::Rails::Engine
    isolate_namespace InyxEmployeesRails
  end
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/secrets/v1beta1/service.proto

package com.google.cloud.secretmanager.v1beta1;

public interface AccessSecretVersionResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.secrets.v1beta1.AccessSecretVersionResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The resource name of the [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in the format
   * `projects/*/secrets/*/versions/*`.
   *

   *
   * string name = 1 [(.google.api.resource_reference) = { ... }
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * The resource name of the [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in the format
   * `projects/*/secrets/*/versions/*`.
   *

   *
   * string name = 1 [(.google.api.resource_reference) = { ... }
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * Secret payload
   *

   *
   * .google.cloud.secrets.v1beta1.SecretPayload payload = 2;
   *
   * @return Whether the payload field is set.
   */
  boolean hasPayload();
  /**
   *
   *
   *

   * Secret payload
   *

   *
   * .google.cloud.secrets.v1beta1.SecretPayload payload = 2;
   *
   * @return The payload.
   */
  com.google.cloud.secretmanager.v1beta1.SecretPayload getPayload();
  /**
   *
   *
   *

   * Secret payload
   *

   *
   * .google.cloud.secrets.v1beta1.SecretPayload payload = 2;
   */
  com.google.cloud.secretmanager.v1beta1.SecretPayloadOrBuilder getPayloadOrBuilder();
}


text:
This is docker file that provides environment for someone who want to visualize network with Cytoscape or who want to try some workflow example in this repository. You can build environment quickly by this.

## What will this Give you?

This directory is sharing typical Dockerfile to visualize network data for R and Python users.
So, you can build environment by using Dockerfile and execute any RCy3/py2cytoscape cookbook's code and Realistica workflow code in this repository.

# Prerequisites

To use this docker and get environment to visualize networks by Cytoscape, please prepare the following software or packages.

- Java SE 8. Cytoscape 3.3 and CyREST currently do not support Java SE 6 or 7 anymore. Java SE 7 works only in combination with Cytoscape 3.2. Java can be can downloaded from Oracle here: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
- Cytoscape version 3.3+, which can be downloaded from http://www.cytoscape.org/download.php.
- CyREST, version 3.0.0 or later, a Cytoscape plugin which provides the Cytoscape end of the communication layer, can be installed via the App Manager or downloaded from the Cytoscape plugins website: http://apps.cytoscape.org/apps/cyrest.

# What this Gives you?

This gives you the following things.

- The environment for data visualization with Cytoscape/jupyter-notebook/RCy3/py2cytoscape.
- The packages that we use often in Data visualization with R and Python: Jupyter Notebook/Igraph/RCy3/graph-tools/igraph/networkx/pandas/numpy/scipy/jupyter notebook/py2cytoscape
- You can execute or try any examples of workflow in this repository.

## More about RCy3/py2cytoscape
If you want to know more about RCy3 and py2cytoscape, you can read the document and reference of RCy3/py2cytocape in bioconductor.
- RCy3
  - [Document](https://www.bioconductor.org/packages/release/bioc/vignettes/RCy3/inst/doc/RCy3.pdf)
  - [Reference](https://www.bioconductor.org/packages/release/bioc/manuals/RCy3/man/RCy3.pdf)
- py2cytoscape
  - [github repository](https://github.com/idekerlab/py2cytoscape)

# Getting Started

Please do the following steps to get started.

1. Install 'Docker for Mac/Windows' in your personal computer(You can skip this step if you already use docker in your computer)
1. Download or clone this directory.
1. Launch docker.
1. Build and run Dockerfile in your computer.
  1. Open a command-line terminal, and go to the directory where you downloaded this repository.
  1. Try ``` docker build -t cyrest/examples . ``` on command-line.
  1. When the building docker image finished, please type ``` docker run -d -p 8888:8888 -v /Your/work/space/path:/home/jovyan/work cyrest/examples```. If you set our workflow directory as your work space path, you can try our workflow.
1. Now, you can use jupyter-notebook and try the workflow or something!!

If you don't know much about docker or this is the first time to use docker, it is helpful to read following message.

# What is docker?

Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. By doing so, thanks to the container, the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code.

## More about Docker
- Docker Home page : https://www.docker.com
- What is docker : https://www.docker.com/what-docker

# The docker installation

## Mac
If you are Mac user, please try the following steps.

1. First, please access this url. https://www.docker.com/products/docker#/mac
1. Then, please download and install docker for mac in this page.

More information : https://docs.docker.com/docker-for-mac/

## Windows
If you are Windows user, please try the following steps.

1. First, please access this url. https://www.docker.com/products/docker#/windows
1. Then, please download and install docker for windows in this page.

More information : https://docs.docker.com/docker-for-windows/

## To verify your installation, let's "Hello world!".

1. Open a command-line terminal, and run some Docker commands to verify that Docker is working as expected.
Some good commands to try are docker version to check that you have the latest release installed and docker ps to see if you have any running containers. (Probably not, since you just started.)
1. Type the ```docker run hello-world``` command and press RETURN. The command does some work for you, if everything runs well, the command's output looks like this:
```
Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker Hub account:
 https://hub.docker.com

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/
```

# How to run Image?

The way of usage is the same as Jupyter Notebook Data Science Stack. So, if you want to know more about usage, please check the page : https://github.com/jupyter/docker-stacks/tree/master/datascience-notebook.

I will show you the usage shortly.

## Basic usage

The following command starts a container with the Notebook server listening for HTTP connections on port 8888 without authentication configured.

```
docker run -d -p 8888:8888 yourDockerImageName
```

Then, you can execute python code and use any packages included in this docker file on jupyter-notebook.

## Advanced usage

If you want to use this docker file with some option, please check this page.
https://github.com/jupyter/docker-stacks/tree/master/datascience-notebook

## What is Docker?

Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. By doing so, thanks to the container, the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code.

## More about Docker
- Docker Home page : https://www.docker.com
- What is docker : https://www.docker.com/what-docker


text:
package eu.neclab.iotplatform.ngsi.api.datamodel;

/*******************************************************************************
 *   Copyright (c) 2015, NEC Europe Ltd.
 *   All rights reserved.
 *
 *   Authors:
 *           * Salvatore Longo - salvatore.longo@neclab.eu
 *           * Tobias Jacobs - tobias.jacobs@neclab.eu
 *           * Flavio Cirillo - flavio.cirillo@neclab.eu
 *           * Raihan Ul-Islam
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *   1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   3. All advertising materials mentioning features or use of this software
 *     must display the following acknowledgment:
 *     This product includes software developed by NEC Europe Ltd.
 *   4. Neither the name of NEC nor the names of its contributors may be used
 *   to endorse or promote products derived from this software without specific
 *   prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY NEC ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NEC BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Implements AppendContextAttributeRequest
 * as defined in the FI-WARE binding of NGSI 9/10.
 *
 */
@XmlRootElement(name = "appendContextAttributeRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class AppendContextAttributeRequest extends NgsiStructure {

	@XmlElement(name = "contextValue", required = true)
	private String contextValue = null;

	@XmlElementWrapper(name = "metadata")
	@XmlElement(name = "contextMetadata", required = false)
	private List<ContextMetadata> contextMetadata;

	public AppendContextAttributeRequest() {

	}

	public AppendContextAttributeRequest(String contextValue,
			List<ContextMetadata> metadata) {
		super();
		this.contextValue = contextValue;
		contextMetadata = metadata;
	}

	public String getContextValue() {
		return contextValue;
	}

	public void setContextValue(String contextValue) {
		this.contextValue = contextValue;
	}

	public List<ContextMetadata> getMetadata() {
		if (contextMetadata == null) {
			contextMetadata = new ArrayList<ContextMetadata>();
		}
		return contextMetadata;
	}

	public void setMetadata(List<ContextMetadata> metadata) {
		contextMetadata = metadata;
	}

}


text:
import sys
import pickle

from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
from tester import test_classifier

from sklearn.feature_selection import SelectKBest

from sklearn.preprocessing import MinMaxScaler

from sklearn.grid_search import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier

from sklearn.metrics import f1_score
from sklearn.metrics import make_scorer

def get_data(create_feature = True):
    with open("final_project_dataset.pkl", "r") as data_file:
        data_dict = pickle.load(data_file)

    # Remove outliers
    data_dict.pop('TOTAL', 0)
    data_dict.pop('THE TRAVEL AGENCY IN THE PARK', 0)

    # Create new features
    if create_feature:
        create_new_features(data_dict)

    return data_dict

def check_feature_poi_ratio(data, feature):
    count_val = 0
    count_val_NaN = 0
    count_poi = 0
    count_poi_NaN = 0

    for k in data:
        poi = data[k]['poi']
        val = data[k][feature]
        if val != 'NaN':
            count_val += 1
            if poi:
                count_poi += 1
        else:
            count_val_NaN += 1
            if poi:
                count_poi_NaN += 1

    print "Feature [%s]:\n\t non-NaN count = %d (with %d POI), NaN count = %d (with %d POI)" % \
        (feature, count_val, count_poi, count_val_NaN, count_poi_NaN)

def get_full_feature_list():
    features = ['poi', 'to_messages', 'deferral_payments', 'expenses', 'deferred_income', \
        'from_poi_to_this_person', 'restricted_stock_deferred', 'shared_receipt_with_poi', \
        'loan_advances', 'from_messages', 'other', 'director_fees', 'bonus', 'total_stock_value', \
        'from_this_person_to_poi', 'long_term_incentive', 'restricted_stock', 'salary', \
        'total_payments', 'exercised_stock_options']
    return features

def get_feature_list():
    features = ['poi','major_payment', 'exercised_stock_options', 'bonus', 'salary', \
        'deferred_income', 'long_term_incentive', 'restricted_stock', \
        'shared_receipt_with_poi', 'loan_advances', 'poi_message_ratio', \
        'director_fees', 'deferral_payments', 'restricted_stock_deferred']
    return features

def get_features_and_labels(dataset, features_list):
    data = featureFormat(dataset, features_list)
    labels, features = targetFeatureSplit(data)

    return data, labels, features

def get_feature_scores(dataset, features_list):
    data,labels,features = get_features_and_labels(dataset, features_list)

    k = len(features_list) - 1
    kbest = SelectKBest(k=k)
    kbest.fit(features, labels)

    # exclude the first poi feature from the feature list
    pairs = zip(features_list[1:], kbest.scores_)
    pairs = list(reversed(sorted(pairs, key = lambda x:x[1])))
    for t in pairs:
        print t[0], ": ", t[1]
    tmp_list,score_list = zip(*pairs)
    return tmp_list[0:k]

def create_new_features(dataset):
    for key in dataset.keys():
        # Create new feature 'poi_message_ratio'
        from_messages = dataset[key]['from_messages']
        to_messages = dataset[key]['to_messages']
        from_poi_messages = dataset[key]['from_poi_to_this_person']
        to_poi_messages = dataset[key]['from_this_person_to_poi']

        from_messages = from_messages if from_messages != 'NaN' else 0
        to_messages = to_messages if to_messages != 'NaN' else 0
        from_poi_messages = from_poi_messages if from_poi_messages != 'NaN' else 0
        to_poi_messages = to_poi_messages if to_poi_messages != 'NaN' else 0

        total_messages = from_messages + to_messages
        if total_messages > 0:
            dataset[key]['poi_message_ratio'] = \
                .1*(from_poi_messages + to_poi_messages)/total_messages
        else:
            dataset[key]['poi_message_ratio'] = 0.0

        # Create feature 'major_payment'
        features_to_sum = ['salary', 'bonus', 'exercised_stock_options']
        sum = 0.0
        for f in features_to_sum:
            if (dataset[key][f] != 'NaN'):
                sum = sum + dataset[key][f]
        dataset[key]['major_payment'] = sum

def tune_classifier(classifier, clf_params, max_features):
    ### features_list is a list of strings, each of which is a feature name.
    ### The first feature must be "poi".
    features_list = get_feature_list()

    ### Create new feature(s)
    ### Store to my_dataset for easy export below.
    my_dataset = get_data()

    ### Extract features and labels from dataset for local testing
    features_list = features_list[0:max_features+1]
    data, labels, features = get_features_and_labels(my_dataset, features_list)

    ### Tune your classifier to achieve better than .3 precision and recall
    ### using our testing script. Check the tester.py script in the final project
    ### folder for details on the evaluation method, especially the test_classifier
    ### function. Because of the small size of the dataset, the script uses
    ### stratified shuffle split cross validation. For more info:
    ### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html

    from sklearn.cross_validation import train_test_split
    features_train, features_test, labels_train, labels_test = \
        train_test_split(features, labels, test_size=0.3, random_state=42)

    # Testing
    clf = GridSearchCV(classifier, param_grid=clf_params, scoring=make_scorer(f1_score))
    clf.fit(features_train, labels_train)
    clf_final = clf.best_estimator_
    print "The best estimator = ", clf_final
    test_classifier(clf_final, my_dataset, features_list, 1000)

def explore_data():
    print "=================================="
    print "Explore the dataset"
    print "=================================="
    data = get_data(False)

    ## Data Exploration part
    print "Size of dataset =", len(data)
    n_poi = 0
    for k in data:
        if data[k]['poi'] == True:
            n_poi = n_poi + 1
    print "# of POI =", n_poi
    print "# of non-POI =", len(data) - n_poi
    print "# of features =", len(data.values()[0])

    count = {}
    for k in data.values()[0]:
        count[k] = 0

    for k in data:
        d = data[k]
        for name in d:
            if isinstance(d[name], int) and d[name] > 0:
                count[name] = count[name] + 1
            else:
                if d[name] != '' and d[name] != 'NaN':
                    count[name] = count[name] + 1

    print "The counts of non-empty features are:", count

def check_all_features():
    print "========================================="
    print "Check NaN and POI counts for all features"
    print "========================================="
    data = get_data(False)
    for feature in data.values()[0]:
        if feature not in ['poi', 'email_address']:
            check_feature_poi_ratio(data, feature)

def select_features():
    print "=================================="
    print "Find the univariate feature scores"
    print "=================================="
    my_dataset = get_data()
    features_list = get_full_feature_list()
    get_feature_scores(my_dataset, features_list)

    print "=================================="
    print "Find the target feature scores"
    print "=================================="
    features_list = get_feature_list()
    get_feature_scores(my_dataset, features_list)

def tune_algorithm():
    print "=================================="
    print "Tune the Decision Tree classifier"
    print "=================================="
    classifier = DecisionTreeClassifier(random_state=42)
    clf_params = dict(min_samples_split=range(2,10))
    for n in range(1, 14):
        print "Tune algorithm for {0} features:".format(n)
        tune_classifier(classifier, clf_params, n)

    print "=================================="
    print "Tune the AdaBoost classifier"
    print "=================================="
    classifier = AdaBoostClassifier(random_state=42)
    clf_params = dict(n_estimators=[10,20,30,40,50,60,70])
    for n in range(1, 14):
        print "Tune algorithm for {0} features:".format(n)
        tune_classifier(classifier, clf_params, n)

def main():
    explore_data()
    check_all_features()
    select_features()
    tune_algorithm()


text:
class RafsController < ApplicationController

	class Under15InconsistencyFound < StandardError; end

	before_filter :may_create_study_subjects_required,
		:only => [:new,:create,:show]
	before_filter :may_update_study_subjects_required,
		:only => [:edit,:update]
	before_filter :may_destroy_study_subjects_required,
		:only => :destroy

	before_filter :valid_id_required,
		:only => [:edit,:update,:show,:destroy]
	before_filter :case_study_subject_required,
		:only => [:edit,:update,:show,:destroy]

	def new
		@study_subject = StudySubject.new
	end

	def create

		params[:study_subject][:addresses_attributes] ||= {}
		params[:study_subject][:addresses_attributes]['0'] ||= {}
		allow_blank_address_line_1_for(
			params[:study_subject][:addresses_attributes]['0'])

		mark_as_eligible(params[:study_subject])
		@study_subject = StudySubject.new(study_subject_params)

		warn = []

		check_was_under_15(@study_subject)

		#	protected attributes
		@study_subject.subject_type   = 'Case'
		@study_subject.case_control_type = 'C'

		#	explicitly validate before searching for duplicates
		raise ActiveRecord::RecordInvalid.new(@study_subject) unless @study_subject.valid?

		#	regular create submit	#	tests DO NOT SEND params[:commit] = 'Submit'
		if params[:commit].blank? or params[:commit] == 'New Case'
			@duplicates = @study_subject.duplicates
			raise StudySubject::DuplicatesFound unless @duplicates.empty?
		end

		if params[:commit] == 'Match Found'
			@duplicates = @study_subject.duplicates
			if params[:duplicate_id] and
					( duplicate = StudySubject.find_by_id(params[:duplicate_id]) ) and
					@duplicates.include?(duplicate)
				duplicate.raf_duplicate_creation_attempted(@study_subject)
				flash[:notice] = "Operational Event created marking this attempted entry."
				redirect_to duplicate
			else
				#
				#	Match Found, but no duplicate_id or subject with the id
				#
				warn << "No valid duplicate_id given"
				raise StudySubject::DuplicatesFound unless @duplicates.empty?
			end

		#	params[:commit].blank? or params[:commit] == 'New Case'
		#		or params[:commit] == 'No Match'
		else
			#	No duplicates found or if there were, not matches.
			#	Transactions are only for marking a rollback point.
			#	The raised error will still kick all the way out.
			StudySubject.transaction do
				@study_subject.save!
				@study_subject.assign_icf_master_id
				@study_subject.create_mother
			end

			if @study_subject.icf_master_id.blank?
				warn << "Case was not assigned an icf_master_id."
			end
			if @study_subject.mother.try(:icf_master_id).blank?
				warn << "Mother was not assigned an icf_master_id."
			end
			flash[:warn] = warn.join('
') unless warn.empty?
			redirect_to @study_subject
			Notification.raf_submitted(@study_subject).deliver_now
		end
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "StudySubject creation failed"
		render :action => 'new'
	rescue ActiveRecord::StatementInvalid => e
		flash.now[:error] = "Database error.  Check production logs and contact Jake."
		render :action => 'new'
	rescue StudySubject::DuplicatesFound
		flash.now[:error] = "Possible Duplicate(s) Found."
		flash.now[:warn] = warn.join('
') unless warn.empty?
		render :action => 'new'
	rescue Under15InconsistencyFound
		flash.now[:error] = "Under 15 Inconsistency Found."
		flash.now[:warn]  = "Under 15 selection does not match computed value."
		render :action => 'new'
	end

	def edit
	end

	def update

		params[:study_subject] ||= {}
		params[:study_subject][:addresses_attributes] ||= {}
		params[:study_subject][:addresses_attributes]['0'] ||= {}
		allow_blank_address_line_1_for(
			params[:study_subject][:addresses_attributes]['0'])

		mark_as_eligible(params[:study_subject])
		@study_subject.assign_attributes(study_subject_params)
		check_was_under_15(@study_subject)
		@study_subject.save!
		flash[:notice] = "Subject successfully updated."
		redirect_to raf_path(@study_subject)
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "StudySubject updation failed"
		render :action => 'edit'
	rescue Under15InconsistencyFound
		flash.now[:error] = "Under 15 Inconsistency Found."
		flash.now[:warn]  = "Under 15 selection does not match computed value."
		render :action => 'edit'
	end

	def show
	end

protected

	def valid_id_required
		if !params[:id].blank? and StudySubject.exists?(params[:id])
			@study_subject = StudySubject.find(params[:id])
		else
			access_denied("Valid study_subject id required!", root_path)
		end
	end

	def case_study_subject_required
		unless @study_subject.is_case?
			access_denied("Valid case study_subject required!", @study_subject)
		end
	end

	#	CAUTION: params come from forms as strings
	#	In testing, don't have to pass the patient and language stuff
	#		so will kinda incorrectly be marked as eligible. (not in production though)
	#	or the enrollments stuff
	def mark_as_eligible(default={})
		is_eligible = YNDK[:yes]
		ineligible_reasons = []

		#	in reality, it will as it will be on the form
		#	in testing, it may not for the tests that don't care
		if default.has_key?('enrollments_attributes') and
			default['enrollments_attributes'].is_a?(Hash) and
			default['enrollments_attributes'].has_key?('0') and
			default['enrollments_attributes']['0'].is_a?(Hash)

			if( default['patient_attributes'].is_a?(Hash) and
				default['patient_attributes'][
					'was_under_15_at_dx'].to_s == YNDK[:no].to_s )
				is_eligible = YNDK[:no]
				ineligible_reasons << "Was not under 15 at diagnosis."
			end
			if( default['patient_attributes'].is_a?(Hash) and
				default['patient_attributes'][
					'was_previously_treated'].to_s == YNDK[:yes].to_s )
				is_eligible = YNDK[:no]
				ineligible_reasons << "Was previously treated."
			end
			if( default['patient_attributes'].is_a?(Hash) and
				default['patient_attributes'][
					'was_ca_resident_at_diagnosis'].to_s == YNDK[:no].to_s )
				is_eligible = YNDK[:no]
				ineligible_reasons << "Was not CA resident at diagnosis."
			end
			if( default['subject_languages_attributes'].is_a?(Hash) and
					default['subject_languages_attributes']['0'].is_a?(Hash) and
					default['subject_languages_attributes']['0']['language_code'].to_s.blank? and
					default['subject_languages_attributes']['1'].is_a?(Hash) and
					default['subject_languages_attributes']['1']['language_code'].to_s.blank? )
#
#	NOTE I don't like this.  Should collect all the language codes
#		and see if it actually includes English or Spanish rather than
#		assuming, even though it is programmed this way
#
				is_eligible = YNDK[:no]
				ineligible_reasons << "Language does not include English or Spanish."
			end

			default['enrollments_attributes']['0']['is_eligible'] = is_eligible
			if( is_eligible == YNDK[:no] )
				default['enrollments_attributes']['0'][
					'ineligible_reason_id'] = IneligibleReason['other'].id
				default['enrollments_attributes']['0'][
					'other_ineligible_reason'] = ineligible_reasons.join("\n")
			else	#	must blank these out if now eligible
				default['enrollments_attributes']['0'][
					'ineligible_reason_id'] = nil
				default['enrollments_attributes']['0'][
					'other_ineligible_reason'] = nil
			end
		end
	end

	def allow_blank_address_line_1_for(address)
		if address['line_1'].blank? and
				!address['city'].blank? and
				!address['state'].blank? and
				!address['zip'].blank?
			#	On validation failure, this will be visible on the re-rendered view.
			address['line_1'] = '[no address provided]'
		end
	end

	def check_was_under_15(study_subject)
		if( !study_subject.dob.blank? and
				!study_subject.patient.nil? and
				!study_subject.patient.was_under_15_at_dx.blank? and
				!study_subject.patient.admit_date.blank? )
			fifteenth_birthday = study_subject.dob.to_date + 15.years
			calc_was_under_15 = (
				study_subject.patient.admit_date.to_date < fifteenth_birthday ) ?
					YNDK[:yes] : YNDK[:no]
			#	this will also be triggered if the dates are reverse (admit before dob)
			if calc_was_under_15 != study_subject.patient.was_under_15_at_dx
				raise Under15InconsistencyFound
			end
		end
	end

	def study_subject_params
		params.require( :study_subject ).permit(
			:first_name, :middle_name, :last_name, :dob, :sex,
			:mother_first_name, :mother_middle_name, :mother_last_name, :mother_maiden_name,
			:father_first_name, :father_middle_name, :father_last_name,
			:guardian_first_name, :guardian_middle_name, :guardian_last_name,
			:guardian_relationship, :other_guardian_relationship, {
			:phone_numbers_attributes => [
				:id,:phone_number,:phone_type,:data_source,:is_primary,:current_phone],
			:addresses_attributes => [
				:id,:line_1,:unit,:city,:state,:zip,:data_source,:county,
				:current_address,:address_at_diagnosis,:address_type],
			:enrollments_attributes => [
				:id,:project_id,:consented,:consented_on,:refused_by_family,
				:refused_by_physician,:other_refusal_reason,:refusal_reason_id,
				:is_eligible,:ineligible_reason_id,:other_ineligible_reason],
			:patient_attributes => [
				:id,:organization_id,:admitting_oncologist,:hospital_no,:admit_date,
				:diagnosis,:other_diagnosis,:raf_county,:raf_zip,:was_under_15_at_dx,
				:was_previously_treated,:was_ca_resident_at_diagnosis],
			:subject_languages_attributes => [ :id,:language_code,:other_language]
		} )
	end

end


text:
from atom.api import Int

from enaml.widgets.bounded_date import ProxyBoundedDate

from .qt_control import QtControl

# cyclic notification guard flags
CHANGED_GUARD = 0x1

class QtBoundedDate(QtControl, ProxyBoundedDate):
    """ A base class for implementing Qt Enaml date widgets.

    """
    #: Cyclic notification guard. This a bitfield of multiple guards.
    _guard = Int(0)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Implement in a subclass to create the date widget.

        """
        raise NotImplementedError

    def init_widget(self):
        """ Initialize the date widget.

        """
        super(QtBoundedDate, self).init_widget()
        d = self.declaration
        self.set_minimum(d.minimum)
        self.set_maximum(d.maximum)
        self.set_date(d.date)

    #--------------------------------------------------------------------------
    # Signal Handlers
    #--------------------------------------------------------------------------
    def on_date_changed(self):
        """ A signal handler for the date changed signal.

        """
        if not self._guard & CHANGED_GUARD:
            self.declaration.date = self.get_date()

    #--------------------------------------------------------------------------
    # Abstract Methods and ProxyBoundedDate API
    #--------------------------------------------------------------------------
    def get_date(self):
        """ Return the current date in the control.

        Returns
        -------
        result : date
            The current control date as a date object.

        """
        raise NotImplementedError

    def set_minimum(self, date):
        """ Set the widget's minimum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the minimum date.

        """
        raise NotImplementedError

    def set_maximum(self, date):
        """ Set the widget's maximum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the maximum date.

        """
        raise NotImplementedError

    def set_date(self, date):
        """ Set the widget's current date.

        Parameters
        ----------
        date : date
            The date object to use for setting the date.

        """
        raise NotImplementedError


text:
package com.sortedunderbelly.motomileage.storage;

import com.sortedunderbelly.motomileage.MainActivity;
import com.sortedunderbelly.motomileage.ReminderSchedule;
import com.sortedunderbelly.motomileage.ReminderType;
import com.sortedunderbelly.motomileage.Trip;
import com.sortedunderbelly.motomileage.TripFilter;

import java.util.List;
import java.util.Set;

/**
 * Created by max.ross on 5/10/14.
 */
public interface TripStorage {
    Trip save(Trip trip);
    boolean delete(String tripId);
    Trip lookup(String tripId);
    List<Trip> allTrips();
    void saveTripFilter(TripFilter tripFilter);
    TripFilter getLastTripFilter();
    void saveReminderTypes(Set<ReminderType> reminderTypes);
    Set<ReminderType> getReminderTypes();
    void saveReminderSchedule(ReminderSchedule schedule);
    ReminderSchedule getReminderSchedule();

    void init(MainActivity activity, String userId);
    void reset();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by JetBrains Inspect Code 2022.2 -->
<Report ToolsVersion="222.0.20220729.152730">
  <Information>
    <Solution>..\Roflcopter.Plugin.Tests\test\data\Roflcopter.Sample.sln</Solution>
    <InspectionScope>
      <Element>Solution</Element>
    </InspectionScope>
  </Information>
  <IssueTypes>
    <IssueType Id="ConditionIsAlwaysTrueOrFalse" Category="Redundancies in Code" CategoryId="CodeRedundancy" Description="Expression is always 'true' or always 'false'" Severity="WARNING" WikiUrl="https://www.jetbrains.com/resharperplatform/help?Keyword=ConditionIsAlwaysTrueOrFalse" />
    <IssueType Id="HeuristicUnreachableCode" Category="Redundancies in Code" CategoryId="CodeRedundancy" Description="Heuristically unreachable code" Severity="WARNING" />
  </IssueTypes>
  <Issues>
    <Project Name="Roflcopter.Sample">
      <Issue TypeId="ConditionIsAlwaysTrueOrFalse" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageContractAnnotationSamples.cs" Offset="686-695" Line="19" Message="Expression is always true" />
      <Issue TypeId="ConditionIsAlwaysTrueOrFalse" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageContractAnnotationSamples.cs" Offset="2744-2754" Line="59" Message="Expression is always true" />
      <Issue TypeId="ConditionIsAlwaysTrueOrFalse" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageContractAnnotationSamples.cs" Offset="2832-2842" Line="61" Message="Expression is always true" />
      <Issue TypeId="HeuristicUnreachableCode" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageContractAnnotationSamples.cs" Offset="3133-3204" Line="68" Message="Code is heuristically unreachable" />
      <Issue TypeId="ConditionIsAlwaysTrueOrFalse" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageLegacyAnnotationSamples.cs" Offset="524-533" Line="16" Message="Expression is always true" />
      <Issue TypeId="ConditionIsAlwaysTrueOrFalse" File="AssertionMessages\InvalidAssertionMessageHighlightingTests\AssertionMessageLegacyAnnotationSamples.cs" Offset="1510-1520" Line="37" Message="Expression is always true" />
    </Project>
  </Issues>
</Report>


text:
package com.alexrnl.jseries.request.parameters;

/**
 * Parameter which allow to set an email for the member to be find.

 * @author Alex
 */
public class Find extends Parameter<String> {
	/** The name of the email parameter */
	public static final String	PARAMETER_FIND	= "find";

	/**
	 * Constructor #1.

	 * @param email
	 *        the email of the member to find.
	 */
	public Find (final String email) {
		super(PARAMETER_FIND, email);
	}
}


text:
JFLAGS=

# Recognize files with .class and .java extensions
.SUFFIXES: .class .java

# This is a rule to convert a file with .java extension
# into a file with a .class extension. The macro $< just
# supplies the name of the file (without the extension)
# that invoked this rule.

.java.class:
	javac $(JFLAGS) $<

# To satisfy the rule named compile, we must have the  following
# class files (with date no later than the source .java files).
# We also must have satisfied the rule named doc.

all: compile

# Get the list of .java files and convert to list of .class files
compile: $(patsubst %.java,%.class, $(wildcard *.java))

# Run javadoc on all hava source files in this directory.
# This rule depends upon the rule named html, which makes the
# html directory if does not already exist.

doc: html
	javadoc -private -author -version -d html/ *.java

# Make the html subdirectory.
html:
	mkdir html

clean:
		/bin/rm --force  *.class


text:
"""Tests for the Entity Registry."""
import asyncio
from unittest.mock import patch

import pytest

from homeassistant.helpers import entity_registry

from tests.common import mock_registry, flush_store

YAML__OPEN_PATH = 'homeassistant.util.yaml.open'

@pytest.fixture
def registry(hass):
    """Return an empty, loaded, registry."""
    return mock_registry(hass)

@asyncio.coroutine
def test_get_or_create_returns_same_entry(registry):
    """Make sure we do not duplicate entries."""
    entry = registry.async_get_or_create('light', 'hue', '1234')
    entry2 = registry.async_get_or_create('light', 'hue', '1234')

    assert len(registry.entities) == 1
    assert entry is entry2
    assert entry.entity_id == 'light.hue_1234'

@asyncio.coroutine
def test_get_or_create_suggested_object_id(registry):
    """Test that suggested_object_id works."""
    entry = registry.async_get_or_create(
        'light', 'hue', '1234', suggested_object_id='beer')

    assert entry.entity_id == 'light.beer'

@asyncio.coroutine
def test_get_or_create_suggested_object_id_conflict_register(registry):
    """Test that we don't generate an entity id that is already registered."""
    entry = registry.async_get_or_create(
        'light', 'hue', '1234', suggested_object_id='beer')
    entry2 = registry.async_get_or_create(
        'light', 'hue', '5678', suggested_object_id='beer')

    assert entry.entity_id == 'light.beer'
    assert entry2.entity_id == 'light.beer_2'

@asyncio.coroutine
def test_get_or_create_suggested_object_id_conflict_existing(hass, registry):
    """Test that we don't generate an entity id that currently exists."""
    hass.states.async_set('light.hue_1234', 'on')
    entry = registry.async_get_or_create('light', 'hue', '1234')
    assert entry.entity_id == 'light.hue_1234_2'

@asyncio.coroutine
def test_create_triggers_save(hass, registry):
    """Test that registering entry triggers a save."""
    with patch.object(registry, 'async_schedule_save') as mock_schedule_save:
        registry.async_get_or_create('light', 'hue', '1234')

    assert len(mock_schedule_save.mock_calls) == 1

async def test_loading_saving_data(hass, registry):
    """Test that we load/save data correctly."""
    orig_entry1 = registry.async_get_or_create('light', 'hue', '1234')
    orig_entry2 = registry.async_get_or_create(
        'light', 'hue', '5678', config_entry_id='mock-id')

    assert len(registry.entities) == 2

    # Now load written data in new registry
    registry2 = entity_registry.EntityRegistry(hass)
    await flush_store(registry._store)
    await registry2.async_load()

    # Ensure same order
    assert list(registry.entities) == list(registry2.entities)
    new_entry1 = registry.async_get_or_create('light', 'hue', '1234')
    new_entry2 = registry.async_get_or_create('light', 'hue', '5678',
                                              config_entry_id='mock-id')

    assert orig_entry1 == new_entry1
    assert orig_entry2 == new_entry2

@asyncio.coroutine
def test_generate_entity_considers_registered_entities(registry):
    """Test that we don't create entity id that are already registered."""
    entry = registry.async_get_or_create('light', 'hue', '1234')
    assert entry.entity_id == 'light.hue_1234'
    assert registry.async_generate_entity_id('light', 'hue_1234') == \
        'light.hue_1234_2'

@asyncio.coroutine
def test_generate_entity_considers_existing_entities(hass, registry):
    """Test that we don't create entity id that currently exists."""
    hass.states.async_set('light.kitchen', 'on')
    assert registry.async_generate_entity_id('light', 'kitchen') == \
        'light.kitchen_2'

@asyncio.coroutine
def test_is_registered(registry):
    """Test that is_registered works."""
    entry = registry.async_get_or_create('light', 'hue', '1234')
    assert registry.async_is_registered(entry.entity_id)
    assert not registry.async_is_registered('light.non_existing')

async def test_loading_extra_values(hass, hass_storage):
    """Test we load extra data from the registry."""
    hass_storage[entity_registry.STORAGE_KEY] = {
        'version': entity_registry.STORAGE_VERSION,
        'data': {
            'entities': [
                {
                    'entity_id': 'test.named',
                    'platform': 'super_platform',
                    'unique_id': 'with-name',
                    'name': 'registry override',
                }, {
                    'entity_id': 'test.no_name',
                    'platform': 'super_platform',
                    'unique_id': 'without-name',
                }, {
                    'entity_id': 'test.disabled_user',
                    'platform': 'super_platform',
                    'unique_id': 'disabled-user',
                    'disabled_by': 'user',
                }, {
                    'entity_id': 'test.disabled_hass',
                    'platform': 'super_platform',
                    'unique_id': 'disabled-hass',
                    'disabled_by': 'hass',
                }
            ]
        }
    }

    registry = await entity_registry.async_get_registry(hass)

    entry_with_name = registry.async_get_or_create(
        'test', 'super_platform', 'with-name')
    entry_without_name = registry.async_get_or_create(
        'test', 'super_platform', 'without-name')
    assert entry_with_name.name == 'registry override'
    assert entry_without_name.name is None
    assert not entry_with_name.disabled

    entry_disabled_hass = registry.async_get_or_create(
        'test', 'super_platform', 'disabled-hass')
    entry_disabled_user = registry.async_get_or_create(
        'test', 'super_platform', 'disabled-user')
    assert entry_disabled_hass.disabled
    assert entry_disabled_hass.disabled_by == entity_registry.DISABLED_HASS
    assert entry_disabled_user.disabled
    assert entry_disabled_user.disabled_by == entity_registry.DISABLED_USER

@asyncio.coroutine
def test_async_get_entity_id(registry):
    """Test that entity_id is returned."""
    entry = registry.async_get_or_create('light', 'hue', '1234')
    assert entry.entity_id == 'light.hue_1234'
    assert registry.async_get_entity_id(
        'light', 'hue', '1234') == 'light.hue_1234'
    assert registry.async_get_entity_id('light', 'hue', '123') is None

async def test_updating_config_entry_id(registry):
    """Test that we update config entry id in registry."""
    entry = registry.async_get_or_create(
        'light', 'hue', '5678', config_entry_id='mock-id-1')
    entry2 = registry.async_get_or_create(
        'light', 'hue', '5678', config_entry_id='mock-id-2')
    assert entry.entity_id == entry2.entity_id
    assert entry2.config_entry_id == 'mock-id-2'

async def test_removing_config_entry_id(registry):
    """Test that we update config entry id in registry."""
    entry = registry.async_get_or_create(
        'light', 'hue', '5678', config_entry_id='mock-id-1')
    assert entry.config_entry_id == 'mock-id-1'
    registry.async_clear_config_entry('mock-id-1')

    entry = registry.entities[entry.entity_id]
    assert entry.config_entry_id is None

async def test_migration(hass):
    """Test migration from old data to new."""
    old_conf = {
        'light.kitchen': {
            'config_entry_id': 'test-config-id',
            'unique_id': 'test-unique',
            'platform': 'test-platform',
            'name': 'Test Name',
            'disabled_by': 'hass',
        }
    }
    with patch('os.path.isfile', return_value=True), patch('os.remove'), \
        patch('homeassistant.helpers.entity_registry.load_yaml',
              return_value=old_conf):
        registry = await entity_registry.async_get_registry(hass)

    assert registry.async_is_registered('light.kitchen')
    entry = registry.async_get_or_create(
        domain='light',
        platform='test-platform',
        unique_id='test-unique',
        config_entry_id='test-config-id',
    )
    assert entry.name == 'Test Name'
    assert entry.disabled_by == 'hass'
    assert entry.config_entry_id == 'test-config-id'


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]
### Added
- create table `content_version_page` to store older versions of cms pages
- save older versions of cms pages via event `cms_page_save_after` into table `content_version_page`
- add tab `Versions` to edit cms page
- receive diff between two cms page versions via ajax


text:
-------------------------------------------------------------------------------
--  plm requirement
-------------------------------------------------------------------------------
CREATE TABLE PLM_REQUIREMENT(
        ID BIGINT NOT NULL,
	NAME VARCHAR(200),
	PRIORITY INT,
	TAG VARCHAR(200),
	STATUS VARCHAR(50),
	CREATE_TIME DATETIME,
	USER_ID VARCHAR(64),
	PARENT_ID BIGINT,
	ISSUE_ID BIGINT,
	VERSION_ID BIGINT,
	PROJECT_ID BIGINT,
	CONSTRAINT PK_PLM_REQUIREMENT PRIMARY KEY(ID),
        CONSTRAINT FK_PIM_REQUIREMENT_PARENT FOREIGN KEY(PARENT_ID) REFERENCES PLM_REQUIREMENT(ID),
        CONSTRAINT FK_PIM_REQUIREMENT_ISSUE FOREIGN KEY(ISSUE_ID) REFERENCES PLM_ISSUE(ID),
        CONSTRAINT FK_PIM_REQUIREMENT_VERSION FOREIGN KEY(VERSION_ID) REFERENCES PLM_VERSION(ID),
        CONSTRAINT FK_PIM_REQUIREMENT_PROJECT FOREIGN KEY(PROJECT_ID) REFERENCES PLM_PROJECT(ID)
) ENGINE=INNODB CHARSET=UTF8;