text:
**WDI Fundamentals Unit 4**

---

We've covered how we can tell our programs to make decisions; now let's look at how we can tell our programs to take repeated/ongoing actions.

## The `while` Loop

To tell your program to repeat something, you use a tool called a **loop** - once your program has finished running a block of code, it 'loops' back to the beginning and starts again.

Suppose that we were to take our `if` statement from the previous lesson and loop it back on itself. Here's the flow diagram for the `if`, in case you've forgotten it.

![Flow Chart for `If` Statement](../assets/chapter4/flow_chart_if.png)

We're going to make one small (but very important) change to this - instead of advancing to the next bit of code after executing the block, we will loop back to our condition.

![Flow Chart `If` -> `While`](../assets/chapter4/flow_chart_if-to-while.png)

Now, we have a loop - so long as our condition remains true (or at least truthy), we will continue to run that block of code over and over again. This type of loop is called a `while` loop, and can be found in nearly every programming language. Here's the general rule for how a while loop is written in JavaScript.

```javascript
while (someCondition) {
  // A block of code.
}
```
As you can see, it is written in almost exactly the same way as an `if` statement.

### Test Yourself
* Consider the following code.

```javascript
var x = 10;
while (x > 5) {
  x -= 2;
}
```

How many times will this loop run? What will the final value of `x` be when it finishes?

* Here's another loop.

```javascript
var x = 10;
var y = 1;
while (x < 20) {
  y += 1;
}
```

How many times will this loop run? What happens when you try to run this code?

A while loop can run **indefinitely** as long as your condition remains true; this is usually a bad thing, so when using a while loop, it's **very important** to plan out beforehand how you will 'escape' the loop by making your condition evaluate to `false`.

Consider the following example.

```javascript
var z = 0;
var myString = '';
while (z < 5) {
  myString += 'X';
  z += 1;
}
```

Q: How many times does this loop run? What's the final value of myString?

A: Each time this loop runs, the value of `z` increases by 1; since its initial value is 0, and the condition becomes `false` the moment that z becomes 5, this means that our loop runs exactly 5 times. As a result, the string `myString` has a final value of "XXXXX" (5 Xs).

Confused? Here's the play-by-play.
* `z` is set to 0 and `myString` is set to "".
* `z` is 0, therefore z < 5 is true so the block gets executed.
  * (in the block) "X" gets added to the end of `myString`; it is now "X"
  * (in the block) `z` is increased by 1; it is now 1. Now that the block is done, we go back to the condition.
* `z` is 1, therefore z < 5 is true so the block gets executed.
  * (in the block) "X" gets added to the end of `myString`; it is now "XX"
  * (in the block) `z` is increased by 1; it is now 2. Now that the block is done, we go back to the condition.
* `z` is 2, therefore z < 5 is true so the block gets executed.
  * (in the block) "X" gets added to the end of `myString`; it is now "XXX"
  * (in the block) `z` is increased by 1; it is now 3. Now that the block is done, we go back to the condition.
* `z` is 3, therefore z < 5 is true so the block gets executed.
  * (in the block) "X" gets added to the end of `myString`; it is now "XXXX"
  * (in the block) `z` is increased by 1; it is now 4. Now that the block is done, we go back to the condition.
* `z` is 4, therefore z < 5 is true so the block gets executed.
  * (in the block) "X" gets added to the end of `myString`; it is now "XXXXX"
  * (in the block) `z` is increased by 1; it is now 5. Now that the block is done, we go back to the condition.
* `z` is now 5, therefore z < 5 is now **false** (since 5 is **not** less than 5) so the block does not get executed again.
* We're done!

What's most interesting about this kind of setup is that if we changed that condition from z < 5 to z < 10, or z < 100, the loop would change to run exactly 10 or exactly 100 times, respectively. In effect, we have changed the `while` loop so that it always runs for a fixed, precisely controllable number of times - it will never get stuck in an infinite loop.

This kind of setup is so useful, and gets used so frequently, that most languages include a special kind of loop used for just this kind of behavior, called a `for` loop.

## The `for` Loop

Let's make a few modifications to our while loop from earlier.

![Flow Chart for `For` Loop](../assets/chapter4/flow_chart_while-to-for.png)

As you can see, there are a couple of key ingredients to making our `for` loop work. We need
1. an 'initialization', which sets up a starting situation (e.g. var x = 0)
2. a condition, which gets evaluated each time we're about to execute the block (e.g. x < 10)
3. a 'finalExpression', which gets evaluated immediately after the block executes *but before the condition is evaluated again* (e.g. x += 1;)

The general syntax for a `for` loop is

```javascript
for (initialization; condition; finalExpression) {
  // A block of code.
}
```

### Test Yourself

```javascript
var x = 10;
for (var i = 0; i < x; i += 1) {
  console.log('HELLO'); // This is a command to our console, telling it to display the text 'HELLO' and advance to a new line.
}
```

* How many times will 'HELLO' be printed out in the console?
* What if (all else the same) we changed the starting value of `i` to 1 instead of 0? How many times would `HELLO` get printed to the console?
* What if (all else the same) we changed the condition from i < x to i <= x?
* What if (all else the same) we changed the final condition from i += 1 to i += 2?
Check your answers in repl.it.

---

Feeling good about loops? [Let's do another exercise.](07_exercise.md)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>nablarch-dev-ui_test-support\ui_test\js\testsupport.js - Nablarch JavaScript Widget</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.0.0

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

jQuery

jsp

jsp.taglib.box

jsp.taglib.button

jsp.taglib.column

jsp.taglib.device

jsp.taglib.function

jsp.taglib.html

jsp.taglib.jsp

jsp.taglib.jstl

jsp.taglib.layout

jsp.taglib.listsearchresult

jsp.taglib.nablarch

jsp.taglib.tab

jsp.taglib.table

jsp.taglib.template

nablarch.ui

nablarch.ui.AutoSpan

nablarch.ui.AutoSum

nablarch.ui.Collapsible

nablarch.ui.ContextMenu

nablarch.ui.DatePicker

nablarch.ui.event.AjaxAction

nablarch.ui.event.Listener

nablarch.ui.event.ShowDialog

nablarch.ui.event.SubWindowListener

nablarch.ui.event.ToggleAction

nablarch.ui.event.WindowClose

nablarch.ui.event.WriteAction

nablarch.ui.LightBox

nablarch.ui.ListBuilder

nablarch.ui.selector

nablarch.ui.SlideMenu

nablarch.ui.Tab

nablarch.ui.TabindexOrder

nablarch.ui.TabLink

nablarch.ui.ToggleCheckbox

nablarch.ui.Tooltip

nablarch.ui.TreeList

nablarch.ui.TreeMenu

nablarch.ui.Widget

nablarch.util.BigDecimal

nablarch.util.BigDecimal.NaN

nablarch.util.Consumer

nablarch.util.DateUtil

nablarch.util.SimpleDateFormat

devtool

jsp

jsp.taglib

nablarch.ui

nablarch.ui.device

nablarch.util

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: nablarch-dev-ui_test-support\ui_test\js\testsupport.js

// 自動テストのサポートメソッドを提供する。
/**
 * nablarch_hiddenから値を取得する。
 *
 * @param $node nablarch_hiddenに値を格納したNodeのjqueryラッパー
 * @key nablarch_hiddenから取得するためのキー
 */
n_hidden_val = function($node, key) {
  var $form  = $node.closest('form')
    , n_text = $form.find('input[name="nablarch_hidden"]').val()
    , vals   = n_text.split('|')
    , filter = function(val) {return val.startsWith(key);}
    , data;
  data = vals.findAll(filter).first();
  return $.trim(data).endsWith('=') ? "" : data.split('=')[1];
};


text:
""" Test end to end flow with:
        Ingress: HTTP south plugin
        Egress: PI Server (C) plugin & scale-set filter plugin
"""

import os
import subprocess
import http.client
import json
import time
import pytest
import utils

__author__ = "Praveen Garg"
__copyright__ = "Copyright (c) 2019 Dianomic Systems"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"

SOUTH_PLUGIN = "http_south"
SVC_NAME = "Room #1"
ASSET_PREFIX = "http-"  # default for HTTP South plugin
ASSET_NAME = "e1"

TASK_NAME = "North v2 PI"

FILTER_PLUGIN = "scale-set"
EGRESS_FILTER_NAME = "SS #1"

READ_KEY = "temperature"
SENSOR_VALUE = 21

# scale(set) factor
SCALE = 9/5
OFFSET = 32
OUTPUT = (SENSOR_VALUE * SCALE) + OFFSET

class TestE2ePiEgressWithScalesetFilter:

    def get_ping_status(self, foglamp_url):
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("GET", '/foglamp/ping')
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        return jdoc

    def get_statistics_map(self, foglamp_url):
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("GET", '/foglamp/statistics')
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        return utils.serialize_stats_map(jdoc)

    @pytest.fixture
    def start_south_north_with_filter(self, reset_and_start_foglamp, add_south, south_branch,
                                      remove_data_file, remove_directories, enable_schedule,
                                      foglamp_url, add_filter, filter_branch, filter_name,
                                      start_north_pi_server_c, pi_host, pi_port, pi_token):
        """ This fixture clones given south & filter plugin repo, and starts south and PI north C instance with filter

        """
        fogbench_template_path = os.path.join(
            os.path.expandvars('${FOGLAMP_ROOT}'), 'data/template.json')
        with open(fogbench_template_path, "w") as f:
            f.write(
                '[{"name": "%s", "sensor_values": '
                '[{"name": "%s", "type": "number", "min": %d, "max": %d, "precision": 0}]}]' % (
                    ASSET_NAME, READ_KEY, SENSOR_VALUE, SENSOR_VALUE))

        add_south(SOUTH_PLUGIN, south_branch, foglamp_url, service_name=SVC_NAME)

        start_north_pi_server_c(foglamp_url, pi_host, pi_port, pi_token, taskname=TASK_NAME, start_task=False)

        filter_cfg = {"enable": "true",
                      "factors": {"factors": [
                          {
                              "asset": "{}{}".format(ASSET_PREFIX, ASSET_NAME),
                              "datapoint": READ_KEY,
                              "scale": SCALE,
                              "offset": OFFSET
                          }]}
                      }

        add_filter(FILTER_PLUGIN, filter_branch, EGRESS_FILTER_NAME, filter_cfg, foglamp_url, TASK_NAME)
        enable_schedule(foglamp_url, TASK_NAME)

        yield self.start_south_north_with_filter

        remove_data_file(fogbench_template_path)
        remove_directories("/tmp/foglamp-south-{}".format(ASSET_NAME.lower()))
        remove_directories("/tmp/foglamp-filter-{}".format(FILTER_PLUGIN))

    def test_end_to_end(self, start_south_north_with_filter, read_data_from_pi, foglamp_url, pi_host, pi_admin,
                        pi_passwd, pi_db, wait_time, retries, skip_verify_north_interface):

        subprocess.run(["cd $FOGLAMP_ROOT/extras/python; python3 -m fogbench -t ../../data/template.json -p http; cd -"]
                       , shell=True, check=True)
        # let the readings ingress
        time.sleep(wait_time * 2)

        self._verify_ping_and_statistics(foglamp_url, count=1, skip_verify_north_interface=skip_verify_north_interface)

        self._verify_ingest(foglamp_url, SENSOR_VALUE, read_count=1)

        if not skip_verify_north_interface:
            self._verify_egress(read_data_from_pi, pi_host, pi_admin, pi_passwd, pi_db, wait_time, retries)

        tracking_details = utils.get_asset_tracking_details(foglamp_url, "Ingest")
        assert len(tracking_details["track"]), "Failed to track Ingest event"
        tracked_item = tracking_details["track"][0]
        assert SVC_NAME == tracked_item["service"]
        assert "http-e1" == tracked_item["asset"]
        assert "http_south" == tracked_item["plugin"]

        tracking_details = utils.get_asset_tracking_details(foglamp_url, "Filter")
        assert len(tracking_details["track"]), "Failed to track Filter event"
        tracked_item = tracking_details["track"][0]
        assert TASK_NAME == tracked_item["service"]
        assert "http-e1" == tracked_item["asset"]
        assert "SS #1" == tracked_item["plugin"]

        if not skip_verify_north_interface:
            egress_tracking_details = utils.get_asset_tracking_details(foglamp_url,"Egress")
            assert len(egress_tracking_details["track"]), "Failed to track Egress event"
            tracked_item = egress_tracking_details["track"][0]
            assert TASK_NAME == tracked_item["service"]
            assert "http-e1" == tracked_item["asset"]
            assert "PI_Server_V2" == tracked_item["plugin"]

    def _verify_ping_and_statistics(self, foglamp_url, count, skip_verify_north_interface=False):
        ping_response = self.get_ping_status(foglamp_url)
        assert count == ping_response["dataRead"]
        if not skip_verify_north_interface:
            assert count == ping_response["dataSent"]

        actual_stats_map = self.get_statistics_map(foglamp_url)
        key_asset_name_with_prefix = "{}{}".format(ASSET_PREFIX.upper(), ASSET_NAME.upper())
        assert count == actual_stats_map[key_asset_name_with_prefix]
        assert count == actual_stats_map['READINGS']

        if not skip_verify_north_interface:
            assert count == actual_stats_map['Readings Sent']
            assert count == actual_stats_map[TASK_NAME]

    def _verify_ingest(self, foglamp_url, value, read_count):
        asset_name_with_prefix = "{}{}".format(ASSET_PREFIX, ASSET_NAME)
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("GET", '/foglamp/asset')
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        assert len(jdoc), "No asset found"
        assert asset_name_with_prefix == jdoc[0]["assetCode"]
        assert read_count == jdoc[0]["count"]

        conn.request("GET", '/foglamp/asset/{}'.format(asset_name_with_prefix))
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        assert len(jdoc), "No asset found"
        assert value == jdoc[0]["reading"][READ_KEY]

    def _verify_egress(self, read_data_from_pi, pi_host, pi_admin, pi_passwd, pi_db, wait_time, retries):
        retry_count = 0
        data_from_pi = None
        while (data_from_pi is None or data_from_pi == []) and retry_count < retries:
            asset_name_with_prefix = "{}{}".format(ASSET_PREFIX, ASSET_NAME)
            data_from_pi = read_data_from_pi(pi_host, pi_admin, pi_passwd, pi_db, asset_name_with_prefix, {READ_KEY})
            retry_count += 1
            time.sleep(wait_time * 2)

        if data_from_pi is None or retry_count == retries:
            assert False, "Failed to read data from PI"

        assert READ_KEY in data_from_pi
        assert isinstance(data_from_pi[READ_KEY], list)
        assert round(OUTPUT, 1) in [round(n, 1) for n in data_from_pi[READ_KEY]]


text:
<?php
declare(strict_types=1);

namespace Fduch\Netrc\Exception;

use \RuntimeException;

/**
 * ParseException
 *
 * @author Alex Medvedev
 */
class ParseException extends RuntimeException
{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DeadCode
{
    public class Program
    {
        public static void Main(string[] args)
        {
        }
    }
}


text:
package cn.binarywang.wx.miniapp.bean.delivery;

import cn.binarywang.wx.miniapp.bean.delivery.base.WxMaDeliveryBaseResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 微信小程序即时配送 异常件退回商家商家确认收货接口 响应参数.
 *
 * @author Luo
 * @version 1.0
 * created on  2021-10-14 10:49
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class AbnormalConfirmResponse extends WxMaDeliveryBaseResponse implements Serializable {

    private static final long serialVersionUID = 3773007367000633663L;

}


text:
jQuery-Ajax-File-Upload
=======================

Plugin to add support for file uploads using jQuery $.ajax()

##What is this?
All this plugin does is:

1. Grabs the files from file fields on change events and adds the data to an array.
2. On form submit it does a pre-ajax call to the back-end with the file post data.
3. After uploading, information about those files is passed back and appended to a normal $.ajax() call.

## Usage
It's easy enough to use, just include it on your page and attach it to your form with:

	$('#myform').fileUpload();

You can pass the following parameters to it:

	$('#myform').fileUpload({
		uploadData    : { 'extra_data' : 'blah' }, // Append POST data to the upload
		submitData    : { 'moar_extra_data' : 'blah' }, // Append POST data to the form submit
		uploadOptions : { dataType : 'json' }, // Customise the parameters passed to the $.ajax() call on uploads. You can use any of the normal $.ajax() params
		submitOptions : { dataType : 'json' }, // Customise the parameters passed to the $.ajax() call on the form submit. You can use any of the normal $.ajax() params
		before	      : function(){}, // Run stuff before the upload happens
		beforeSubmit  : function(uploadData){ console.log(uploadData); return true; }, // access the data returned by the upload return false to stop the submit ajax call
		success       : function(data, textStatus, jqXHR){ console.log(data); }, // Callback for the submit success ajax call
		error 	      : function(jqXHR, textStatus, errorThrown){ console.log(jqXHR); }, // Callback if an error happens with your upload call or the submit call
		complete      : function(jqXHR, textStatus){ console.log(jqXHR); } // Callback on completion
	});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<Keyboard
    xmlns:latin="http://schemas.android.com/apk/res/com.android.inputmethod.latin"
    latin:keyboardLeftPadding="10%p"
    latin:keyboardRightPadding="10%p"
    latin:keyWidth="13.250%p"
    latin:touchPositionCorrectionData="@array/touch_position_correction_data_default"
>
    <include
        latin:keyboardLayout="@xml/rows_number" />
</Keyboard>


text:
/*
 * candy-timeago-plugin
 * @version 0.1 (2011-07-15)
 * @author David Devlin (dave.devlin@gmail.com)
 *
 * Integrates the jQuery Timeago plugin (http://timeago.yarp.com/) with Candy.
 */

/*global
    msos: false,
    jQuery: false,
    jquery: false,
    candy: false
*/

msos.provide("candy.date.timeago");
msos.require("jquery.tools.timeago");

candy.date.timeago.version = new msos.set_version(15, 9, 10);

candy.date.timeago.iso8601 = function (date) {
	"use strict";

	var zeropad = function (num) {
			return ((num < 10) ? '0' : '') + num;
		};

    return date.getUTCFullYear()
        + "-" + zeropad(date.getUTCMonth()+1)
        + "-" + zeropad(date.getUTCDate())
        + "T" + zeropad(date.getUTCHours())
        + ":" + zeropad(date.getUTCMinutes())
        + ":" + zeropad(date.getUTCSeconds()) + "Z";
};

candy.date.timeago.init = function () {
	"use strict";

	candy.util.localizedTime = function (dateTime) {
		var temp_lt = 'candy.util.localizedTime (candy.date.timeago) -> ';

		if (msos.config.verbose) {
			msos.console.debug(temp_lt + 'start.');
		}

		if (dateTime === undefined || !dateTime instanceof Date) {
			msos.console.error(temp_lt + 'failed: missing or invalid Date instance!');
			return undefined;
		}

		if (msos.config.verbose) {
			msos.console.debug(temp_lt + 'done!');
		}
		return candy.date.timeago.iso8601(dateTime);
	};
};


text:
namespace gfx {
class SizeF;
}

namespace blink {

class ComputedStyle;
class DOMRectReadOnly;
class LayoutBox;
class LayoutObject;
class LayoutRect;
class LayoutSize;

// Helper functions for ResizeObserverEntry and ResizeObservation.
class ResizeObserverUtilities {
 public:
  // Given |box_option|, compute the appropriate box for use with
  // ResizeObserver. This takes the following factors into account: writing
  // mode, effective zoom (for non-device-pixel boxes) and pixel snapping for
  // device-pixel boxes.
  static gfx::SizeF ComputeZoomAdjustedBox(ResizeObserverBoxOptions box_option,
                                           const LayoutBox& layout_box,
                                           const ComputedStyle& style);

  // Compute a scaled and pixel snapped device pixel content box for svg
  // bounding boxes.
  static gfx::SizeF ComputeSnappedDevicePixelContentBox(
      LayoutSize box_size,
      const LayoutObject& layout_object,
      const ComputedStyle& style);

  static DOMRectReadOnly* ZoomAdjustedLayoutRect(LayoutRect content_rect,
                                                 const ComputedStyle& style);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_RESIZE_OBSERVER_RESIZE_OBSERVER_UTILITIES_H_


text:
import React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createMount, getClasses } from '@material-ui/core/test-utils';
import describeConformance from '../test-utils/describeConformance';
import consoleErrorMock from 'test/utils/consoleErrorMock';
import { createClientRender } from 'test/utils/createClientRender';
import SwitchBase from './SwitchBase';
import FormControl, { useFormControl } from '../FormControl';
import IconButton from '../IconButton';

const shouldSuccessOnce = name => func => () => {
  global.successOnce = global.successOnce || {};

  if (!global.successOnce[name]) {
    func();
    global.successOnce[name] = true;
  }
};

describe('<SwitchBase />', () => {
  const render = createClientRender({ strict: true });
  let mount;
  let classes;

  before(() => {
    mount = createMount({ strict: true });
    classes = getClasses(<SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" />);
  });

  describeConformance(
    <SwitchBase checkedIcon="checked" icon="unchecked" type="checkbox" />,
    () => ({
      classes,
      inheritComponent: IconButton,
      mount,
      refInstanceof: window.HTMLSpanElement,
      testComponentPropWith: 'div',
      after: () => mount.cleanUp(),
    }),
  );

  it('should render a span', () => {
    const { container } = render(
      <SwitchBase checkedIcon="checked" icon="unchecked" type="checkbox" />,
    );

    expect(container.firstChild).to.have.property('nodeName', 'SPAN');
  });

  it('should render an icon and input inside the button by default', () => {
    const { container, getByRole } = render(
      <SwitchBase checkedIcon="checked" icon="unchecked" type="checkbox" />,
    );
    const buttonInside = container.firstChild.firstChild;

    expect(buttonInside).to.have.property('nodeName', 'SPAN');
    expect(buttonInside.childNodes[0]).to.equal(getByRole('checkbox'));
    expect(buttonInside.childNodes[1]).to.have.text('unchecked');
  });

  it('should have a ripple by default', () => {
    const { getByTestId } = render(
      <SwitchBase
        checkedIcon="checked"
        icon="unchecked"
        type="checkbox"
        TouchRippleProps={{ 'data-testid': 'TouchRipple' }}
      />,
    );

    expect(getByTestId('TouchRipple')).to.be.ok;
  });

  it('can disable the ripple ', () => {
    const { queryByTestId } = render(
      <SwitchBase
        checkedIcon="checked"
        icon="unchecked"
        type="checkbox"
        disableRipple
        TouchRippleProps={{ 'data-testid': 'TouchRipple' }}
      />,
    );

    expect(queryByTestId('TouchRipple')).to.be.null;
  });

  it('should pass tabIndex to the input so it can be taken out of focus rotation', () => {
    const { getByRole } = render(
      <SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" tabIndex={-1} />,
    );

    expect(getByRole('checkbox')).to.have.attribute('tabIndex', '-1');
  });

  it('should pass value, disabled, checked, and name to the input', () => {
    const { getByRole } = render(
      <SwitchBase
        icon="unchecked"
        checkedIcon="checked"
        type="checkbox"
        name="gender"
        disabled
        value="male"
      />,
    );
    const input = getByRole('checkbox');

    expect(input).to.have.attribute('name', 'gender');
    expect(input).to.have.attribute('disabled');
    expect(input).to.have.attribute('value', 'male');
  });

  it('can disable the components, and render the IconButton with the disabled className', () => {
    const { container } = render(
      <SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" disabled />,
    );

    // to.be.disabled
    expect(container.firstChild).to.have.attribute('aria-disabled', 'true');
    expect(container.firstChild).to.have.class(classes.disabled);
  });

  describe('controlled', () => {
    it('should check the checkbox', () => {
      const { container, getByRole, getByTestId, setProps } = render(
        <SwitchBase
          icon="unchecked"
          checkedIcon={}
          type="checkbox"
          checked={false}
        />,
      );
      setProps({ checked: true });

      expect(container.firstChild).to.have.class(classes.checked);
      expect(getByRole('checkbox')).to.have.property('checked', true);
      expect(getByTestId('checked-icon')).to.be.ok;
    });

    it('should uncheck the checkbox', () => {
      const { container, getByRole, getByTestId, setProps } = render(
        <SwitchBase
          icon={}
          checkedIcon="checked"
          type="checkbox"
          checked
        />,
      );
      setProps({ checked: false });

      expect(container.firstChild).not.to.have.class(classes.checked);
      expect(getByRole('checkbox')).to.have.property('checked', false);
      expect(getByTestId('unchecked-icon')).to.be.ok;
    });
  });

  it('can change checked state uncontrolled starting from defaultChecked', () => {
    const { container, getByRole, getByTestId } = render(
      <SwitchBase
        icon={}
        checkedIcon={}
        type="checkbox"
        defaultChecked
      />,
    );

    expect(container.firstChild).to.have.class(classes.checked);
    expect(getByRole('checkbox')).to.have.property('checked', true);
    expect(getByTestId('checked-icon')).to.be.ok;

    getByRole('checkbox').click();

    expect(container.firstChild).not.to.have.class(classes.checked);
    expect(getByRole('checkbox')).to.have.property('checked', false);
    expect(getByTestId('unchecked-icon')).to.be.ok;

    getByRole('checkbox').click();

    expect(container.firstChild).to.have.class(classes.checked);
    expect(getByRole('checkbox')).to.have.property('checked', true);
    expect(getByTestId('checked-icon')).to.be.ok;
  });

  describe('handleInputChange()', () => {
    it('should call onChange when uncontrolled', () => {
      const handleChange = spy(event => event.target.checked);
      const { getByRole } = render(
        <SwitchBase
          icon="unchecked"
          checkedIcon="checked"
          type="checkbox"
          onChange={handleChange}
        />,
      );

      getByRole('checkbox').click();

      expect(handleChange.callCount).to.equal(1);
      // event.target.check is true
      expect(handleChange.firstCall.returnValue).to.equal(true);
    });

    it('should call onChange when controlled', () => {
      const checked = true;
      const handleChange = spy((event, newChecked) => newChecked);
      const { getByRole } = render(
        <SwitchBase
          icon="unchecked"
          checkedIcon="checked"
          type="checkbox"
          checked={checked}
          onChange={handleChange}
        />,
      );

      getByRole('checkbox').click();

      expect(handleChange.callCount).to.equal(1);
      expect(handleChange.firstCall.returnValue).to.equal(!checked);
    });

    describe('prop: inputProps', () => {
      it('should be able to add aria', () => {
        const { getByLabelText } = render(
          <SwitchBase
            icon="unchecked"
            checkedIcon="checked"
            type="checkbox"
            inputProps={{ 'aria-label': 'foo' }}
          />,
        );

        expect(getByLabelText('foo')).to.have.property('type', 'checkbox');
      });
    });

    describe('prop: id', () => {
      it('should be able to add id to a checkbox input', () => {
        const { getByRole } = render(
          <SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" id="foo" />,
        );

        expect(getByRole('checkbox')).to.have.attribute('id', 'foo');
      });

      it('should be able to add id to a radio input', () => {
        const { getByRole } = render(
          <SwitchBase icon="unchecked" checkedIcon="checked" type="radio" id="foo" />,
        );

        expect(getByRole('radio')).to.have.attribute('id', 'foo');
      });
    });
  });

  describe('with FormControl', () => {
    describe('enabled', () => {
      it('should not have the disabled class', () => {
        const { getByTestId } = render(
          <FormControl>
            <SwitchBase data-testid="root" icon="unchecked" checkedIcon="checked" type="checkbox" />
          </FormControl>,
        );

        expect(getByTestId('root')).not.to.have.class(classes.disabled);
      });

      it('should be overridden by props', () => {
        const { getByTestId } = render(
          <FormControl>
            <SwitchBase
              disabled
              data-testid="root"
              icon="unchecked"
              checkedIcon="checked"
              type="checkbox"
            />
          </FormControl>,
        );

        expect(getByTestId('root')).to.have.class(classes.disabled);
      });
    });

    describe('disabled', () => {
      it('should have the disabled class', () => {
        const { getByTestId } = render(
          <FormControl disabled>
            <SwitchBase data-testid="root" icon="unchecked" checkedIcon="checked" type="checkbox" />
          </FormControl>,
        );

        expect(getByTestId('root')).to.have.class(classes.disabled);
      });

      it('should be overridden by props', () => {
        const { getByTestId } = render(
          <FormControl>
            <SwitchBase
              disabled={false}
              data-testid="root"
              icon="unchecked"
              checkedIcon="checked"
              type="checkbox"
            />
          </FormControl>,
        );

        expect(getByTestId('root')).not.to.have.class(classes.disabled);
      });
    });
  });

  describe('focus/blur', () => {
    it('forwards focus/blur events and notifies the FormControl', () => {
      function FocusMonitor(props) {
        const { focused } = useFormControl();

        return focused: {String(focused)};
      }
      const handleBlur = spy();
      const handleFocus = spy();
      const { getByRole, getByTestId } = render(
        <FormControl>
          <FocusMonitor data-testid="focus-monitor" />
          <SwitchBase
            data-testid="root"
            onBlur={handleBlur}
            onFocus={handleFocus}
            icon="unchecked"
            checkedIcon="checked"
            type="checkbox"
          />
        </FormControl>,
      );

      getByRole('checkbox').focus();

      expect(getByTestId('focus-monitor')).to.have.text('focused: true');
      expect(handleFocus.callCount).to.equal(1);

      getByRole('checkbox').blur();

      expect(getByTestId('focus-monitor')).to.have.text('focused: false');
      expect(handleBlur.callCount).to.equal(1);
    });
  });

  describe('check transitioning between controlled states throws errors', () => {
    beforeEach(() => {
      consoleErrorMock.spy();
    });

    afterEach(() => {
      consoleErrorMock.reset();
    });

    it(
      'should error when uncontrolled and changed to controlled',
      shouldSuccessOnce('didWarnUncontrolledToControlled')(() => {
        const wrapper = render(
          <SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" />,
        );

        expect(consoleErrorMock.callCount()).to.equal(0);

        wrapper.setProps({ checked: true });
        expect(consoleErrorMock.callCount()).to.equal(1);
        expect(consoleErrorMock.args()[0][0]).to.include(
          'A component is changing an uncontrolled input of type %s to be controlled.',
        );
      }),
    );

    it(
      'should error when controlled and changed to uncontrolled',
      shouldSuccessOnce('didWarnControlledToUncontrolled')(() => {
        const { setProps } = render(
          <SwitchBase icon="unchecked" checkedIcon="checked" type="checkbox" checked={false} />,
        );
        expect(consoleErrorMock.callCount()).to.equal(0);

        setProps({ checked: undefined });
        expect(consoleErrorMock.callCount()).to.equal(1);
        expect(consoleErrorMock.args()[0][0]).to.include(
          'A component is changing a controlled input of type %s to be uncontrolled.',
        );
      }),
    );
  });
});


text:
#include "icint.h"

#define Mask(n)	((n) == 32 ? 0xffffffff : ((1 << (n))-1))

pixman_format_t *
pixman_format_create (pixman_format_name_t name)
{
    switch (name) {
    case PIXMAN_FORMAT_NAME_ARGB32:
	return pixman_format_create_masks (32,
				    0xff000000,
				    0x00ff0000,
				    0x0000ff00,
				    0x000000ff);
    case PIXMAN_FORMAT_NAME_RGB24:
	return pixman_format_create_masks (32,
				    0x0,
				    0xff0000,
				    0x00ff00,
				    0x0000ff);
    case PIXMAN_FORMAT_NAME_A8:
	return pixman_format_create_masks (8, 0xff,
				    0, 0, 0);
    case PIXMAN_FORMAT_NAME_A1:
	return pixman_format_create_masks (1, 0x1,
				    0, 0, 0);
    }

    return NULL;
}

/* XXX: There's some nonsense going on here. The macros above help
   pixman_format_create_masks to encode a format into an int, while
   immediately afterwards pixman_format_init goes through the effort of
   decoding it. This should all be disentagled, (it's probably
   possible to just eliminate the encoding macros altogether). */
pixman_format_t *
pixman_format_create_masks (int bpp,
		     int alpha_mask,
		     int red_mask,
		     int green_mask,
		     int blue_mask)
{
    int type;
    int format_code;
    pixman_format_t *format;

    if (red_mask == 0 && green_mask == 0 && blue_mask == 0)
	type = PICT_TYPE_A;
    else if (red_mask > blue_mask)
	type = PICT_TYPE_ARGB;
    else
	type = PICT_TYPE_ABGR;

    format_code = PICT_FORMAT (bpp, type,
			       _FbOnes (alpha_mask),
			       _FbOnes (red_mask),
			       _FbOnes (green_mask),
			       _FbOnes (blue_mask));

    format = malloc (sizeof (pixman_format_t));
    if (format == NULL)
	return NULL;

    pixman_format_init (format, format_code);

    return format;
}

void
pixman_format_init (pixman_format_t *format, int format_code)
{
    memset (format, 0, sizeof (pixman_format_t));

/* XXX: What do we want to lodge in here?
    format->id = FakeClientID (0);
*/
    format->format_code = format_code;

    switch (PICT_FORMAT_TYPE(format_code)) {
    case PICT_TYPE_ARGB:

	format->alphaMask = Mask(PICT_FORMAT_A(format_code));
	if (format->alphaMask)
	    format->alpha = (PICT_FORMAT_R(format_code) +
			     PICT_FORMAT_G(format_code) +
			     PICT_FORMAT_B(format_code));

	format->redMask = Mask(PICT_FORMAT_R(format_code));
	format->red = (PICT_FORMAT_G(format_code) +
		       PICT_FORMAT_B(format_code));

	format->greenMask = Mask(PICT_FORMAT_G(format_code));
	format->green = PICT_FORMAT_B(format_code);

	format->blueMask = Mask(PICT_FORMAT_B(format_code));
	format->blue = 0;
	break;

    case PICT_TYPE_ABGR:

	format->alphaMask = Mask(PICT_FORMAT_A(format_code));
	if (format->alphaMask)
	    format->alpha = (PICT_FORMAT_B(format_code) +
			     PICT_FORMAT_G(format_code) +
			     PICT_FORMAT_R(format_code));

	format->blueMask = Mask(PICT_FORMAT_B(format_code));
	format->blue = (PICT_FORMAT_G(format_code) +
			PICT_FORMAT_R(format_code));

	format->greenMask = Mask(PICT_FORMAT_G(format_code));
	format->green = PICT_FORMAT_R(format_code);

	format->redMask = Mask(PICT_FORMAT_R(format_code));
	format->red = 0;
	break;

    case PICT_TYPE_A:

	format->alpha = 0;
	format->alphaMask = Mask(PICT_FORMAT_A(format_code));

	/* remaining fields already set to zero */
	break;
    }

    format->depth = _FbOnes ((format->alphaMask << format->alpha) |
			     (format->redMask << format->red) |
			     (format->blueMask << format->blue) |
			     (format->greenMask << format->green));
}
slim_hidden_def(pixman_format_init);

void
pixman_format_destroy (pixman_format_t *format)
{
    free (format);
}

void
pixman_format_get_masks (pixman_format_t *format,
                         int *bpp,
                         int *alpha_mask,
                         int *red_mask,
                         int *green_mask,
                         int *blue_mask)
{
    *bpp = PICT_FORMAT_BPP (format->format_code);

    if (format->alphaMask)
	*alpha_mask = format->alphaMask << format->alpha;
    else
	*alpha_mask = 0;

    if (format->redMask)
	*red_mask = format->redMask << format->red;
    else
	*red_mask = 0;

    if (format->greenMask)
	*green_mask = format->greenMask << format->green;
    else
	*green_mask = 0;

    if (format->blueMask)
	*blue_mask = format->blueMask << format->blue;
    else
	*blue_mask = 0;
}


text:
XenForo-IgnoreUserLimit
======================

Enforces per-user group limits on for how long an ignored user list is permitted to be.

Disable User Ignore feature permits the ignore feature to be completely disabled for a usergroup.

New Permission:
- User Ignore Limit (default for registered users: -1)
- Disable User Ignore feature


text:
package org.elasticsearch.search.aggregations.pipeline;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.AggregationReduceContext;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.metrics.InternalNumericMetricsAggregation;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class InternalBucketMetricValue extends InternalNumericMetricsAggregation.SingleValue implements BucketMetricValue {
    public static final String NAME = "bucket_metric_value";
    static final ParseField KEYS_FIELD = new ParseField("keys");

    private double value;
    private String[] keys;

    public InternalBucketMetricValue(String name, String[] keys, double value, DocValueFormat formatter, Map<String, Object> metadata) {
        super(name, metadata);
        this.keys = keys;
        this.value = value;
        this.format = formatter;
    }

    /**
     * Read from a stream.
     */
    public InternalBucketMetricValue(StreamInput in) throws IOException {
        super(in);
        format = in.readNamedWriteable(DocValueFormat.class);
        value = in.readDouble();
        keys = in.readStringArray();
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeNamedWriteable(format);
        out.writeDouble(value);
        out.writeStringArray(keys);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    @Override
    public double value() {
        return value;
    }

    @Override
    public String[] keys() {
        return keys;
    }

    DocValueFormat formatter() {
        return format;
    }

    @Override
    public InternalAggregation reduce(List<InternalAggregation> aggregations, AggregationReduceContext reduceContext) {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public Object getProperty(List<String> path) {
        if (path.isEmpty()) {
            return this;
        } else if (path.size() == 1 && "value".equals(path.get(0))) {
            return value();
        } else if (path.size() == 1 && KEYS_FIELD.getPreferredName().equals(path.get(0))) {
            return keys();
        } else {
            throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path);
        }
    }

    @Override
    public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        boolean hasValue = Double.isInfinite(value) == false;
        builder.field(CommonFields.VALUE.getPreferredName(), hasValue ? value : null);
        if (hasValue && format != DocValueFormat.RAW) {
            builder.field(CommonFields.VALUE_AS_STRING.getPreferredName(), format.format(value).toString());
        }
        builder.startArray(KEYS_FIELD.getPreferredName());
        for (String key : keys) {
            builder.value(key);
        }
        builder.endArray();
        return builder;
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), value, Arrays.hashCode(keys));
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        if (super.equals(obj) == false) return false;
        InternalBucketMetricValue other = (InternalBucketMetricValue) obj;
        return Objects.equals(value, other.value) && Arrays.equals(keys, other.keys);
    }
}


text:
require 'test_helper'

class ConfirmationTest < ActionController::IntegrationTest

  def visit_user_confirmation_with_token(confirmation_token)
    visit user_confirmation_path(:confirmation_token => confirmation_token)
  end

  def resend_confirmation
    user = create_user(:confirm => false)
    ActionMailer::Base.deliveries.clear

    visit new_user_session_path
    click_link "Didn't receive confirmation instructions?"

    fill_in 'email', :with => user.email
    click_button 'Resend confirmation instructions'
  end

  test 'user should be able to request a new confirmation' do
    resend_confirmation

    assert_current_url '/users/sign_in'
    assert_contain 'You will receive an email with instructions about how to confirm your account in a few minutes'
    assert_equal 1, ActionMailer::Base.deliveries.size
    assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from
  end

  test 'user should receive a confirmation from a custom mailer' do
    User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)

    resend_confirmation

    assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from
  end

  test 'user with invalid confirmation token should not be able to confirm an account' do
    visit_user_confirmation_with_token('invalid_confirmation')
    assert_have_selector '#error_explanation'
    assert_contain /Confirmation token(.*)invalid/
  end

  test 'user with valid confirmation token should be able to confirm an account' do
    user = create_user(:confirm => false)
    assert_not user.confirmed?
    visit_user_confirmation_with_token(user.confirmation_token)

    assert_contain 'Your account was successfully confirmed.'
    assert_current_url '/'
    assert user.reload.confirmed?
  end

  test 'user with valid confirmation token should not be able to confirm an account after the token has expired' do
    swap Devise, :confirm_within => 3.days do
      user = create_user(:confirm => false, :confirmation_sent_at => 4.days.ago)
      assert_not user.confirmed?
      visit_user_confirmation_with_token(user.confirmation_token)

      assert_have_selector '#error_explanation'
      assert_contain /needs to be confirmed within 3 days/
      assert_not user.reload.confirmed?
    end
  end

  test 'user with valid confirmation token should be able to confirm an account before the token has expired' do
    swap Devise, :confirm_within => 3.days do
      user = create_user(:confirm => false, :confirmation_sent_at => 2.days.ago)
      assert_not user.confirmed?
      visit_user_confirmation_with_token(user.confirmation_token)

      assert_contain 'Your account was successfully confirmed.'
      assert_current_url '/'
      assert user.reload.confirmed?
    end
  end

  test 'user should be redirected to a custom path after confirmation' do
    Devise::ConfirmationsController.any_instance.stubs(:after_confirmation_path_for).returns("/?custom=1")

    user = create_user(:confirm => false)
    visit_user_confirmation_with_token(user.confirmation_token)

    assert_current_url "/?custom=1"
  end

  test 'already confirmed user should not be able to confirm the account again' do
    user = create_user(:confirm => false)
    user.confirmed_at = Time.now
    user.save
    visit_user_confirmation_with_token(user.confirmation_token)

    assert_have_selector '#error_explanation'
    assert_contain 'already confirmed'
  end

  test 'already confirmed user should not be able to confirm the account again neither request confirmation' do
    user = create_user(:confirm => false)
    user.confirmed_at = Time.now
    user.save

    visit_user_confirmation_with_token(user.confirmation_token)
    assert_contain 'already confirmed'

    fill_in 'email', :with => user.email
    click_button 'Resend confirmation instructions'
    assert_contain 'already confirmed'
  end

  test 'sign in user automatically after confirming its email' do
    user = create_user(:confirm => false)
    visit_user_confirmation_with_token(user.confirmation_token)

    assert warden.authenticated?(:user)
  end

  test 'increases sign count when signed in through confirmation' do
    user = create_user(:confirm => false)
    visit_user_confirmation_with_token(user.confirmation_token)

    user.reload
    assert_equal 1, user.sign_in_count
  end

  test 'not confirmed user with setup to block without confirmation should not be able to sign in' do
    swap Devise, :allow_unconfirmed_access_for => 0.days do
      sign_in_as_user(:confirm => false)

      assert_contain 'You have to confirm your account before continuing'
      assert_not warden.authenticated?(:user)
    end
  end

  test 'not confirmed user should not see confirmation message if invalid credentials are given' do
    swap Devise, :allow_unconfirmed_access_for => 0.days do
      sign_in_as_user(:confirm => false) do
        fill_in 'password', :with => 'invalid'
      end

      assert_contain 'Invalid email or password'
      assert_not warden.authenticated?(:user)
    end
  end

  test 'not confirmed user but configured with some days to confirm should be able to sign in' do
    swap Devise, :allow_unconfirmed_access_for => 1.day do
      sign_in_as_user(:confirm => false)

      assert_response :success
      assert warden.authenticated?(:user)
    end
  end

  test 'error message is configurable by resource name' do
    store_translations :en, :devise => {
      :failure => { :user => { :unconfirmed => "Not confirmed user" } }
    } do
      sign_in_as_user(:confirm => false)
      assert_contain 'Not confirmed user'
    end
  end

  test 'resent confirmation token with valid E-Mail in XML format should return valid response' do
    user = create_user(:confirm => false)
    post user_confirmation_path(:format => 'xml'), :user => { :email => user.email }
    assert_response :success
    assert_equal response.body, {}.to_xml
  end

  test 'resent confirmation token with invalid E-Mail in XML format should return invalid response' do
    user = create_user(:confirm => false)
    post user_confirmation_path(:format => 'xml'), :user => { :email => 'invalid.test@test.com' }
    assert_response :unprocessable_entity
    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
  end

  test 'confirm account with valid confirmation token in XML format should return valid response' do
    user = create_user(:confirm => false)
    get user_confirmation_path(:confirmation_token => user.confirmation_token, :format => 'xml')
    assert_response :success
    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
  end

  test 'confirm account with invalid confirmation token in XML format should return invalid response' do
    user = create_user(:confirm => false)
    get user_confirmation_path(:confirmation_token => 'invalid_confirmation', :format => 'xml')
    assert_response :unprocessable_entity
    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
  end

  test 'request an account confirmation account with JSON, should return an empty JSON' do
    user = create_user(:confirm => false)

    post user_confirmation_path, :user => { :email => user.email }, :format => :json
    assert_response :success
    assert_equal response.body, {}.to_json
  end

  test "when in paranoid mode and with a valid e-mail, should not say that the e-mail is valid" do
    swap Devise, :paranoid => true do
      user = create_user(:confirm => false)
      visit new_user_session_path

      click_link "Didn't receive confirmation instructions?"
      fill_in 'email', :with => user.email
      click_button 'Resend confirmation instructions'

      assert_contain "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
      assert_current_url "/users/sign_in"
    end
  end

  test "when in paranoid mode and with a invalid e-mail, should not say that the e-mail is invalid" do
    swap Devise, :paranoid => true do
      visit new_user_session_path

      click_link "Didn't receive confirmation instructions?"
      fill_in 'email', :with => "idonthavethisemail@gmail.com"
      click_button 'Resend confirmation instructions'

      assert_not_contain "1 error prohibited this user from being saved:"
      assert_not_contain "Email not found"

      assert_contain "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
      assert_current_url "/users/sign_in"
    end
  end
end

class ConfirmationOnChangeTest < ActionController::IntegrationTest
  def create_second_admin(options={})
    @admin = nil
    create_admin(options)
  end

  def visit_admin_confirmation_with_token(confirmation_token)
    visit admin_confirmation_path(:confirmation_token => confirmation_token)
  end

  test 'admin should be able to request a new confirmation after email changed' do
    admin = create_admin
    admin.update_attributes(:email => 'new_test@example.com')

    visit new_admin_session_path
    click_link "Didn't receive confirmation instructions?"

    fill_in 'email', :with => admin.unconfirmed_email
    assert_difference "ActionMailer::Base.deliveries.size" do
      click_button 'Resend confirmation instructions'
    end

    assert_current_url '/admin_area/sign_in'
    assert_contain 'You will receive an email with instructions about how to confirm your account in a few minutes'
  end

  test 'admin with valid confirmation token should be able to confirm email after email changed' do
    admin = create_admin
    admin.update_attributes(:email => 'new_test@example.com')
    assert_equal 'new_test@example.com', admin.unconfirmed_email
    visit_admin_confirmation_with_token(admin.confirmation_token)

    assert_contain 'Your account was successfully confirmed.'
    assert_current_url '/admin_area/home'
    assert admin.reload.confirmed?
    assert_not admin.reload.pending_reconfirmation?
  end

  test 'admin with previously valid confirmation token should not be able to confirm email after email changed again' do
    admin = create_admin
    admin.update_attributes(:email => 'first_test@example.com')
    assert_equal 'first_test@example.com', admin.unconfirmed_email

    confirmation_token = admin.confirmation_token
    admin.update_attributes(:email => 'second_test@example.com')
    assert_equal 'second_test@example.com', admin.unconfirmed_email

    visit_admin_confirmation_with_token(confirmation_token)
    assert_have_selector '#error_explanation'
    assert_contain /Confirmation token(.*)invalid/

    visit_admin_confirmation_with_token(admin.confirmation_token)
    assert_contain 'Your account was successfully confirmed.'
    assert_current_url '/admin_area/home'
    assert admin.reload.confirmed?
    assert_not admin.reload.pending_reconfirmation?
  end

  test 'admin email should be unique also within unconfirmed_email' do
    admin = create_admin
    admin.update_attributes(:email => 'new_admin_test@example.com')
    assert_equal 'new_admin_test@example.com', admin.unconfirmed_email

    create_second_admin(:email => "new_admin_test@example.com")

    visit_admin_confirmation_with_token(admin.confirmation_token)
    assert_have_selector '#error_explanation'
    assert_contain /Email.*already.*taken/
    assert admin.reload.pending_reconfirmation?
  end
end


text:
/** @file types.h
 *
 *	Commonly Used Type Definitions
 *
 *	## Includes
 *	* The integer types: `int8_t`, `int16_t`, `int32_t`, and `int64_t`
 *	* Limits for the integer types
 *	* `bool`, `true`, `false`
 *	* `NULL`
 *	* size_t
 *	* `uchar`, `uint`, `umax`, and `imax`
 */

#ifndef _TYPES_H
#define _TYPES_H

#ifdef __cplusplus
	extern "C" {
#endif

#include <stdint.h>
#include <limits.h>
#include <stdbool.h>
// size_t NULL
#include <stddef.h>

/// The largest signed integer for a given architecture
typedef long long int imax;

#define IMAX_MAX ((size_t)LLONG_MAX) ///< the maximum value of `imax`
#define IMAX_MIN ((size_t)LLONG_MIN) ///< the minimum value of `imax`

// Unsigned
/// The largest unsigned integer for a given architecture
typedef unsigned long long int umax;
typedef unsigned int  uint; ///< a naturally sized unsigned integer
typedef unsigned char uchar; ///< an unsigned character

#define UMAX_MAX ((size_t)ULLONG_MAX) ///< the maximum value of `umax`
// UINT_MAX is defined in limits.h
// UCHAR_MAX is defined in limits.h

/// A type to simply indicate success or failure
typedef enum{
	r_success, ///< indicates the function call was successful
	r_failure  ///< indicates the function call failed
} return_t;

/**	RETURN can be used as the return type of a function so that a warning is
 *	issued if the return value is ignored.
 */
#define RETURN return_t __attribute__((warn_unused_result))

#ifdef __cplusplus
	}
#endif

#endif // _TYPES_H


text:
<?php
namespace Chamilo\Core\Repository\Implementation\Photobucket\Integration\Chamilo\Core\Menu\Package;

class Installer extends \Chamilo\Configuration\Package\Action\Installer
{
}


text:
<?php
use Oasis\Mlib\Utils\Exceptions\DataValidationException;
use Oasis\Mlib\Utils\Validators\StringValidator;

/**
 * Created by PhpStorm.
 * User: minhao
 * Date: 2016-09-02
 * Time: 16:35
 */
class StringValidatorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getValidDataForNonStrictMode
     *
     * @param $target
     */
    public function testNonStrictInputWithValidInput($target)
    {
        $validator = new StringValidator();
        $this->assertTrue(is_string($validator->validate($target)));
    }

    /**
     * @dataProvider getInvalidDataForNonStrictMode
     *
     * @param $target
     */
    public function testNonStrictInputWithInvalidInput($target)
    {
        $validator = new StringValidator();
        $this->expectException(DataValidationException::class);
        $this->assertTrue(is_string($validator->validate($target)));
    }

    /**
     * @dataProvider getValidDataForStrictMode
     *
     * @param $target
     */
    public function testStrictInputWithValidInput($target)
    {
        $validator = new StringValidator(true);
        $this->assertTrue(is_string($validator->validate($target)));
    }

    /**
     * @dataProvider getInvalidDataForStrictMode
     *
     * @param $target
     */
    public function testStrictInputWithInvalidInput($target)
    {
        $validator = new StringValidator(true);
        $this->expectException(DataValidationException::class);
        $this->assertTrue(is_string($validator->validate($target)));
    }

    /**
     * @dataProvider getValidDataForStrictModeWithEmptyNotAllowed
     *
     * @param $target
     */
    public function testStrictInputWithEmptyNotAllowed($target)
    {
        $validator = new StringValidator(true, false);
        $this->assertTrue(is_string($validator->validate($target)));
    }

    /**
     * @dataProvider getInvalidDataForStrictModeWithEmptyNotAllowed
     *
     * @param $target
     */
    public function testStrictInputWithInvalidInputEmptyNotAllowed($target)
    {
        $validator = new StringValidator(true, false);
        $this->expectException(DataValidationException::class);
        $this->assertTrue(is_string($validator->validate($target)));

    }

    public function getValidDataForNonStrictMode()
    {
        return [
            ["abc"],
            [""],
            [1],
            [0],
            [1.1],
            [true],
            [false],

        ];
    }

    public function getInvalidDataForNonStrictMode()
    {
        return [
            [[]],
            [['abc']],
            [new stdClass()],
            [null],
        ];
    }

    public function getValidDataForStrictMode()
    {
        return [
            ["abc"],
            [""],
        ];
    }

    public function getValidDataForStrictModeWithEmptyNotAllowed()
    {
        return [
            ["abc"],
        ];
    }

    public function getInvalidDataForStrictMode()
    {
        return [
            [1],
            [0],
            [1.1],
            [true],
            [false],
            [null],
            [[]],
            [['abc']],
            [new stdClass()],
        ];
    }

    public function getInvalidDataForStrictModeWithEmptyNotAllowed()
    {
        return [
            [""],
            [1],
            [0],
            [1.1],
            [true],
            [false],
            [null],
            [[]],
            [['abc']],
            [new stdClass()],
        ];
    }
}


text:
using NUnit.Framework;

namespace FunWithCommandLine.SubclassedOptions
{
    [TestFixture]
    public class SubclassedOptionsTests
    {
        [Test]
        public void NonVirtualOverrides_ValueSetInCtorIsOverwritten()
        {
            // Assemble
            var child = new ChildOptions();
            var expected = child.SealedOption;

            // Act
            child = OptionsHelpers.Parse(child);

            // Assert
            Assert.AreNotEqual(expected, child.SealedOption);
        }

        [Test]
        public void VirtualOverrides_OverridenDefaultIsUsed()
        {
            // Act
            var child = OptionsHelpers.Parse<ChildOptions>();

            // Assert
            Assert.AreEqual("child - virtual option", child.VirtualOption);
        }
    }
}