text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">

    <string name="button_cancel">בטל</string>
    <string name="button_enter_details">הכנס פרטים</string>
    <string name="button_scan_qr">סרוק קוד-QR</string>
    <string name="button_save">שמור</string>
    <string name="button_new_tag">תג חדש</string>
    <string name="button_settings">הגדרות</string>
    <string name="button_all_tags">כל התוויות</string>
    <string name="button_no_tags">ללא תגיות</string>
    <string name="button_qr_from_image">קוד QR מתמונה</string>
    <string name="button_accept">Accept</string>

    <string name="format_custom_period">%d שניות</string>

    <string name="hint_label">תווית</string>
    <string name="hint_secret">סוד</string>

    <string name="label_hidden">מוסתר</string>
    <string name="label_type">סוג</string>
    <string name="label_secret">סוד</string>
    <string name="label_period">תקופה</string>
    <string name="label_digits">ספרות</string>
    <string name="label_counter">מונה</string>
    <string name="label_issuer">מנפיק</string>
    <string name="label_label">תווית</string>
    <string name="label_algorithm">אלגוריתם</string>
    <string name="label_tags">תגים</string>
    <string name="label_advanced">אפשרויות מתקדמות</string>

    <string name="drawer_open">הצג תגיות</string>
    <string name="drawer_close">הסתר תגיות</string>

    <string name="menu_main_about">אודות</string>
    <string name="menu_main_backup">גיבוי</string>
    <string name="menu_main_search">חפש</string>
    <string name="menu_main_settings">הגדרות</string>
    <string name="menu_main_sort">מיון</string>
    <string name="menu_sort_none">לא ממוין</string>
    <string name="menu_sort_issuer">מנפיק</string>
    <string name="menu_sort_label">תווית</string>
    <string name="menu_sort_last_used">שימוש אחרון</string>
    <string name="menu_sort_most_used">הכי משומש</string>
    <string name="menu_popup_edit">ערוך</string>
    <string name="menu_popup_change_image">שנה תמונה</string>
    <string name="menu_popup_remove">הסר</string>
    <string name="menu_popup_show_qr_code">הצג קוד QR</string>
    <string name="menu_popup_establish_pin">Enter pin</string>
    <string name="menu_send_keystrokes">Share as Keystrokes</string>

    <string name="button_card_options">אפשרויות נוספות</string>
    <string name="button_card_options_format">אפשרויות נוספות עבור %1$s</string>
    <string name="button_card_copy">העתק אסימון</string>
    <string name="button_card_copy_format">העתק אסימון %1$s</string>
    <string name="button_add">הוסף חשבון חדש</string>
    <string name="button_close_menu">סגור תפריט</string>

    <string name="toast_auth_failed">אימות נכשל, אנא נסה שוב!</string>
    <string name="toast_auth_failed_fatal">אימות נכשל, סוגר את andOTP!</string>
    <string name="toast_copied_to_clipboard">הועתק ללוח</string>
    <string name="toast_entry_exists">ערך זה כבר קיים</string>
    <string name="toast_invalid_qr_code">קוד QR לא תקין</string>
    <string name="toast_encryption_key_empty">מפתח הצפנה לא נטען</string>
    <string name="toast_intent_creation_failed">הועבר קוד לא חוקי שנוסף על ידי הישום</string>
    <string name="toast_intent_creation_succeeded">נוסף קוד שסופק על ידי הישום</string>
    <string name="toast_file_load_error">לא היה ניתן לפתוח את הקובץ</string>
    <string name="toast_qr_error">לא היה ניתן למצוא/לאמת קוד QR</string>
    <string name="toast_qr_checksum_exception">אימות סכום הבדיקה נכשל בעת פענוח קוד QR</string>
    <string name="toast_qr_format_error">שגיאת פורמט בקוד QR</string>
    <string name="toast_qr_unsuported">קוד QR אינו נתמך</string>
    <string name="toast_qr_failed_to_generate">יצירת קוד QR נכשלה</string>

    <string name="error_invalid_secret">סוד לא חוקי</string>

    <string name="dialog_title_auth">אימות</string>
    <string name="dialog_title_manual_entry">הכנס פרטים</string>
    <string name="dialog_title_remove">הסר</string>
    <string name="dialog_title_rename">שנה שם</string>
    <string name="dialog_title_counter">מונה</string>
    <string name="dialog_title_used_tokens">שימוש באסימונים</string>
    <string name="dialog_title_keystore_error">שגיאת KeyStore</string>
    <string name="dialog_title_qr_code">קוד QR</string>
    <string name="dialog_title_pin">PIN</string>
    <string name="dialog_title_enter_password">הכנס סיסמה</string>
    <string name="dialog_title_auto_time">Automatic time</string>
    <string name="dialog_label_enter_password">הכנס סיסמה</string>
    <string name="dialog_label_confirm_password">אשר סיסמה</string>
    <string name="dialog_msg_auth">אנא הכנס את האישורים המזהים של מכשירך כדי להפעיל את andOTP.</string>
    <string name="dialog_msg_confirm_delete">האם אתה בטוח שברצונך להסיר את החשבון \"%1$s\"?</string>
    <string name="dialog_msg_used_tokens">andOTP יעקוב אחר השימוש באסימונים שלך (באמצעות הפיטצ\'ר \"הקש
        כדי לחשוף\" או העתקה ללוח) כדי להיות מסוגל למיין אותם לפי \"הנפוץ ביותר\" או
        \"נעשה שימוש אחרון\".\n\nהודעה זו לא תוצג שוב.</string>
    <string name="dialog_msg_keystore_error">טעינת מפתח ההצפנה מ- KeyStore נכשלה.
        כל חשבון שנוסף יאבד.\n\nכדי שתוכל עדיין להשתמש ב- andOTP, אתה יכול לגשת
        להגדרות ולהחליף את הצפנת מסד הנתונים לסיסמה / קוד PIN.</string>
    <string name="dialog_msg_auto_time">Please enable the Automatic date & time option in
        your phones Settings to ensure the correct generation of time-based
        one-time-passwords (TOTP).</string>
    <string name="dialog_hint_dont_show_again">Don\'t show this message again.</string>
    <string name="yes">Yes</string>
    <string name="no">No</string>

    <string name="shortcut_name_scan_qr">סרוק קוד-QR</string>
    <string name="shortcut_name_import_qr">ייבא קוד QR</string>
    <string name="shortcut_name_enter_details">הכנס פרטים</string>

    <string name="empty_list_view_text">Start adding your tokens by pressing \"+\" at the bottom</string>
</resources>


text:
<include file="Public:head"/>

修改相册
返回

          <form method="post" action="">

*相册名称:
<input type="text" name="title" value="{Saivi:$photo.title}" class="px" style="width:400px;" id="name" onkeyup="DivFollowingText1()">

尽量简单,不要超过20字.

<div class="chatItem you" id="photo1" style="width:350px;" <if condition="$photo['isshowinfo'] eq 1">display:none<else/> </if>>

{Saivi:$photo.title}

{Saivi:$photo.info}

查看全文

<div class="chatItem you" id="photo2" style="<if condition="$photo['isshowinfo'] eq 0">display:none<else/> </if>">

{Saivi:$photo.title}

*相册封面图:	<input type="hidden" name="id" value="{Saivi:$photo.id}" />
<input type="text" name="picurl" value="{Saivi:$photo.picurl}" class="px" style="width:400px;" id="pic" onblur="document.getElementById('pic_src').src=document.getElementById('pic').value;document.getElementById('zpic2').src=document.getElementById('pic').value;" onchange="document.getElementById('pic_src').src=document.getElementById('pic').value;document.getElementById('zpic2').src=document.getElementById('pic').value;">

上传 预览

   相册介绍:

		<textarea class="px" id="info" name="info" style="width:400px; height:120px" onkeyup="DivFollowingText2()">{Saivi:$photo.info}</textarea>

		请简单描述相册内容,尽量控制在150文字以内。

			<input name="isshowinfo" <if condition="$photo['isshowinfo'] eq 0">checked="checked"</if> type="radio" id="RadioGroup0_0" value="0" checked="checked" onclick="document.getElementById('photo2').style.display='none';document.getElementById('photo1').style.display='';">
			显示简介

			<input type="radio" <if condition="$photo['isshowinfo'] eq 1">checked="checked"</if> name="isshowinfo" value="1" id="RadioGroup0_1" onclick="document.getElementById('photo1').style.display='none';document.getElementById('photo2').style.display='';">
			不显示简介

是否显示:

	<select name="status">
	<option value="1" <if condition="$photo['status'] eq 1"> selected</if>>显示此相册</option>
	<option value="0" <if condition="$photo['status'] eq 0"> selected</if>>不显示此相册</option>
	</select>

		<button type="submit" name="button" class="btn btn-primary btn_submit  J_ajax_submit_btn">保存</button>
		取消

          </form>

<include file="Public:footer"/>

redpajama_set_name: RedPajamaGithub


text:
import { shallow } from 'enzyme';
import { containerWithStore, containerProps } from 'helpers/store';
import TodoModal from '../';

describe('TodoModal', () => {
  let props;
  let component;
  const renderComponent = () => shallow(containerWithStore(TodoModal, {}, props));

  beforeEach(() => {
    props = {
      closeModal: () => {},
      isOpen: true,
    };
  });

  it('renders TodoModal component', () => {
    component = renderComponent().find('TodoModal');
    const todoModalProps = containerProps(component);

    expect(component).toBePresent();
    expect(todoModalProps).toEqual(['closeModal', 'isOpen', 'createTodo']);
  });
});


text:
import os

# yapf: disable
# __sphinx_doc_begin__
# (Optional/Auto-filled) training is terminated. Filled only if not provided.
DONE = "done"

# (Optional) Enum for user controlled checkpoint
SHOULD_CHECKPOINT = "should_checkpoint"

# (Auto-filled) The hostname of the machine hosting the training process.
HOSTNAME = "hostname"

# (Auto-filled) The auto-assigned id of the trial.
TRIAL_ID = "trial_id"

# (Auto-filled) The auto-assigned id of the trial.
EXPERIMENT_TAG = "experiment_tag"

# (Auto-filled) The node ip of the machine hosting the training process.
NODE_IP = "node_ip"

# (Auto-filled) The pid of the training process.
PID = "pid"

# (Optional) Mean reward for current training iteration
EPISODE_REWARD_MEAN = "episode_reward_mean"

# (Optional) Mean loss for training iteration
MEAN_LOSS = "mean_loss"

# (Optional) Mean accuracy for training iteration
MEAN_ACCURACY = "mean_accuracy"

# Number of episodes in this iteration.
EPISODES_THIS_ITER = "episodes_this_iter"

# (Optional/Auto-filled) Accumulated number of episodes for this trial.
EPISODES_TOTAL = "episodes_total"

# Number of timesteps in this iteration.
TIMESTEPS_THIS_ITER = "timesteps_this_iter"

# (Auto-filled) Accumulated number of timesteps for this entire trial.
TIMESTEPS_TOTAL = "timesteps_total"

# (Auto-filled) Time in seconds this iteration took to run.
# This may be overriden to override the system-computed time difference.
TIME_THIS_ITER_S = "time_this_iter_s"

# (Auto-filled) Accumulated time in seconds for this entire trial.
TIME_TOTAL_S = "time_total_s"

# (Auto-filled) The index of this training iteration.
TRAINING_ITERATION = "training_iteration"
# __sphinx_doc_end__
# yapf: enable

DEFAULT_EXPERIMENT_INFO_KEYS = ("trainable_name", EXPERIMENT_TAG, TRIAL_ID)

DEFAULT_RESULT_KEYS = (TRAINING_ITERATION, TIME_TOTAL_S, TIMESTEPS_TOTAL,
                       MEAN_ACCURACY, MEAN_LOSS)

# __duplicate__ is a magic keyword used internally to
# avoid double-logging results when using the Function API.
RESULT_DUPLICATE = "__duplicate__"

# Where Tune writes result files by default
DEFAULT_RESULTS_DIR = (os.environ.get("TEST_TMPDIR")
                       or os.environ.get("TUNE_RESULT_DIR")
                       or os.path.expanduser("~/ray_results"))

# Meta file about status under each experiment directory, can be
# parsed by automlboard if exists.
JOB_META_FILE = "job_status.json"

# Meta file about status under each trial directory, can be parsed
# by automlboard if exists.
EXPR_META_FILE = "trial_status.json"

# File that stores parameters of the trial.
EXPR_PARAM_FILE = "params.json"

# Pickle File that stores parameters of the trial.
EXPR_PARAM_PICKLE_FILE = "params.pkl"

# File that stores the progress of the trial.
EXPR_PROGRESS_FILE = "progress.csv"

# File that stores results of the trial.
EXPR_RESULT_FILE = "result.json"

# Config prefix when using Analysis.
CONFIG_PREFIX = "config/"


text:
class Presentation < ActiveRecord::Base
  belongs_to :activity

  validates :event_date, :rn_participants, :all_participants, presence: true
  validates :rn_participants, :all_participants, numericality: { greater_than_or_equal_to: 0, only_integer: true }
  validate  :validate_dates

  def chronic_event_date
    event_date.strftime("%m/%d/%Y") if event_date
  end
  def chronic_event_date=(str)
    self.event_date = Chronic.parse(str)
    unless str.blank?
      @event_date_invalid = true if self.event_date.nil?
    end
  end

  private

  def validate_dates
    errors.add(:event_date, "is invalid") if @event_date_invalid
  end
end


text:
package com.amazonaws.services.databasemigrationservice.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeEventSubscriptionsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * An optional pagination token provided by a previous request. If this parameter is specified, the response
     * includes only records beyond the marker, up to the value specified by MaxRecords.
     *

     */
    private String marker;
    /**
     *

     * A list of event subscriptions.
     *

     */
    private java.util.List<EventSubscription> eventSubscriptionsList;

    /**
     *

     * An optional pagination token provided by a previous request. If this parameter is specified, the response
     * includes only records beyond the marker, up to the value specified by MaxRecords.
     *

     *
     * @param marker
     *        An optional pagination token provided by a previous request. If this parameter is specified, the response
     *        includes only records beyond the marker, up to the value specified by MaxRecords.
     */

    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     *

     * An optional pagination token provided by a previous request. If this parameter is specified, the response
     * includes only records beyond the marker, up to the value specified by MaxRecords.
     *

     *
     * @return An optional pagination token provided by a previous request. If this parameter is specified, the response
     *         includes only records beyond the marker, up to the value specified by MaxRecords.
     */

    public String getMarker() {
        return this.marker;
    }

    /**
     *

     * An optional pagination token provided by a previous request. If this parameter is specified, the response
     * includes only records beyond the marker, up to the value specified by MaxRecords.
     *

     *
     * @param marker
     *        An optional pagination token provided by a previous request. If this parameter is specified, the response
     *        includes only records beyond the marker, up to the value specified by MaxRecords.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeEventSubscriptionsResult withMarker(String marker) {
        setMarker(marker);
        return this;
    }

    /**
     *

     * A list of event subscriptions.
     *

     *
     * @return A list of event subscriptions.
     */

    public java.util.List<EventSubscription> getEventSubscriptionsList() {
        return eventSubscriptionsList;
    }

    /**
     *

     * A list of event subscriptions.
     *

     *
     * @param eventSubscriptionsList
     *        A list of event subscriptions.
     */

    public void setEventSubscriptionsList(java.util.Collection<EventSubscription> eventSubscriptionsList) {
        if (eventSubscriptionsList == null) {
            this.eventSubscriptionsList = null;
            return;
        }

        this.eventSubscriptionsList = new java.util.ArrayList<EventSubscription>(eventSubscriptionsList);
    }

    /**
     *

     * A list of event subscriptions.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setEventSubscriptionsList(java.util.Collection)} or
     * {@link #withEventSubscriptionsList(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param eventSubscriptionsList
     *        A list of event subscriptions.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeEventSubscriptionsResult withEventSubscriptionsList(EventSubscription... eventSubscriptionsList) {
        if (this.eventSubscriptionsList == null) {
            setEventSubscriptionsList(new java.util.ArrayList<EventSubscription>(eventSubscriptionsList.length));
        }
        for (EventSubscription ele : eventSubscriptionsList) {
            this.eventSubscriptionsList.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of event subscriptions.
     *

     *
     * @param eventSubscriptionsList
     *        A list of event subscriptions.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeEventSubscriptionsResult withEventSubscriptionsList(java.util.Collection<EventSubscription> eventSubscriptionsList) {
        setEventSubscriptionsList(eventSubscriptionsList);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getMarker() != null)
            sb.append("Marker: ").append(getMarker()).append(",");
        if (getEventSubscriptionsList() != null)
            sb.append("EventSubscriptionsList: ").append(getEventSubscriptionsList());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeEventSubscriptionsResult == false)
            return false;
        DescribeEventSubscriptionsResult other = (DescribeEventSubscriptionsResult) obj;
        if (other.getMarker() == null ^ this.getMarker() == null)
            return false;
        if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false)
            return false;
        if (other.getEventSubscriptionsList() == null ^ this.getEventSubscriptionsList() == null)
            return false;
        if (other.getEventSubscriptionsList() != null && other.getEventSubscriptionsList().equals(this.getEventSubscriptionsList()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
        hashCode = prime * hashCode + ((getEventSubscriptionsList() == null) ? 0 : getEventSubscriptionsList().hashCode());
        return hashCode;
    }

    @Override
    public DescribeEventSubscriptionsResult clone() {
        try {
            return (DescribeEventSubscriptionsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
var express = require('express');
var router = express.Router();
var Account = global.db.Account;
var AccessKey = global.db.AccessKey;
var Channel = global.db.Channel;
var Message = global.db.Message;
var AccountInGroup = global.db.AccountInGroup;
var AccountInChannel = global.db.AccountInChannel;
var Random = require(__dirname + "/../../util/random");
var socket = global.socket;
var ERROR_NOTACCESSIBLE = "ERROR_NOTACCESSIBLE";
var ERROR_NOTFOUND = "ERROR_NOTFOUND";
var ERROR_DUPLICATED = "ERROR_DUPLICATED";
var loadAccountAndCheckJoinSameGroup = function(sessionKey, targetAccountId) {
	var loadedAccount;
	return AccessKey.findBySessionKey(sessionKey).then(function(accessKey) {
		if (!accessKey) {
			throw ERROR_NOTACCESSIBLE;
		}
		return Account.findById(accessKey.AccountId);
	}).then(function(account) {
		if (!account) {
			throw ERROR_NOTACCESSIBLE;
		}
		loadedAccount = account;
		return AccountInGroup.findAll({
			where : {
				AccountId : loadedAccount.id
			}
		});
	}).then(function(ownerAccountInGroups) {
		if (0 == ownerAccountInGroups.length) {
			throw ERROR_NOTACCESSIBLE
		}
		var ownerJoiningGroupIds = ownerAccountInGroups.map(function(ownerAccountInGroup) {
			return ownerAccountInGroup.GroupId;
		});
		return AccountInGroup.findAll({
			where : {
				AccountId : parseInt(targetAccountId),
				GroupId : {
					$in : ownerJoiningGroupIds
				},
			}
		});
	}).then(function(accountInGroups) {
		return new Promise(function(success, fail) {
			if (!accountInGroups || 0 == accountInGroups.length) {
				fail(ERROR_NOTACCESSIBLE)
			} else {
				success(loadedAccount);
			}
		});
	})
}
router.post('/', function(req, res) {
	var sessionKey = req.body.sessionKey || req.body.access_token;
	if (!sessionKey) {
		res.status(400).end();
		return;
	}
	if (!req.body.name || !req.body.targetAccountId || !parseInt(req.body.targetAccountId)) {
		res.status(400).end();
		return;
	}
	var createdChannel;
	var loadedAccount;
	loadAccountAndCheckJoinSameGroup(sessionKey, req.body.targetAccountId).then(function(account) {
		loadedAccount = account;
		return Random.createRandomBase62();
	}).then(function(random) {
		return Channel.create({
			ownerId : loadedAccount.id,
			accessKey : random,
			name : req.body.name,
			type : Channel.TYPE_PRIVATE
		});
	}).then(function(channel) {
		createdChannel = channel;
		createdChannel.dataValues.owner = loadedAccount;
		return AccountInChannel.create({
			ChannelId : createdChannel.id,
			AccountId : loadedAccount.id,
			type : AccountInChannel.TYPE_JOIN
		});
	}).then(function() {
		return AccountInChannel.create({
			ChannelId : createdChannel.id,
			AccountId : parseInt(req.body.targetAccountId),
			type : AccountInChannel.TYPE_JOIN
		});
	}).then(function() {
		res.status(201).json(createdChannel);
		socket.sendAppendsChannelEvent(req.body.targetAccountId, loadedAccount, createdChannel);
	})["catch"](function(error) {
		if (ERROR_NOTACCESSIBLE == error) {
			res.status(403).end();
		} else {
			console.log(error.stack);
			res.status(500).end();
		}
	});
});
router.post("/:channelAccessKey/invite", function(req, res) {
	var sessionKey = req.body.sessionKey || req.body.access_token;
	if (!sessionKey) {
		res.status(400).end();
		return;
	}
	if (!req.params.channelAccessKey || !req.body.targetAccountId || !parseInt(req.body.targetAccountId)) {
		res.status(400).end();
		return;
	}
	var loadedChannel;
	var loadedAccount;
	loadAccountAndCheckJoinSameGroup(sessionKey, req.body.targetAccountId).then(function(account) {
		loadedAccount = account;
		return Channel.find({
			where : {
				accessKey : req.params.channelAccessKey
			}
		});
	}).then(function(channel) {
		if (!channel) {
			throw ERROR_NOTFOUND;
		}
		loadedChannel = channel;
		return AccountInChannel.find({
			ChannelId : loadedChannel.id,
			AccountId : loadedAccount.id,
			type : AccountInChannel.TYPE_JOIN
		});
	}).then(function(accountInChannel) {
		if (!accountInChannel) {
			throw ERROR_NOTACCESSIBLE;
		}
		return AccountInChannel.find({
			where : {
				ChannelId : loadedChannel.id,
				AccountId : parseInt(req.body.targetAccountId),
				type : AccountInChannel.TYPE_JOIN
			}
		});
	}).then(function(accountInChannel) {
		if (accountInChannel) {
			throw ERROR_DUPLICATED;
		}
		return AccountInChannel.create({
			ChannelId : loadedChannel.id,
			AccountId : parseInt(req.body.targetAccountId),
			type : AccountInChannel.TYPE_JOIN
		});
	}).then(function() {
		res.status(201).json(loadedChannel);
		socket.sendAppendsChannelEvent(req.body.targetAccountId, loadedAccount, loadedChannel);
	})["catch"](function(error) {
		if (ERROR_NOTACCESSIBLE == error) {
			res.status(403).end();
		} else if (ERROR_NOTFOUND == error) {
			res.status(404).end();
		} else if (ERROR_DUPLICATED == error) {
			res.status(409).end();
		} else {
			console.log(error.stack);
			res.status(500).end();
		}
	});
})
router.post('/:channelAccessKey/messages', function(req, res) {
	var sessionKey = req.body.sessionKey || req.body.access_token;
	if (!sessionKey) {
		res.status(400).end();
		return;
	}
	if (!req.params.channelAccessKey || !req.body.body) {
		res.status(400).end();
		return;
	}
	Channel.loadAccessibleChannel(sessionKey, req.params.channelAccessKey).then(function(result) {
		return Message.handleMessage(result.account, result.channel, req.body.body);
	}).then(function(result) {
		res.status(201).json(result);
	})["catch"](function(error) {
		if (ERROR_NOTACCESSIBLE == error) {
			res.status(403).end();
		} else if (ERROR_NOTFOUND == error) {
			res.status(404).end();
		} else {
			console.log(error.stack);
			res.status(500).end();
		}
	});
});
var startOrStopTalking = function(req, res, start) {
	var sendFunc = start ? "sendStartTalking" : "sendStopTalking";
	var sessionKey = req.body.sessionKey || req.body.access_token;
	if (!sessionKey) {
		res.status(400).end();
		return;
	}
	if (!req.params.channelAccessKey) {
		res.status(400).end();
		return;
	}
	Channel.loadAccessibleChannel(sessionKey, req.params.channelAccessKey).then(function(result) {
		return socket[sendFunc](result.channel.accessKey, result.account);
	}).then(function(result) {
		res.status(201).json(result);
	})["catch"](function(error) {
		if (ERROR_NOTACCESSIBLE == error) {
			res.status(403).end();
		} else if (ERROR_NOTFOUND == error) {
			res.status(404).end();
		} else {
			console.log(error.stack);
			res.status(500).end();
		}
	});
}
router.put('/:channelAccessKey/messages/startTalking', function(req, res) {
	startOrStopTalking(req, res, true);
})
router.put('/:channelAccessKey/messages/stopTalking', function(req, res) {
	startOrStopTalking(req, res, false);
})
router.put('/:channelAccessKey/away', function(req, res) {
	var sessionKey = req.body.sessionKey;
	if (!sessionKey) {
		res.status(400).end();
		return;
	}
	if (!req.params.channelAccessKey) {
		res.status(400).end();
		return;
	}
	var loadedAccount;
	var loadedChannel;
	AccessKey.findBySessionKey(sessionKey).then(function(accessKey) {
		if (!accessKey) {
			throw ERROR_NOTACCESSIBLE;
		}
		return Account.findById(accessKey.AccountId);
	}).then(function(account) {
		if (!account) {
			throw ERROR_NOTACCESSIBLE;
		}
		loadedAccount = account;
		return Channel.find({
			where : {
				accessKey : req.params.channelAccessKey
			}
		});
	}).then(function(channel) {
		if (!channel) {
			throw ERROR_NOTFOUND;
		}
		loadedChannel = channel;
		return AccountInChannel.find({
			where : {
				ChannelId : loadedChannel.id,
				AccountId : loadedAccount.id
			}
		})
	}).then(function(accountInChannel) {
		if (Channel.TYPE_PRIVATE == loadedChannel.type) {
			if (!accountInChannel) {
				throw ERROR_NOTFOUND;
			}
			return accountInChannel.destroy();
		} else {
			if (accountInChannel && AccountInChannel.TYPE_AWAY == accountInChannel.type) {
				throw ERROR_NOTACCESSIBLE;
			}
			return AccountInChannel.create({
				AccountId : loadedAccount.id,
				ChannelId : loadedChannel.id,
				type : AccountInChannel.TYPE_AWAY
			});
		}
	}).then(function() {
		res.status(200).end();
	})["catch"](function(error) {
		if (ERROR_NOTACCESSIBLE == error) {
			res.status(403).end();
		} else if (ERROR_NOTFOUND == error) {
			res.status(404).end();
		} else {
			console.log(error.stack);
			res.status(500).end();
		}
	});
});
module.exports = router;


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AWSS3CreateBucketConfiguration.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AWSS3CreateBucketConfiguration</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>AWSS3Model.h</DeclaredIn>

			<NodeRef refid="1066"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSS3CreateBucketConfiguration/setLocationConstraint:</TokenIdentifier>
			<Abstract type="html">Specifies the region where the bucket will be created. If you don't specify a region, the bucket will be created in US Standard.</Abstract>
			<DeclaredIn>AWSS3Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, assign) AWSS3BucketLocationConstraint locationConstraint</Declaration>

			<Anchor>//api/name/locationConstraint</Anchor>
            <NodeRef refid="1066"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSS3CreateBucketConfiguration/locationConstraint</TokenIdentifier>
			<Abstract type="html">Specifies the region where the bucket will be created. If you don't specify a region, the bucket will be created in US Standard.</Abstract>
			<DeclaredIn>AWSS3Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, assign) AWSS3BucketLocationConstraint locationConstraint</Declaration>

			<Anchor>//api/name/locationConstraint</Anchor>
            <NodeRef refid="1066"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSS3CreateBucketConfiguration/locationConstraint</TokenIdentifier>
			<Abstract type="html">Specifies the region where the bucket will be created. If you don't specify a region, the bucket will be created in US Standard.</Abstract>
			<DeclaredIn>AWSS3Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, assign) AWSS3BucketLocationConstraint locationConstraint</Declaration>

			<Anchor>//api/name/locationConstraint</Anchor>
            <NodeRef refid="1066"/>
		</Token>

	</File>
</Tokens>


text:
package com.netflix.spectator.tdigest;

import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.ManualClock;
import com.typesafe.config.ConfigFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.concurrent.atomic.AtomicInteger;

@RunWith(JUnit4.class)
public class TDigestRegistryTest {

  private final ManualClock clock = new ManualClock();
  private final DefaultRegistry registry = new DefaultRegistry(clock);
  private final TDigestConfig config = new TDigestConfig(
      ConfigFactory.parseString("polling-frequency = 60s"));

  @Test
  public void gaugesAreRegisteredWithUnderlying() throws Exception {
    TDigestRegistry tdr = new TDigestRegistry(registry, config);
    Id id = tdr.createId("test");
    AtomicInteger value = new AtomicInteger(0);
    tdr.gauge(id, value);
    Assert.assertNotNull(registry.get(id));
  }
}


text:
<?php
namespace Aws\Test\S3;

use Aws\Command;
use Aws\Exception\AwsException;
use Aws\Result;
use Aws\S3\Exception\S3Exception;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
use Aws\Test\UsesServiceTrait;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;

/**
 * @covers Aws\S3\S3Client
 */
class S3ClientTest extends \PHPUnit_Framework_TestCase
{
    use UsesServiceTrait;

    public function testCanUseBucketEndpoint()
    {
        $c = new S3Client([
            'region'          => 'us-standard',
            'version'         => 'latest',
            'endpoint'        => 'http://test.domain.com',
            'bucket_endpoint' => true
        ]);
        $this->assertEquals(
            'http://test.domain.com/key',
            $c->getObjectUrl('test', 'key')
        );
    }

    public function bucketNameProvider()
    {
        return [
            ['.bucket', false],
            ['bucket.', false],
            ['192.168.1.1', false],
            ['1.1.1.100', false],
            ['test@42!@$5_', false],
            ['ab', false],
            ['12', false],
            ['bucket_name', false],
            ['bucket-name', true],
            ['bucket', true],
            ['my.bucket.com', true],
            ['test-fooCaps', false],
            ['w-w', true],
            ['w------', false]
        ];
    }

    /**
     * @dataProvider bucketNameProvider
     */
    public function testValidatesDnsBucketNames($bucket, $valid)
    {
        $this->assertEquals($valid, S3Client::isBucketDnsCompatible($bucket));
    }

    public function testCreatesPresignedRequests()
    {
        /** @var S3Client $client */
        $client = $this->getTestClient('S3', [
            'region'      => 'us-east-1',
            'credentials' => ['key' => 'foo', 'secret' => 'bar']
        ]);
        $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']);
        $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri();
        $this->assertStringStartsWith('https://s3.amazonaws.com/foo/bar?', $url);
        $this->assertContains('X-Amz-Expires=', $url);
        $this->assertContains('X-Amz-Credential=', $url);
        $this->assertContains('X-Amz-Signature=', $url);
    }

    public function testCreatingPresignedUrlDoesNotPermanentlyRemoveSigner()
    {
        $sent = false;
        $client = new S3Client([
            'region' => 'us-east-1',
            'version' => 'latest',
            'credentials' => ['key' => 'foo', 'secret'  => 'bar'],
            'http_handler' => function (RequestInterface $request) use (&$sent) {
                $sent = true;
                foreach (['X-Amz-Date', 'Authorization'] as $signatureHeader) {
                    $this->assertTrue($request->hasHeader($signatureHeader));
                }
                return Promise\promise_for(new Response);
            },
        ]);
        $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']);
        $client->createPresignedRequest($command, 1342138769)->getUri();
        $client->execute($command);
        $this->assertTrue($sent);
    }

    public function testCreatesPresignedUrlsWithSpecialCharacters()
    {
        $client = new S3Client([
            'region'      => 'us-east-1',
            'version'     => 'latest',
            'credentials' => ['key' => 'foo', 'secret'  => 'bar']
        ]);
        $command = $client->getCommand('GetObject', [
            'Bucket' => 'foobar test: abc',
            'Key'    => '+%.a'
        ]);
        $url = $client->createPresignedRequest($command, 1342138769)->getUri();
        $this->assertEquals('/foobar%20test%3A%20abc/%2B%25.a', $url->getPath());
        $query = Psr7\parse_query($url->getQuery());
        $this->assertArrayHasKey('X-Amz-Credential', $query);
        $this->assertArrayHasKey('X-Amz-Signature', $query);
    }

    public function testRegistersStreamWrapper()
    {
        $s3 = $this->getTestClient('S3', ['region' => 'us-east-1']);
        $s3->registerStreamWrapper();
        $this->assertContains('s3', stream_get_wrappers());
        stream_wrapper_unregister('s3');
    }

    public function doesExistProvider()
    {
        return [
            ['foo', null, true, []],
            ['foo', 'bar', true, []],
            ['foo', null, true, $this->getS3ErrorMock('AccessDenied', 403)],
            ['foo', 'bar', true, $this->getS3ErrorMock('AccessDenied', 403)],
            ['foo', null, false, $this->getS3ErrorMock('Foo', 401)],
            ['foo', 'bar', false, $this->getS3ErrorMock('Foo', 401)],
            ['foo', null, -1, $this->getS3ErrorMock('Foo', 500)],
            ['foo', 'bar', -1, $this->getS3ErrorMock('Foo', 500)],
        ];
    }

    private function getS3ErrorMock($errCode, $statusCode)
    {
        $context = [
            'code' => $errCode,
            'response' => new Response($statusCode),
        ];
        return new S3Exception('', new Command('mockCommand'), $context);
    }

    /**
     * @dataProvider doesExistProvider
     */
    public function testsIfExists($bucket, $key, $exists, $result)
    {
        /** @var S3Client $s3 */
        $s3 = $this->getTestClient('S3', ['region' => 'us-east-1']);
        $this->addMockResults($s3, [$result]);
        try {
            if ($key) {
                $this->assertSame($exists, $s3->doesObjectExist($bucket, $key));
            } else {
                $this->assertSame($exists, $s3->doesBucketExist($bucket));
            }
        } catch (\Exception $e) {
            $this->assertEquals(-1, $exists);
        }
    }

    public function testReturnsObjectUrl()
    {
        $s3 = $this->getTestClient('S3', [
            'region'      => 'us-east-1',
            'credentials' => false
        ]);
        $this->assertEquals('https://s3.amazonaws.com/foo/bar', $s3->getObjectUrl('foo', 'bar'));
    }

    public function testReturnsObjectUrlViaPath()
    {
        /** @var S3Client $s3 */
        $s3 = $this->getTestClient('S3', [
            'region'      => 'us-east-1',
            'credentials' => false
        ]);
        $this->assertEquals(
            'https://s3.amazonaws.com/foo.baz/bar',
            $s3->getObjectUrl('foo.baz', 'bar')
        );
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testEnsuresPrefixOrRegexSuppliedForDeleteMatchingObjects()
    {
        /** @var S3Client $client */
        $client = $this->getTestClient('S3');
        $client->deleteMatchingObjects('foo');
    }

    public function testDeletesMatchingObjectsByPrefixAndRegex()
    {
        /** @var S3Client $client */
        $client = $this->getTestClient('S3');
        $client->getHandlerList()->setHandler(function ($c, $r) {
            $this->assertEquals('bucket', $c['Bucket']);
            return Promise\promise_for(new Result([
                'IsTruncated' => false,
                'Marker' => '',
                'Contents' => [
                    ['Key' => 'foo/bar'],
                    ['Key' => 'foo/bar/baz'],
                    ['Key' => 'foo/test'],
                    ['Key' => 'foo/bar/bam'],
                    ['Key' => 'foo/bar/001'],
                    ['Key' => 'foo/other']
                ]
            ]));
        });

        $agg = [];
        $client->deleteMatchingObjects('bucket', 'foo/bar/', '/^foo\/bar\/[a-z]+$/', [
            'before' => function ($cmd) use (&$agg) {
                foreach ($cmd['Delete']['Objects'] as $k) {
                    $agg[] = $k['Key'];
                }
            }
        ]);

        $this->assertEquals(['foo/bar/baz', 'foo/bar/bam'], $agg);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject
     */
    public function testProxiesToTransferObjectPut()
    {
        $client = $this->getTestClient('S3');
        $client->uploadDirectory(__DIR__, 'test');
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Mock queue is empty. Trying to send a ListObjects
     */
    public function testProxiesToTransferObjectGet()
    {
        $client = $this->getTestClient('S3');
        $client->downloadBucket(__DIR__, 'test');
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject
     */
    public function testProxiesToObjectUpload()
    {
        $client = $this->getTestClient('S3');
        $client->upload('bucket', 'key', 'body');
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Mock queue is empty. Trying to send a HeadObject
     */
    public function testProxiesToObjectCopy()
    {
        $client = $this->getTestClient('S3');
        $client->copy('fromBucket', 'fromKey', 'toBucket', 'toKey');
    }

    /**
     * @dataProvider getTestCasesForLocationConstraints
     */
    public function testAddsLocationConstraintAutomatically($region, $target, $command, $contains)
    {
        $client = $this->getTestClient('S3', ['region' => $region]);
        $params = ['Bucket' => 'foo'];
        if ($region !== $target) {
            $params['CreateBucketConfiguration'] = ['LocationConstraint' => $target];
        }
        $command = $client->getCommand($command, $params);

        $text = "<LocationConstraint>{$target}</LocationConstraint>";
        $body = (string) \Aws\serialize($command)->getBody();
        if ($contains) {
            $this->assertContains($text, $body);
        } else {
            $this->assertNotContains($text, $body);
        }
    }

    public function getTestCasesForLocationConstraints()
    {
        return [
            ['us-west-2', 'us-west-2', 'CreateBucket', true],
            ['us-east-1', 'us-east-1', 'CreateBucket', false],
            ['us-west-2', 'us-west-2', 'HeadBucket',   false],
            ['us-west-2', 'eu-west-1', 'CreateBucket', true],
            ['us-west-2', 'us-east-1', 'CreateBucket', false],
        ];
    }

    public function testSaveAsParamAddsSink()
    {
        $client = $this->getTestClient('S3', [
            'http_handler' => function ($request, array $options) {
                $this->assertArrayHasKey('sink', $options);
                return Promise\promise_for(
                    new Psr7\Response(200, [], 'sink=' . $options['sink'])
                );
            }
        ]);

        $result = $client->getObject([
            'Bucket' => 'foo',
            'Key'    => 'bar',
            'SaveAs' => 'baz',
        ]);

        $this->assertEquals('sink=baz', (string) $result['Body']);
    }

    public function testRequestSucceedsWithColon()
    {
        $key = 'aaa:bbb';
        $s3 = $this->getTestClient('S3', [
            'http_handler' => function (RequestInterface $request) use ($key) {
                $this->assertContains(
                    urlencode($key),
                    (string) $request->getUri()
                );

                return Promise\promise_for(new Psr7\Response);
            }
        ]);

        $s3->getObject([
            'Bucket' => 'bucket',
            'Key'    => $key,
        ]);
    }

    public function testRetriesConnectionErrors()
    {
        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () use (&$retries) {
                if (0 === --$retries) {
                    return new FulfilledPromise(new Response);
                }

                return new RejectedPromise([
                    'connection_error' => true,
                    'exception' => $this->getMockBuilder(ConnectException::class)
                        ->disableOriginalConstructor()
                        ->getMock(),
                    'response' => null,
                ]);
            },
        ]);

        $client->headBucket([
            'Bucket' => 'bucket',
        ]);

        $this->assertEquals(0, $retries);
    }

    /**
     * @dataProvider successErrorResponseProvider
     *
     * @param Response $failingSuccess
     * @param string   $operation
     * @param array    $payload
     */
    public function testRetries200Errors(
        Response $failingSuccess,
        $operation,
        array $payload
    ) {
        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () use (&$retries, $failingSuccess) {
                if (0 === --$retries) {
                    return new FulfilledPromise(new Response(
                        200,
                        [],
                        $this->getWellFormedXml()
                    ));
                }

                return new FulfilledPromise($failingSuccess);
            },
        ]);

        $client->{$operation}($payload);

        $this->assertEquals(0, $retries);
    }

    public function successErrorResponseProvider()
    {
        return [
            [
                new Response(200, [], $this->getErrorXml()),
                'copyObject',
                [
                    'Bucket' => 'foo',
                    'Key' => 'bar',
                    'CopySource' => 'baz',
                ],
            ],
            [
                new Response(200, [], $this->getErrorXml()),
                'uploadPartCopy',
                [
                    'PartNumber' => 1,
                    'UploadId' => PHP_INT_SIZE,
                    'Bucket' => 'foo',
                    'Key' => 'bar',
                    'CopySource' => 'baz',
                ],
            ],
            [
                new Response(200, [], $this->getErrorXml()),
                'completeMultipartUpload',
                [
                    'UploadId' => PHP_INT_SIZE,
                    'Bucket' => 'foo',
                    'Key' => 'bar',
                ],
            ],
            [
                new Response(200, [], $this->getMalformedXml()),
                'listObjects',
                [
                    'Bucket' => 'foo',
                ],
            ],
        ];
    }

    private function getErrorXml()
    {
        return <<<EOXML
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  InternalError
  <Message>We encountered an internal error. Please try again.</Message>
  <RequestId>656c76696e6727732072657175657374</RequestId>
  <HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
EOXML;
    }

    private function getMalformedXml()
    {
        return <<<EOXML
<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Name>jmtestbucket2</Name>
    <Prefix></Prefix>
    <Marker></Marker>
    <MaxKeys>1000</MaxKeys>
    <Delimiter>/</Delimiter>
    <IsTruncated>false</IsTruncated>
    <Contents>
        <Key><</Key>
        <LastModified>2015-09-03T23:51:29.000Z</LastModified>
        <ETag>"af1ed9909386b6116bda14403ff5f72e"</ETag>
        <Size>10</Size>
EOXML;
    }

    private function getWellFormedXml()
    {
        return '<?xml version="1.0" encoding="UTF-8"?><node></node>';
    }

    /**
     * @expectedException \Aws\S3\Exception\S3Exception
     * @expectedExceptionMessageRegExp /Your socket connection to the server/
     */
    public function testClientSocketTimeoutErrorsAreNotRetriedIndefinitely()
    {
        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () {
                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $this->getMockBuilder(RequestException::class)
                        ->disableOriginalConstructor()
                        ->getMock(),
                    'response' => new Response(400, [], $this->getSocketTimeoutResponse()),
                ]);
            },
        ]);

        $client->putObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
            'Body' => Psr7\stream_for('x'),
        ]);
    }

    private function getSocketTimeoutResponse()
    {
        return <<<EOXML
<?xml version="1.0" encoding="UTF-8"?>
<Error>
    RequestTimeout
    <Message>Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed.</Message>
    <RequestId>REQUEST_ID</RequestId>
    <HostId>HOST_ID</HostId>
</Error>
EOXML;
    }

    public function testNetworkingErrorsAreRetriedOnIdempotentCommands()
    {
        $networkingError = $this->getMockBuilder(RequestException::class)
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();

        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () use (&$retries, $networkingError) {
                if (0 === --$retries) {
                    return new FulfilledPromise(new Response);
                }

                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $networkingError,
                    'response' => null,
                ]);
            },
        ]);

        $client->putObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
        ]);

        $this->assertEquals(0, $retries);
    }

    /**
     * @expectedException \Aws\S3\Exception\S3Exception
     * @expectedExceptionMessageRegExp /CompleteMultipartUpload/
     */
    public function testNetworkingErrorsAreNotRetriedOnNonIdempotentCommands()
    {
        $networkingError = $this->getMockBuilder(RequestException::class)
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();

        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () use (&$retries, $networkingError) {
                if (0 === --$retries) {
                    return new FulfilledPromise(new Response);
                }

                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $networkingError,
                    'response' => null,
                ]);
            },
        ]);

        $client->completeMultipartUpload([
            'Bucket' => 'bucket',
            'Key' => 'key',
            'UploadId' => 1,
        ]);

        $this->assertEquals(0, $retries);
    }

    public function testErrorsWithUnparseableBodiesCanBeRetried()
    {
        $networkingError = $this->getMockBuilder(RequestException::class)
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMock();

        $retries = 11;
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'retries' => $retries,
            'http_handler' => function () use (&$retries, $networkingError) {
                if (0 === --$retries) {
                    return new FulfilledPromise(new Response);
                }

                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $networkingError,
                    'response' => new Response(200, [], openssl_random_pseudo_bytes(2048)),
                ]);
            },
        ]);

        $client->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
        ]);

        $this->assertEquals(0, $retries);
    }

    public function testListObjectsAppliesUrlEncodingWhenNoneSupplied()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => function (RequestInterface $request) {
                $query = Psr7\parse_query($request->getUri()->getQuery());
                $this->assertArrayHasKey('encoding-type', $query);
                $this->assertSame('url', $query['encoding-type']);

                return new FulfilledPromise(new Response);
            },
        ]);

        $client->listObjects(['Bucket' => 'bucket']);
    }

    public function testListObjectsUrlDecodesEncodedKeysWhenEncodingNotSupplied()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => function () {
                return new FulfilledPromise(new Response(200, [], $this->getUrlEncodedListObjectsResponse()));
            },
        ]);

        $response = $client->listObjects(['Bucket' => 'bucket']);
        $this->assertSame(',', $response['Delimiter']);
        $this->assertSame('test/yearmonth=201601/file2', $response['Marker']);
        $this->assertSame('test/yearmonth=201601/file2', $response['NextMarker']);
        $this->assertSame('test/yearmonth=201601/', $response['Prefix']);
        $this->assertSame('test/yearmonth=201601/file1', $response['Contents'][0]['Key']);
        $this->assertSame('test/yearmonth=201601/', $response['CommonPrefixes'][0]['Prefix']);
    }

    public function testListObjectsDoesNotUrlDecodeEncodedKeysWhenEncodingSupplied()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => function () {
                return new FulfilledPromise(new Response(200, [], $this->getUrlEncodedListObjectsResponse()));
            },
        ]);

        $response = $client->listObjects([
            'Bucket' => 'bucket',
            'EncodingType' => 'url',
        ]);

        $this->assertSame('%2C', $response['Delimiter']);
        $this->assertSame('test/yearmonth%3D201601/file2', $response['Marker']);
        $this->assertSame('test/yearmonth%3D201601/file2', $response['NextMarker']);
        $this->assertSame('test/yearmonth%3D201601/', $response['Prefix']);
        $this->assertSame('test/yearmonth%3D201601/file1', $response['Contents'][0]['Key']);
        $this->assertSame('test/yearmonth%3D201601/', $response['CommonPrefixes'][0]['Prefix']);
    }

    private function getUrlEncodedListObjectsResponse()
    {
        return <<<EOXML
<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Prefix>test/yearmonth%3D201601/</Prefix>
    <Marker>test/yearmonth%3D201601/file2</Marker>
    <NextMarker>test/yearmonth%3D201601/file2</NextMarker>
    <Delimiter>%2C</Delimiter>
    <EncodingType>url</EncodingType>
    <Contents>
        <Key>test/yearmonth%3D201601/file1</Key>
    </Contents>
    <CommonPrefixes>
        <Prefix>test/yearmonth%3D201601/</Prefix>
    </CommonPrefixes>
</ListBucketResult>
EOXML;
    }

    public function testHeadObjectDisablesContentDecodingByDefault()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => function (RequestInterface $r, array $opts = []) {
                $this->assertArrayHasKey('decode_content', $opts);
                $this->assertSame(false, $opts['decode_content']);

                return Promise\promise_for(new Response);
            }
        ]);

        $client->headObject(['Bucket' => 'bucket', 'Key' => 'key']);
    }

    public function testContentDecodingCanBeDisabled()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http' => ['decode_content' => false],
            'http_handler' => function (RequestInterface $r, array $opts = []) {
                $this->assertArrayHasKey('decode_content', $opts);
                $this->assertSame(false, $opts['decode_content']);

                return Promise\promise_for(new Response);
            }
        ]);

        $client->getObject(['Bucket' => 'bucket', 'Key' => 'key']);
    }

    public function testContentDecodingCanBeDisabledOnCommands()
    {
        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => function (RequestInterface $r, array $opts = []) {
                $this->assertArrayHasKey('decode_content', $opts);
                $this->assertSame(false, $opts['decode_content']);

                return Promise\promise_for(new Response);
            }
        ]);

        $client->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
            '@http' => ['decode_content' => false],
        ]);
    }

    public function testCanDetermineRegionOfBucket()
    {
        $client = new S3Client([
            'region' => 'us-west-2',
            'version' => 'latest',
            'http_handler' => function () {
                return new FulfilledPromise(new Response(301, [
                    'X-Amz-Bucket-Region' => 'alderaan-north-1',
                ]));
            },
        ]);
        $this->assertSame('alderaan-north-1', $client->determineBucketRegion('bucket'));

        $client = new S3Client([
            'region' => 'us-west-2',
            'version' => 'latest',
            'http_handler' => function() {
                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $this->getMockBuilder(AwsException::class)
                        ->disableOriginalConstructor()
                        ->getMock(),
                    'response' => new Response(400, [
                        'X-Amz-Bucket-Region' => 'us-west-2',
                    ]),
                ]);
            },
        ]);
        $this->assertSame('us-west-2', $client->determineBucketRegion('bucket'));
    }

    /**
     * @expectedException \Aws\Exception\AwsException
     */
    public function testDetermineBucketRegionExposeException()
    {
        $client = new S3Client([
            'region' => 'us-west-2',
            'version' => 'latest',
            'http_handler' => function() {
                return new RejectedPromise([
                    'connection_error' => false,
                    'exception' => $this->getMockBuilder(AwsException::class)
                        ->disableOriginalConstructor()
                        ->getMock(),
                    'response' => null,
                ]);
            },
        ]);
        $client->determineBucketRegion('bucket');
    }

    public function testAppliesS3EndpointMiddleware()
    {
        // test applies s3-accelerate.dualstack for valid operations
        $handler = function (RequestInterface $req) {
            $this->assertSame(
                'bucket.s3-accelerate.dualstack.amazonaws.com',
                $req->getUri()->getHost()
            );
            return Promise\promise_for(new Response);
        };

        $accelerateClient = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'use_accelerate_endpoint' => true,
            'use_dual_stack_endpoint' => true,
            'http_handler' => $handler,
        ]);
        $accelerateClient->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key'
        ]);

        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => $handler,
        ]);
        $client->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
            '@use_accelerate_endpoint' => true,
            '@use_dual_stack_endpoint' => true,
        ]);

        // test applies dualstack solo for invalid accelerate operations
        // when both endpoint is enabled
        $handler = function (RequestInterface $req) {
            $this->assertSame(
                's3.dualstack.us-west-2.amazonaws.com',
                $req->getUri()->getHost()
            );
            return Promise\promise_for(new Response);
        };

        $accelerateClient = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'use_accelerate_endpoint' => true,
            'use_dual_stack_endpoint' => true,
            'http_handler' => $handler,
        ]);
        $accelerateClient->createBucket([
            'Bucket' => 'bucket',
        ]);

        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => $handler,
        ]);
        $client->createBucket([
            'Bucket' => 'bucket',
            '@use_accelerate_endpoint' => true,
            '@use_dual_stack_endpoint' => true,
        ]);

        // test applies s3-accelerate for valid operations
        $handler = function (RequestInterface $req) {
            $this->assertSame(
                'bucket.s3-accelerate.amazonaws.com',
                $req->getUri()->getHost()
            );
            return Promise\promise_for(new Response);
        };

        $accelerateClient = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'use_accelerate_endpoint' => true,
            'http_handler' => $handler,
        ]);
        $accelerateClient->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key'
        ]);

        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => $handler,
        ]);
        $client->getObject([
            'Bucket' => 'bucket',
            'Key' => 'key',
            '@use_accelerate_endpoint' => true,
        ]);

        // test applies dualstack
        $handler = function (RequestInterface $req) {
            $this->assertSame(
                's3.dualstack.us-west-2.amazonaws.com',
                $req->getUri()->getHost()
            );
            $this->assertContains(
                'bucket',
                $req->getUri()->getPath()
            );
            return Promise\promise_for(new Response);
        };

        $dualStackClient = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'use_dual_stack_endpoint' => true,
            'http_handler' => $handler,
        ]);
        $dualStackClient->createBucket([
            'Bucket' => 'bucket',
        ]);

        $client = new S3Client([
            'version' => 'latest',
            'region' => 'us-west-2',
            'http_handler' => $handler,
        ]);
        $client->createBucket([
            'Bucket' => 'bucket',
            '@use_dual_stack_endpoint' => true,
        ]);
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
  <title>gl-fragcoord Test</title>
  <link rel="stylesheet" href="../../../resources/js-test-style.css"/>

<canvas id="example" width="32" height="32">
</canvas>


text:
from __future__ import annotations

from typing import TYPE_CHECKING, Any, cast

import _pytest
import _pytest.fixtures
import aiohttp
import pytest

from erasmus.data import Passage, VerseRange
from erasmus.services.biblegateway import BibleGateway

from . import Galatians_3_10_11, Mark_5_1, ServiceTest

if TYPE_CHECKING:
    from erasmus.types import Service

Psalm_53_1_ESV = (
    '**To the choirmaster: according to Mahalath. A Maskil of David.** **1.** The fool '
    'says in his heart, "There is no God." They are corrupt, doing abominable '
    'iniquity; there is none who does good.'
)

class TestBibleGateway(ServiceTest):
    @pytest.fixture(
        params=[
            {
                'terms': ['Melchizedek'],
                'verses': [
                    Passage(
                        text='And **Melchizedek** king of Salem brought out bread and '
                        'wine; now he was a priest of God Most High.',
                        range=VerseRange.from_string('Genesis 14:18'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='The LORD has sworn and will not change His mind, '
                        '\u201CYou are a priest forever According to the order of '
                        '**Melchizedek**.\u201D',
                        range=VerseRange.from_string('Psalm 110:4'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='just as He says also in another _passage_, \u201CYOU ARE '
                        'A PRIEST FOREVER ACCORDING TO THE ORDER OF **MELCHIZEDEK**.'
                        '\u201D',
                        range=VerseRange.from_string('Hebrews 5:6'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='being designated by God as a high priest according to '
                        'the order of **Melchizedek**.',
                        range=VerseRange.from_string('Hebrews 5:10'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='where Jesus has entered as a forerunner for us, having '
                        'become a high priest forever according to the order of '
                        '**Melchizedek**.',
                        range=VerseRange.from_string('Hebrews 6:20'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='_**Melchizedek**\u2019s Priesthood Like Christ\u2019s_'
                        ' For this **Melchizedek**, king of Salem, priest of the '
                        'Most High God, who met Abraham as he was returning from the '
                        'slaughter of the kings and blessed him,',
                        range=VerseRange.from_string('Hebrews 7:1'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='for he was still in the loins of his father when '
                        '**Melchizedek** met him.',
                        range=VerseRange.from_string('Hebrews 7:10'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Now if perfection was through the Levitical priesthood '
                        '(for on the basis of it the people received the Law), what '
                        'further need _was there_ for another priest to arise '
                        'according to the order of **Melchizedek**, and not be '
                        'designated according to the order of Aaron?',
                        range=VerseRange.from_string('Hebrews 7:11'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='And this is clearer still, if another priest arises '
                        'according to the likeness of **Melchizedek**,',
                        range=VerseRange.from_string('Hebrews 7:15'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='For it is attested _of Him_, \u201CYOU ARE A PRIEST '
                        'FOREVER ACCORDING TO THE ORDER OF **MELCHIZEDEK**.\u201D',
                        range=VerseRange.from_string('Hebrews 7:17'),
                        version='NASB1995',
                    ),
                ],
                'total': 10,
            },
            {
                'terms': ['faith'],
                'verses': [
                    Passage(
                        text='I am unworthy of all the lovingkindness and of all '
                        'the **faith**fulness which You have shown to Your '
                        'servant; for with my staff _only_ I crossed this Jordan, '
                        'and now I have become two companies.',
                        range=VerseRange.from_string('Genesis 32:10'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='When the time for Israel to die drew near, he called his '
                        'son Joseph and said to him, \u201CPlease, if I have found '
                        'favor in your sight, place now your hand under my thigh and '
                        'deal with me in kindness and **faith**fulness. Please do not '
                        'bury me in Egypt,',
                        range=VerseRange.from_string('Genesis 47:29'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='\u201CNot so, with My servant Moses, He is **faith**'
                        'ful in all My household;',
                        range=VerseRange.from_string('Numbers 12:7'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Know therefore that the LORD your God, He is God, the '
                        '**faith**ful God, who keeps His covenant and His '
                        'lovingkindness to a thousandth generation with those who love '
                        'Him and keep His commandments;',
                        range=VerseRange.from_string('Deuteronomy 7:9'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='\u201CThe Rock! His work is perfect, For all His ways '
                        'are just; A God of **faith**fulness and without injustice, '
                        'Righteous and upright is He.',
                        range=VerseRange.from_string('Deuteronomy 32:4'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='\u201CThen He said, \u2018I will hide My face from them, '
                        'I will see what their end _shall be_; For they are a perverse '
                        'generation, Sons in whom is no **faith**fulness.',
                        range=VerseRange.from_string('Deuteronomy 32:20'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='because you broke **faith** with Me in the midst of the '
                        'sons of Israel at the waters of Meribah-kadesh, in the '
                        'wilderness of Zin, because you did not treat Me as holy in '
                        'the midst of the sons of Israel.',
                        range=VerseRange.from_string('Deuteronomy 32:51'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='So the men said to her, \u201COur life for yours if you '
                        'do not tell this business of ours; and it shall come about '
                        'when the LORD gives us the land that we will deal kindly and '
                        '**faith**fully with you.\u201D',
                        range=VerseRange.from_string('Joshua 2:14'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='But I will raise up for Myself a **faith**ful priest who '
                        'will do according to what is in My heart and in My soul; and '
                        'I will build him an enduring house, and he will walk before '
                        'My anointed always.',
                        range=VerseRange.from_string('1 Samuel 2:35'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Then Ahimelech answered the king and said, \u201CAnd who '
                        'among all your servants is as **faith**ful as David, even the '
                        'king\u2019s son-in-law, who is captain over your guard, and '
                        'is honored in your house?',
                        range=VerseRange.from_string('1 Samuel 22:14'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='The LORD will repay each man _for_ his righteousness and '
                        'his **faith**fulness; for the LORD delivered you into _my_ '
                        'hand today, but I refused to stretch out my hand against the '
                        'LORD\u2019S anointed.',
                        range=VerseRange.from_string('1 Samuel 26:23'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='I am of those who are peaceable _and_ **faith**ful in '
                        'Israel. You are seeking to destroy a city, even a mother in '
                        'Israel. Why would you swallow up the inheritance of the '
                        'LORD?\u201D',
                        range=VerseRange.from_string('2 Samuel 20:19'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Moreover, they did not require an accounting from the '
                        'men into whose hand they gave the money to pay to those who '
                        'did the work, for they dealt **faith**fully.',
                        range=VerseRange.from_string('2 Kings 12:15'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Only no accounting shall be made with them for the money '
                        'delivered into their hands, for they deal **faith**fully.'
                        '\u201D',
                        range=VerseRange.from_string('2 Kings 22:7'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Then he charged them saying, \u201CThus you shall do in '
                        'the fear of the LORD, **faith**fully and wholeheartedly.',
                        range=VerseRange.from_string('2 Chronicles 19:9'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='_**Faith**less Priests_ Now it came about after this '
                        'that Joash decided to restore the house of the LORD.',
                        range=VerseRange.from_string('2 Chronicles 24:4'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='They **faith**fully brought in the contributions and the '
                        'tithes and the consecrated things; and Conaniah the Levite '
                        '_was_ the officer in charge of them and his brother Shimei '
                        '_was_ second.',
                        range=VerseRange.from_string('2 Chronicles 31:12'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='Under his authority _were_ Eden, Miniamin, Jeshua, '
                        'Shemaiah, Amariah and Shecaniah in the cities of the priests, '
                        'to distribute **faith**fully _their portions_ to their '
                        'brothers by divisions, whether great or small,',
                        range=VerseRange.from_string('2 Chronicles 31:15'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='The genealogical enrollment _included_ all their little '
                        'children, their wives, their sons and their daughters, for '
                        'the whole assembly, for they consecrated themselves '
                        '**faith**fully in holiness.',
                        range=VerseRange.from_string('2 Chronicles 31:18'),
                        version='NASB1995',
                    ),
                    Passage(
                        text='_Sennacherib Invades Judah_ After these acts of '
                        '**faith**fulness Sennacherib king of Assyria came and invaded '
                        'Judah and besieged the fortified cities, and thought to break '
                        'into them for himself.',
                        range=VerseRange.from_string('2 Chronicles 32:1'),
                        version='NASB1995',
                    ),
                ],
                'total': 378,
            },
            {'terms': ['antidisestablishmentarianism'], 'verses': [], 'total': 0},
        ],
        ids=['Melchizedek', 'faith', 'antidisestablishmentarianism'],
    )
    def search_data(self, request: _pytest.fixtures.SubRequest) -> dict[str, Any]:
        return cast('dict[str, Any]', request.param)

    @pytest.fixture(
        params=[
            {
                'verse': VerseRange.from_string('Gal 3:10-11'),
                'passage': Passage(
                    Galatians_3_10_11, VerseRange.from_string('Gal 3:10-11'), 'NASB1995'
                ),
            },
            {
                'verse': VerseRange.from_string('Mark 5:1'),
                'passage': Passage(
                    Mark_5_1, VerseRange.from_string('Mark 5:1'), 'NASB1995'
                ),
            },
            {
                'verse': VerseRange.from_string('Psalm 53:1'),
                'passage': Passage(
                    Psalm_53_1_ESV, VerseRange.from_string('Psalm 53:1'), 'ESV'
                ),
                'version': 'ESV',
                'abbr': 'ESV',
            },
        ],
        ids=['Gal 3:10-11 NASB1995', 'Mark 5:1 NASB1995', 'Psalm 53:1 ESV'],
    )
    def passage_data(self, request: _pytest.fixtures.SubRequest) -> dict[str, Any]:
        return cast('dict[str, Any]', request.param)

    @pytest.fixture
    def default_version(self) -> str:
        return 'NASB1995'

    @pytest.fixture
    def default_abbr(self) -> str:
        return 'NASB1995'

    @pytest.fixture
    def service(self, aiohttp_client_session: aiohttp.ClientSession) -> Service:
        return BibleGateway(config={}, session=aiohttp_client_session)


text:
package org.assertj.core.internal.maps;

import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.assertj.core.data.MapEntry.entry;
import static org.assertj.core.error.ElementsShouldSatisfy.elementsShouldSatisfyAny;
import static org.assertj.core.error.ElementsShouldSatisfy.unsatisfiedRequirement;
import static org.assertj.core.test.Maps.mapOf;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.AssertionsUtil.expectAssertionError;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.assertj.core.util.Lists.emptyList;
import static org.assertj.core.util.Lists.list;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiConsumer;

import org.assertj.core.error.UnsatisfiedRequirement;
import org.assertj.core.internal.MapsBaseTest;
import org.assertj.core.test.Player;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class Maps_assertAnySatisfyingConsumer_Test extends MapsBaseTest {

  private Map<String, Player> greatPlayers;

  @Mock
  private BiConsumer<String, Player> consumer;

  @Override
  @BeforeEach
  public void setUp() {
    super.setUp();
    greatPlayers = mapOf(entry("Bulls", jordan), entry("Spurs", duncan), entry("Lakers", magic));
  }

  @Test
  void must_not_check_all_entries() {
    // GIVEN
    assertThat(greatPlayers).hasSizeGreaterThan(2); // This test requires a map with size > 2
    // first entry does not match -> assertion error, 2nd entry does match -> doNothing()
    doThrow(new AssertionError("some error message")).doNothing().when(consumer).accept(anyString(), any(Player.class));
    // WHEN
    maps.assertAnySatisfy(someInfo(), greatPlayers, consumer);
    // THEN
    // make sure that we only evaluated 2 out of 3 entries
    verify(consumer, times(2)).accept(anyString(), any(Player.class));
  }

  @Test
  void should_pass_if_one_entry_satisfies_the_given_requirements() {
    maps.assertAnySatisfy(someInfo(), greatPlayers, (team, player) -> {
      assertThat(team).isEqualTo("Lakers");
      assertThat(player.getPointsPerGame()).isGreaterThan(18);
    });
  }

  @Test
  void should_fail_if_the_map_under_test_is_empty_whatever_the_assertions_requirements_are() {
    // GIVEN
    actual.clear();
    // WHEN
    AssertionError error = expectAssertionError(() -> maps.assertAnySatisfy(someInfo(), actual,
                                                                            ($1, $2) -> assertThat(true).isTrue()));
    // THEN
    assertThat(error).hasMessage(elementsShouldSatisfyAny(actual, emptyList(), someInfo()).create());
  }

  @Test
  void should_fail_if_no_entry_satisfies_the_given_requirements() {
    // WHEN
    AssertionError error = expectAssertionError(() -> maps.assertAnySatisfy(someInfo(), actual,
                                                                            ($1, $2) -> assertThat(true).isFalse()));
    // THEN
    Iterator<Entry<String, String>> actualEntries = actual.entrySet().iterator();
    List<UnsatisfiedRequirement> errors = list(unsatisfiedRequirement(actualEntries.next(),
                                                                      format("%nExpecting value to be false but was true")),
                                               unsatisfiedRequirement(actualEntries.next(),
                                                                      format("%nExpecting value to be false but was true")));
    assertThat(error).hasMessage(elementsShouldSatisfyAny(actual, errors, someInfo()).create());
  }

  @Test
  void should_fail_if_actual_is_null() {
    // WHEN
    AssertionError error = expectAssertionError(() -> maps.assertAnySatisfy(someInfo(), null, (team, player) -> {}));
    // THEN
    assertThat(error).hasMessage(actualIsNull());
  }

  @Test
  void should_fail_if_given_requirements_are_null() {
    assertThatNullPointerException().isThrownBy(() -> maps.assertAnySatisfy(someInfo(), greatPlayers, null))
                                    .withMessage("The BiConsumer<K, V> expressing the assertions requirements must not be null");
  }
}


text:
package com.meltmedia.dropwizard.mongo.junit;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import com.mongodb.MongoClient;

/**
 * A JUnit Rule for creating a mongo client. This rule is designed to be used as
 * a ClassRule.
 *
 * @author Christian Trimble
 */
public class MongoRule
  implements TestRule
{
  MongoClient mongoClient;
  String host;
  int port;

  public MongoRule( String host, int port ) {
    this.host = host;
    this.port = port;
  }

  /**
   * Return an instance of the mongo client when this rule is in effect.
   *
   * @return
   */
  public MongoClient getClient() {
    return mongoClient;
  }

  /**
   * Wraps the provided statement with code to create and then clean up a
   * MongoClient object.
   */
  @Override
  public Statement apply( final Statement statement, final Description description ) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        try {
          mongoClient = new MongoClient(host, port);
          statement.evaluate();
        } finally {
          if( mongoClient != null ) {
            try {
              mongoClient.close();
            } catch( Exception e ) {
            }
            mongoClient = null;
          }
        }
      }
    };
  }
}


text:
'use strict';

var di = require('di');

module.exports = NodeFactory;

di.annotate(NodeFactory, new di.Provide('Serializables.V1.Node'));
di.annotate(NodeFactory,
    new di.Inject(
        'Promise',
        'Serializable',
        'Serializables.V1.Obm',
        'Serializables.V1.Snmp',
        'Serializables.V1.Ssh',
        'Constants',
        '_'
    )
);

function NodeFactory (
    Promise,
    Serializable,
    ObmSerializable,
    SnmpSerializable,
    SshSerializable,
    Constants,
    _
) {
    function Node (defaults) {
        Serializable.call(
            this,
            Node.schema,
            defaults
        );
    }

    Node.schema = {
        id: 'Serializables.V1.Node',
        type: 'object',
        properties: {
            name: {
                type: 'string'
            },
            type: {
                enum: _.values(Constants.NodeTypes)
            },
            obmSettings: {
                type: 'array',
                items: {
                    $ref: 'Serializables.V1.Obm'
                }
            },
            sshSettings: {
                type: 'object',
                items: {
                    $ref: 'Serializables.V1.Ssh'
                }
            },
            snmpSettings: {
                type: 'object',
                items: {
                    $ref: 'Serializables.V1.Snmp'
                }
            },
            bootSettings: {
                type: 'object',
                items: {
                    $ref: 'Serializables.V1.Boot'
                }
            }
        },
        required: [ 'name' ]
    };

    Serializable.register(NodeFactory, Node);

    Node.prototype.serializeObmSettings = function () {
        var self = this;
        if (this.obmSettings) {
            return Promise.map(this.obmSettings, function (item) {
                var serializable = new ObmSerializable();

                return serializable.serialize(item);
            }).then(function (settings) {
                self.obmSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.deserializeObmSettings = function () {
        var self = this;
        if (this.obmSettings) {
            return Promise.map(this.obmSettings, function (item) {
                var serializable = new ObmSerializable();
                return serializable.deserialize(item);
            }).then(function (settings) {
                self.obmSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.serializeSnmpSettings = function () {
        var self = this;

        if (this.snmpSettings) {
            return Promise.resolve().then(function () {
                var serializable = new SnmpSerializable();
                return serializable.serialize(self.snmpSettings);
            }).then(function (settings) {
                self.snmpSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.deserializeSnmpSettings = function () {
        var self = this;

        if (this.snmpSettings) {
            return Promise.resolve().then(function () {
                var serializable = new SnmpSerializable();
                return serializable.deserialize(self.snmpSettings);
            }).then(function (settings) {
                self.snmpSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.serializeSshSettings = function () {
        var self = this;

        if (this.sshSettings) {
            return Promise.resolve().then(function () {
                var serializable = new SshSerializable();
                return serializable.serialize(self.sshSettings);
            }).then(function (settings) {
                self.sshSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.deserializeSshSettings = function () {
        var self = this;

        if (this.sshSettings) {
            return Promise.resolve().then(function () {
                var serializable = new SshSerializable();
                return serializable.deserialize(self.sshSettings);
            }).then(function (settings) {
                self.sshSettings = settings;
                return self;
            });
        }
    };

    Node.prototype.serialize = function (target) {
        var self = this;
        this.defaults(target);
        return Promise.all([
                this.serializeSnmpSettings(),
                this.serializeObmSettings(),
                this.serializeSshSettings()
        ])
        .spread(function() {
            return self;
        });
    };

    Node.prototype.deserialize = function (target) {
        var self = this;

        this.defaults(target);
        return Promise.all([
                this.deserializeSnmpSettings(),
                this.deserializeObmSettings(),
                this.deserializeSshSettings()
        ])
        .spread(function() {
            return self;
        });
    };

    return Node;
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');

var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);

var _svgIcon = require('../../svg-icon');

var _svgIcon2 = _interopRequireDefault(_svgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ImageStraighten = _react2.default.createClass({
  displayName: 'ImageStraighten',

  mixins: [_reactAddonsPureRenderMixin2.default],

  render: function render() {
    return _react2.default.createElement(
      _svgIcon2.default,
      this.props,
      _react2.default.createElement('path', { d: 'M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z' })
    );
  }
});

exports.default = ImageStraighten;
module.exports = exports['default'];


text:
package lru

// Cache is the interface that defines operations
// that a cache can perform.
type Cache interface {
	// Add sets a key and value in the cache. The returned
	// boolean is true if an eviction occured, and false if not.
	Add(interface{}, interface{}) bool

	// Get retrieves the value of a key from the cache. The returned
	// boolean is true if the key was found, and false if not.
	Get(interface{}) (interface{}, bool)

	// Remove deletes a key from the cache. The returned boolean is
	// true if a key was deleted, and false if not.
	Remove(interface{}) bool

	// Clear should clear the cache.
	Clear()
}

// New returns a new LRU with provided options.
func New(opts ...Option) Cache {
	o := newDefaultOptions()

	for _, opt := range opts {
		opt(o)
	}

	c := newBasic(o.Size)

	if o.MultiThreaded {
		c = newMultiThreaded(c)
	}

	if o.Lookup != nil {
		c = newLazyLookup(c, o.Lookup)
	}

	return c
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>JSONML</title>
<meta name="date" content="2013-04-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.json

Class JSONML

java.lang.Object

org.json.JSONML

public class JSONML
extends java.lang.Object

This provides static methods to convert an XML text into a JSONArray or
 JSONObject, and to covert a JSONArray or JSONObject into an XML text using
 the JsonML transform.

Version:

2012-03-28

Author:

JSON.org

Constructor Summary

Constructors

Constructor and Description

JSONML()

Method Summary

Methods

Modifier and Type
Method and Description

static JSONArray
toJSONArray(java.lang.String string)

Convert a well-formed (but not necessarily valid) XML string into a
 JSONArray using the JsonML transform.

static JSONArray
toJSONArray(XMLTokener x)

Convert a well-formed (but not necessarily valid) XML string into a
 JSONArray using the JsonML transform.

static JSONObject
toJSONObject(java.lang.String string)

Convert a well-formed (but not necessarily valid) XML string into a
 JSONObject using the JsonML transform.

static JSONObject
toJSONObject(XMLTokener x)

Convert a well-formed (but not necessarily valid) XML string into a
 JSONObject using the JsonML transform.

static java.lang.String
toString(JSONArray ja)

Reverse the JSONML transformation, making an XML text from a JSONArray.

static java.lang.String
toString(JSONObject jo)

Reverse the JSONML transformation, making an XML text from a JSONObject.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JSONML

public JSONML()

Method Detail

toJSONArray

public static JSONArray toJSONArray(java.lang.String string)
                             throws JSONException

Convert a well-formed (but not necessarily valid) XML string into a
 JSONArray using the JsonML transform. Each XML tag is represented as
 a JSONArray in which the first element is the tag name. If the tag has
 attributes, then the second element will be JSONObject containing the
 name/value pairs. If the tag contains children, then strings and
 JSONArrays will represent the child tags.
 Comments, prologs, DTDs, and <[ [ ]]> are ignored.

Parameters:

string - The source string.

Returns:

A JSONArray containing the structured data from the XML string.

Throws:

JSONException

toJSONArray

public static JSONArray toJSONArray(XMLTokener x)
                             throws JSONException

Convert a well-formed (but not necessarily valid) XML string into a
 JSONArray using the JsonML transform. Each XML tag is represented as
 a JSONArray in which the first element is the tag name. If the tag has
 attributes, then the second element will be JSONObject containing the
 name/value pairs. If the tag contains children, then strings and
 JSONArrays will represent the child content and tags.
 Comments, prologs, DTDs, and <[ [ ]]> are ignored.

Parameters:

x - An XMLTokener.

Returns:

A JSONArray containing the structured data from the XML string.

Throws:

JSONException

toJSONObject

public static JSONObject toJSONObject(XMLTokener x)
                               throws JSONException

Convert a well-formed (but not necessarily valid) XML string into a
 JSONObject using the JsonML transform. Each XML tag is represented as
 a JSONObject with a "tagName" property. If the tag has attributes, then
 the attributes will be in the JSONObject as properties. If the tag
 contains children, the object will have a "childNodes" property which
 will be an array of strings and JsonML JSONObjects.

 Comments, prologs, DTDs, and <[ [ ]]> are ignored.

Parameters:

x - An XMLTokener of the XML source text.

Returns:

A JSONObject containing the structured data from the XML string.

Throws:

JSONException

toJSONObject

public static JSONObject toJSONObject(java.lang.String string)
                               throws JSONException

Convert a well-formed (but not necessarily valid) XML string into a
 JSONObject using the JsonML transform. Each XML tag is represented as
 a JSONObject with a "tagName" property. If the tag has attributes, then
 the attributes will be in the JSONObject as properties. If the tag
 contains children, the object will have a "childNodes" property which
 will be an array of strings and JsonML JSONObjects.

 Comments, prologs, DTDs, and <[ [ ]]> are ignored.

Parameters:

string - The XML source text.

Returns:

A JSONObject containing the structured data from the XML string.

Throws:

JSONException

toString

public static java.lang.String toString(JSONArray ja)
                                 throws JSONException

Reverse the JSONML transformation, making an XML text from a JSONArray.

Parameters:

ja - A JSONArray.

Returns:

An XML string.

Throws:

JSONException

toString

public static java.lang.String toString(JSONObject jo)
                                 throws JSONException

Reverse the JSONML transformation, making an XML text from a JSONObject.
 The JSONObject must contain a "tagName" property. If it has children,
 then it must have a "childNodes" property containing an array of objects.
 The other properties are attributes with string values.

Parameters:

jo - A JSONObject.

Returns:

An XML string.

Throws:

JSONException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method