text stringlengths 2 1.04M | meta dict |
|---|---|
'''
参考 https://github.com/7sDream/zhihu-py3/blob/master/zhihu/client.py
知乎认证部分
'''
import os
import time
import json
import requests
from PIL import Image
from global_constant import *
class Authentication(object):
'''
知乎认证类,可用cookies(JSON数据格式)或者帐号密码登陆
若使用帐号密码登陆,则会将cookies以JSON数据格式保存至当前文件夹下
'''
def __init__(self, cookies_path=None, kw=None):
self.session = requests.Session()
self.session.headers.update(headers)
if cookies_path is not None:
assert isinstance(cookies_path, str)
self._login_with_cookies(cookies_path)
elif kw is not None:
self._login_with_email(kw)
else:
print("Input the parameter.")
def _login_with_cookies(self, cookies_path):
'''
使用cookies文件登陆
cookies_path:cookie文件路径
cookies是JSON数据格式
'''
try:
with open(cookies_path) as f:
cookies = f.read()
self.session.cookies.update(json.loads(cookies))
except FileNotFoundError as e:
print("No such file or directory.")
def _login_with_email(self, kw):
'''
使用帐号密码登陆
登陆过程:
请求 url: https://www.zhihu.com
获取 _xsrf
请求 url: https://www.zhihu.com/captcha.gif?r=*
获取 captcha.gif
手动输入 captcha
登陆
kw:帐号、密码字典
'''
xsrf = self._get_xsrf()
captcha = self._get_captcha()
form_data = {
'_xsrf': xsrf,
'captcha': captcha,
'remember_me': 'true'
}
form_data.update(kw)
response = self.session.post(login_url, data=form_data)
if response.status_code is 200:
print("Login sucessfully.")
self._save_cookies()
else:
print("Login failed.")
def _get_xsrf(self):
self.session.get(zhihu_url)
return self.session.cookies.get('_xsrf')
def _get_captcha(self):
captcha_url = captcha_url_prefix + str(int(time.time() * 1000))
response = self.session.get(captcha_url)
with open("captcha.gif", 'wb') as f:
for i in response:
f.write(i)
with open("captcha.gif", 'rb') as f:
Image.open(f).show()
os.remove("captcha.gif")
return input("Input the captcha.\n")
def _save_cookies(self):
'''
保存cookies至当前文件夹下
'''
with open('cookies.json', 'w') as f:
json.dump(self.session.cookies.get_dict(), f)
def set_proxy(self, proxy):
'''
设置代理
proxy: str, 形式: "('http', 'example.com:port')"
'''
self.session.proxies.update({proxy[0]+'://': proxy[1]})
| {
"content_hash": "720260f55e7e8e72a36dc1706d321072",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 71,
"avg_line_length": 28.31958762886598,
"alnum_prop": 0.5438660356752821,
"repo_name": "time-river/wander",
"id": "02a7c887276dcb2f09dd93de5cc5d068648ff6ea",
"size": "3038",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "practice/requests/zhihu/authentication.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "100268"
}
],
"symlink_target": ""
} |
namespace omaha {
namespace internal {
void CommandLineParserArgs::Reset() {
switch_arguments_.clear();
}
// Assumes switch_name is already lower case.
HRESULT CommandLineParserArgs::AddSwitch(const CString& switch_name) {
ASSERT1(CString(switch_name).MakeLower().Compare(switch_name) == 0);
if (switch_arguments_.find(switch_name) != switch_arguments_.end()) {
return E_INVALIDARG;
}
StringVector string_vector;
switch_arguments_[switch_name] = string_vector;
return S_OK;
}
// Assumes switch_name is already lower case.
HRESULT CommandLineParserArgs::AddSwitchArgument(const CString& switch_name,
const CString& value) {
ASSERT1(CString(switch_name).MakeLower().Compare(switch_name) == 0);
ASSERT1(!switch_name.IsEmpty());
if (switch_name.IsEmpty()) {
// We don't have a switch yet, so this is just a base argument.
// Example command line: "foo.exe myarg /someswitch"
// Here, myarg would be a base argument.
// TODO(omaha): base_args_.push_back(switch_name_str);
return E_INVALIDARG;
}
SwitchAndArgumentsMap::iterator iter = switch_arguments_.find(switch_name);
if (iter == switch_arguments_.end()) {
return E_UNEXPECTED;
}
(*iter).second.push_back(value);
return S_OK;
}
int CommandLineParserArgs::GetSwitchCount() const {
return switch_arguments_.size();
}
bool CommandLineParserArgs::HasSwitch(const CString& switch_name) const {
CString switch_name_lower = switch_name;
switch_name_lower.MakeLower();
return switch_arguments_.find(switch_name_lower) != switch_arguments_.end();
}
// The value at a particular index may change if switch_names are added
// since we're using a map underneath. But this keeps us from having to write
// an interator and expose it externally.
HRESULT CommandLineParserArgs::GetSwitchNameAtIndex(int index,
CString* name) const {
ASSERT1(name);
if (index >= static_cast<int>(switch_arguments_.size())) {
return E_INVALIDARG;
}
SwitchAndArgumentsMapIter iter = switch_arguments_.begin();
for (int i = 0; i < index; ++i) {
++iter;
}
*name = (*iter).first;
return S_OK;
}
HRESULT CommandLineParserArgs::GetSwitchArgumentCount(
const CString& switch_name, int* count) const {
ASSERT1(count);
CString switch_name_lower = switch_name;
switch_name_lower.MakeLower();
SwitchAndArgumentsMapIter iter = switch_arguments_.find(switch_name_lower);
if (iter == switch_arguments_.end()) {
return E_INVALIDARG;
}
*count = (*iter).second.size();
return S_OK;
}
HRESULT CommandLineParserArgs::GetSwitchArgumentValue(
const CString& switch_name,
int argument_index,
CString* argument_value) const {
ASSERT1(argument_value);
CString switch_name_lower = switch_name;
switch_name_lower.MakeLower();
int count = 0;
HRESULT hr = GetSwitchArgumentCount(switch_name_lower, &count);
if (FAILED(hr)) {
return hr;
}
if (argument_index >= count) {
return E_INVALIDARG;
}
SwitchAndArgumentsMapIter iter = switch_arguments_.find(switch_name_lower);
if (iter == switch_arguments_.end()) {
return E_INVALIDARG;
}
*argument_value = (*iter).second[argument_index];
return S_OK;
}
} // namespace internal
CommandLineParser::CommandLineParser() {
}
CommandLineParser::~CommandLineParser() {
}
HRESULT CommandLineParser::ParseFromString(const wchar_t* command_line) {
CString command_line_str(command_line);
command_line_str.Trim(_T(" "));
int argc = 0;
wchar_t** argv = ::CommandLineToArgvW(command_line_str, &argc);
if (!argv) {
return HRESULTFromLastError();
}
HRESULT hr = ParseFromArgv(argc, argv);
::LocalFree(argv);
return hr;
}
// TODO(Omaha): Move the rule parser into a separate class.
// TODO(Omaha): Fail the regular command parser if [/ switch is passed.
// ParseFromArgv parses either a rule or a command line.
//
// Rules have required and optional parameters. An example of a rule is:
// "gu.exe /install <extraargs> [/oem [/appargs <appargs> [/silent"
// This creates a rule for a command line that requires "/install" for the rule
// to match. The other parameters are optional, indicated by prefixes of "[/".
//
// Command lines do not use "[/", and use "/" for all parameters.
// A command line that looks like this:
// "gu.exe /install <extraargs> /oem /appargs <appargs>"
// will match the rule above.
HRESULT CommandLineParser::ParseFromArgv(int argc, wchar_t** argv) {
if (argc == 0 || !argv) {
return E_INVALIDARG;
}
CORE_LOG(L5, (_T("[CommandLineParser::ParseFromArgv][argc=%d]"), argc));
Reset();
if (argc == 1) {
// We only have the program name. So, we're done parsing.
ASSERT1(!IsSwitch(argv[0]));
return S_OK;
}
CString current_switch_name;
bool is_optional_switch = false;
// Start parsing at the first argument after the program name (index 1).
for (int i = 1; i < argc; ++i) {
HRESULT hr = S_OK;
CString token = argv[i];
token.Trim(_T(" "));
CORE_LOG(L5, (_T("[Parsing arg][i=%d][argv[i]=%s]"), i, token));
if (IsSwitch(token)) {
hr = StripSwitchNameFromArgv(token, ¤t_switch_name);
if (FAILED(hr)) {
return hr;
}
hr = AddSwitch(current_switch_name);
if (FAILED(hr)) {
CORE_LOG(LE, (_T("[AddSwitch failed][%s][0x%x]"),
current_switch_name, hr));
return hr;
}
is_optional_switch = false;
} else if (IsOptionalSwitch(token)) {
hr = StripOptionalSwitchNameFromArgv(token, ¤t_switch_name);
if (FAILED(hr)) {
return hr;
}
hr = AddOptionalSwitch(current_switch_name);
if (FAILED(hr)) {
CORE_LOG(LE, (_T("[AddOptionalSwitch failed][%s][0x%x]"),
current_switch_name, hr));
return hr;
}
is_optional_switch = true;
} else {
hr = is_optional_switch ?
AddOptionalSwitchArgument(current_switch_name, token) :
AddSwitchArgument(current_switch_name, token);
if (FAILED(hr)) {
CORE_LOG(LE, (_T("[Adding switch argument failed][%d][%s][%s][0x%x]"),
is_optional_switch, current_switch_name, token, hr));
return hr;
}
}
}
return S_OK;
}
bool CommandLineParser::IsSwitch(const CString& param) const {
// Switches must have a prefix (/) or (-), and at least one character.
if (param.GetLength() < 2) {
return false;
}
// All switches must start with / or -, and not contain any spaces.
// Since the argv parser strips out the enclosing quotes around an argument,
// we need to handle the following cases properly:
// * foo.exe /switch arg -- /switch is a switch, arg is an arg
// * foo.exe /switch "/x y" -- /switch is a switch, '/x y' is an arg and it
// will get here _without_ the quotes.
// If param_str starts with / and contains no spaces, then it's a switch.
return ((param[0] == _T('/')) || (param[0] == _T('-'))) &&
(param.Find(_T(" ")) == -1) &&
(param.Find(_T("%20")) == -1);
}
bool CommandLineParser::IsOptionalSwitch(const CString& param) const {
// Optional switches must have a prefix ([/) or ([-), and at least one
// character.
return param[0] == _T('[') && IsSwitch(param.Right(param.GetLength() - 1));
}
HRESULT CommandLineParser::StripSwitchNameFromArgv(const CString& param,
CString* switch_name) {
ASSERT1(switch_name);
if (!IsSwitch(param)) {
return E_INVALIDARG;
}
*switch_name = param.Right(param.GetLength() - 1);
switch_name->Trim(_T(" "));
switch_name->MakeLower();
return S_OK;
}
HRESULT CommandLineParser::StripOptionalSwitchNameFromArgv(const CString& param,
CString* name) {
ASSERT1(name);
if (!IsOptionalSwitch(param)) {
return E_INVALIDARG;
}
return StripSwitchNameFromArgv(param.Right(param.GetLength() - 1), name);
}
void CommandLineParser::Reset() {
required_args_.Reset();
optional_args_.Reset();
}
HRESULT CommandLineParser::AddSwitch(const CString& switch_name) {
ASSERT1(switch_name == CString(switch_name).MakeLower());
return required_args_.AddSwitch(switch_name);
}
HRESULT CommandLineParser::AddSwitchArgument(const CString& switch_name,
const CString& argument_value) {
ASSERT1(switch_name == CString(switch_name).MakeLower());
return required_args_.AddSwitchArgument(switch_name, argument_value);
}
int CommandLineParser::GetSwitchCount() const {
return required_args_.GetSwitchCount();
}
bool CommandLineParser::HasSwitch(const CString& switch_name) const {
return required_args_.HasSwitch(switch_name);
}
// The value at a particular index may change if switch_names are added
// since we're using a map underneath. But this keeps us from having to write
// an interator and expose it externally.
HRESULT CommandLineParser::GetSwitchNameAtIndex(int index,
CString* switch_name) const {
return required_args_.GetSwitchNameAtIndex(index, switch_name);
}
HRESULT CommandLineParser::GetSwitchArgumentCount(const CString& switch_name,
int* count) const {
return required_args_.GetSwitchArgumentCount(switch_name, count);
}
HRESULT CommandLineParser::GetSwitchArgumentValue(
const CString& switch_name,
int argument_index,
CString* argument_value) const {
return required_args_.GetSwitchArgumentValue(switch_name,
argument_index,
argument_value);
}
HRESULT CommandLineParser::AddOptionalSwitch(const CString& switch_name) {
ASSERT1(switch_name == CString(switch_name).MakeLower());
return optional_args_.AddSwitch(switch_name);
}
HRESULT CommandLineParser::AddOptionalSwitchArgument(const CString& switch_name,
const CString& value) {
ASSERT1(switch_name == CString(switch_name).MakeLower());
return optional_args_.AddSwitchArgument(switch_name, value);
}
int CommandLineParser::GetOptionalSwitchCount() const {
return optional_args_.GetSwitchCount();
}
bool CommandLineParser::HasOptionalSwitch(const CString& switch_name) const {
return optional_args_.HasSwitch(switch_name);
}
// The value at a particular index may change if switch_names are added
// since we're using a map underneath. But this keeps us from having to write
// an interator and expose it externally.
HRESULT CommandLineParser::GetOptionalSwitchNameAtIndex(int index,
CString* name) const {
return optional_args_.GetSwitchNameAtIndex(index, name);
}
HRESULT CommandLineParser::GetOptionalSwitchArgumentCount(const CString& name,
int* count) const {
return optional_args_.GetSwitchArgumentCount(name, count);
}
HRESULT CommandLineParser::GetOptionalSwitchArgumentValue(const CString& name,
int argument_index,
CString* val) const {
return optional_args_.GetSwitchArgumentValue(name,
argument_index,
val);
}
} // namespace omaha
| {
"content_hash": "503ca43fc87a4d8178cc54a2b11a163e",
"timestamp": "",
"source": "github",
"line_count": 354,
"max_line_length": 80,
"avg_line_length": 32.57344632768361,
"alnum_prop": 0.6390599254184373,
"repo_name": "taxilian/omaha",
"id": "66e9d3fa6bed99af015749e8b1330c759c72bfed",
"size": "12373",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "goopdate/command_line_parser.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1957"
},
{
"name": "C",
"bytes": "2626743"
},
{
"name": "C#",
"bytes": "2385"
},
{
"name": "C++",
"bytes": "4634004"
},
{
"name": "Python",
"bytes": "103638"
}
],
"symlink_target": ""
} |
<?php
namespace Turiknox\SLog\Model\ResourceModel\Category;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* Collection initialisation
*/
protected function _construct()
{
$this->_init('Turiknox\SLog\Model\Category','Turiknox\SLog\Model\ResourceModel\Category');
}
} | {
"content_hash": "2710403fb60dcd9ff18e621a37fb0a9a",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 98,
"avg_line_length": 21.952380952380953,
"alnum_prop": 0.6832971800433839,
"repo_name": "Turiknox/magento2-slog",
"id": "28d0041698b8c23c210001856f5d802eae8dc15b",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/Turiknox/SLog/Model/ResourceModel/Category/Collection.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "58136"
}
],
"symlink_target": ""
} |

This is the official github repository for NAV Coin. NAV Coin is the worlds first anonymous cryptocurrency powered by blockchain technology. It's anonymous network is completely powered by a separate Blockchain known as the NAV Subchain. For more information please visit the website:
http://www.navcoin.org
## Coin Specifications
| Specification | Value |
|:-----------|:-----------|
| Block Spacing | `30 seconds` |
| Stake Minimum Age | `2 hours` |
| Stake Maximum Age | `24 hours` |
| Stake Reward | `5% per annum` |
| Port | `44440` |
| RPC Port | `44444` |
## Navtech Settings
| Specification | Value |
|:-----------|:-----------|
| addanonserver | `95.183.52.55:3000` |
| addanonserver | `95.183.53.184:3000` |
| addanonserver | `95.183.52.28:3000` |
| addanonserver | `95.183.52.29:3000` |
| anonhash | `000c17f28eaa71f48de6d8856fc3a22f` |
## Social Channels
| Site | link |
|:-----------|:-----------|
| Bitcointalk | https://bitcointalk.org/index.php?topic=679791 |
| Facebook | https://www.facebook.com/NAVCoin |
| Twitter | https://twitter.com/NavCoin |
| Reddit | http://www.reddit.com/r/navcoin |
| Slack | https://navcoin-sign-up.herokuapp.com |
| Telegram | https://telegram.me/joinchat/COuj0kE7K01APpfZSq3i7Q |
## Navtech Decentralization
We are working towards a lot of cool projects, our major upcoming milestone is the decentralisation of our Navtech Anon network. For more information please see our projects page:
http://www.navcoin.org/projects
| {
"content_hash": "4b35f3d88c6b0a942f13b033dbe121a4",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 284,
"avg_line_length": 37.093023255813954,
"alnum_prop": 0.69717868338558,
"repo_name": "navcoindev/navcoin2",
"id": "40da1af179021d1bb9262bf6258ebe5a25531f28",
"size": "1595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "3657260"
},
{
"name": "C++",
"bytes": "4418557"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50617"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "M4",
"bytes": "18274"
},
{
"name": "Makefile",
"bytes": "16184"
},
{
"name": "NSIS",
"bytes": "5907"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "3517"
},
{
"name": "Python",
"bytes": "94499"
},
{
"name": "QMake",
"bytes": "21656"
},
{
"name": "Shell",
"bytes": "8552"
}
],
"symlink_target": ""
} |
require "helper"
describe Google::Cloud do
describe "#spanner" do
it "calls out to Google::Cloud.spanner" do
gcloud = Google::Cloud.new
stubbed_spanner = ->(project, keyfile, scope: nil, timeout: nil, client_config: nil) {
project.must_be :nil?
keyfile.must_be :nil?
scope.must_be :nil?
timeout.must_be :nil?
client_config.must_be :nil?
"spanner-project-object-empty"
}
Google::Cloud.stub :spanner, stubbed_spanner do
project = gcloud.spanner
project.must_equal "spanner-project-object-empty"
end
end
it "passes project and keyfile to Google::Cloud.spanner" do
gcloud = Google::Cloud.new "project-id", "keyfile-path"
stubbed_spanner = ->(project, keyfile, scope: nil, timeout: nil, client_config: nil) {
project.must_equal "project-id"
keyfile.must_equal "keyfile-path"
scope.must_be :nil?
timeout.must_be :nil?
client_config.must_be :nil?
"spanner-project-object"
}
Google::Cloud.stub :spanner, stubbed_spanner do
project = gcloud.spanner
project.must_equal "spanner-project-object"
end
end
it "passes project and keyfile and options to Google::Cloud.spanner" do
gcloud = Google::Cloud.new "project-id", "keyfile-path"
stubbed_spanner = ->(project, keyfile, scope: nil, timeout: nil, client_config: nil) {
project.must_equal "project-id"
keyfile.must_equal "keyfile-path"
scope.must_equal "http://example.com/scope"
timeout.must_equal 60
client_config.must_equal({ "gax" => "options" })
"spanner-project-object-scoped"
}
Google::Cloud.stub :spanner, stubbed_spanner do
project = gcloud.spanner scope: "http://example.com/scope", timeout: 60, client_config: { "gax" => "options" }
project.must_equal "spanner-project-object-scoped"
end
end
end
describe ".spanner" do
let(:default_credentials) do
creds = OpenStruct.new empty: true
def creds.is_a? target
target == Google::Auth::Credentials
end
creds
end
let(:found_credentials) { "{}" }
it "gets defaults for project_id and keyfile" do
# Clear all environment variables
ENV.stub :[], nil do
# Get project_id from Google Compute Engine
Google::Cloud.stub :env, OpenStruct.new(project_id: "project-id") do
Google::Cloud::Spanner::Credentials.stub :default, default_credentials do
spanner = Google::Cloud.spanner
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.credentials.must_equal default_credentials
end
end
end
end
it "uses provided project_id and keyfile" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_be :nil?
client_config.must_be :nil?
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud.spanner "project-id", "path/to/keyfile.json"
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
end
describe "Spanner.new" do
let(:default_credentials) do
creds = OpenStruct.new empty: true
def creds.is_a? target
target == Google::Auth::Credentials
end
creds
end
let(:found_credentials) { "{}" }
it "gets defaults for project_id and keyfile" do
# Clear all environment variables
ENV.stub :[], nil do
# Get project_id from Google Compute Engine
Google::Cloud.stub :env, OpenStruct.new(project_id: "project-id") do
Google::Cloud::Spanner::Credentials.stub :default, default_credentials do
spanner = Google::Cloud::Spanner.new
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.credentials.must_equal default_credentials
end
end
end
end
it "uses provided project_id and credentials" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_be :nil?
client_config.must_be :nil?
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new project_id: "project-id", credentials: "path/to/keyfile.json"
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
it "uses provided project and keyfile aliases" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_be :nil?
client_config.must_be :nil?
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new project: "project-id", keyfile: "path/to/keyfile.json"
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
end
describe "Spanner.configure" do
let(:found_credentials) { "{}" }
let :spanner_client_config do
{"interfaces"=>
{"google.spanner.v1.Spanner"=>
{"retry_codes"=>{"idempotent"=>["DEADLINE_EXCEEDED", "UNAVAILABLE"]}}}}
end
after do
Google::Cloud.configure.reset!
end
it "uses shared config for project and keyfile" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_be :nil?
client_config.must_be :nil?
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
# Set new configuration
Google::Cloud.configure do |config|
config.project = "project-id"
config.keyfile = "path/to/keyfile.json"
end
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
it "uses shared config for project_id and credentials" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_be :nil?
client_config.must_be :nil?
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
# Set new configuration
Google::Cloud.configure do |config|
config.project_id = "project-id"
config.credentials = "path/to/keyfile.json"
end
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
it "uses spanner config for project and keyfile" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_equal 42
client_config.must_equal spanner_client_config
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
# Set new configuration
Google::Cloud::Spanner.configure do |config|
config.project = "project-id"
config.keyfile = "path/to/keyfile.json"
config.timeout = 42
config.client_config = spanner_client_config
end
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
it "uses spanner config for project_id and credentials" do
stubbed_credentials = ->(keyfile, scope: nil) {
keyfile.must_equal "path/to/keyfile.json"
scope.must_be :nil?
"spanner-credentials"
}
stubbed_service = ->(project, credentials, timeout: nil, client_config: nil) {
project.must_equal "project-id"
credentials.must_equal "spanner-credentials"
timeout.must_equal 42
client_config.must_equal spanner_client_config
OpenStruct.new project: project
}
# Clear all environment variables
ENV.stub :[], nil do
# Set new configuration
Google::Cloud::Spanner.configure do |config|
config.project_id = "project-id"
config.credentials = "path/to/keyfile.json"
config.timeout = 42
config.client_config = spanner_client_config
end
File.stub :file?, true, ["path/to/keyfile.json"] do
File.stub :read, found_credentials, ["path/to/keyfile.json"] do
Google::Cloud::Spanner::Credentials.stub :new, stubbed_credentials do
Google::Cloud::Spanner::Service.stub :new, stubbed_service do
spanner = Google::Cloud::Spanner.new
spanner.must_be_kind_of Google::Cloud::Spanner::Project
spanner.project.must_equal "project-id"
spanner.service.must_be_kind_of OpenStruct
end
end
end
end
end
end
end
end
| {
"content_hash": "77669057d9d5de6a973c4bba93dee0ce",
"timestamp": "",
"source": "github",
"line_count": 363,
"max_line_length": 118,
"avg_line_length": 37.170798898071624,
"alnum_prop": 0.6027569851033869,
"repo_name": "quartzmo/gcloud-ruby",
"id": "37d93ccc1a4e2c6a3d69cf393e34f8b25f7da302",
"size": "14069",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "google-cloud-spanner/test/google/cloud/spanner_test.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Protocol Buffer",
"bytes": "20395"
},
{
"name": "Ruby",
"bytes": "562364"
}
],
"symlink_target": ""
} |
The matched value was assigned in a match guard.
Erroneous code example:
```compile_fail,E0510
let mut x = Some(0);
match x {
None => {}
Some(_) if { x = None; false } => {} // error!
Some(_) => {}
}
```
When matching on a variable it cannot be mutated in the match guards, as this
could cause the match to be non-exhaustive.
Here executing `x = None` would modify the value being matched and require us
to go "back in time" to the `None` arm. To fix it, change the value in the match
arm:
```
let mut x = Some(0);
match x {
None => {}
Some(_) => {
x = None; // ok!
}
}
```
| {
"content_hash": "2d054a777eccea3985050dc781acd5fa",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 80,
"avg_line_length": 21.06896551724138,
"alnum_prop": 0.6104746317512275,
"repo_name": "graydon/rust",
"id": "e045e04bdbe11ac23b981af155fbfa163c581269",
"size": "611",
"binary": false,
"copies": "19",
"ref": "refs/heads/master",
"path": "compiler/rustc_error_codes/src/error_codes/E0510.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4990"
},
{
"name": "Assembly",
"bytes": "20064"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "Bison",
"bytes": "78848"
},
{
"name": "C",
"bytes": "725899"
},
{
"name": "C++",
"bytes": "55803"
},
{
"name": "CSS",
"bytes": "22181"
},
{
"name": "JavaScript",
"bytes": "36295"
},
{
"name": "LLVM",
"bytes": "1587"
},
{
"name": "Makefile",
"bytes": "227056"
},
{
"name": "Puppet",
"bytes": "16300"
},
{
"name": "Python",
"bytes": "142548"
},
{
"name": "RenderScript",
"bytes": "99815"
},
{
"name": "Rust",
"bytes": "18342682"
},
{
"name": "Shell",
"bytes": "269546"
},
{
"name": "TeX",
"bytes": "57"
}
],
"symlink_target": ""
} |
export * from './head'
export { default as App } from './app'
export { findResultsState } from './instantsearch'
| {
"content_hash": "7c6ec1d019d23321c14f629fab28cf3c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 50,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.6902654867256637,
"repo_name": "JeromeFitz/next.js",
"id": "ce4b600e6d79bb0f7698fc10a0c9d45f839da01b",
"size": "113",
"binary": false,
"copies": "9",
"ref": "refs/heads/canary",
"path": "examples/with-algolia-react-instantsearch/components/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "579"
},
{
"name": "CSS",
"bytes": "38864"
},
{
"name": "JavaScript",
"bytes": "8065763"
},
{
"name": "Rust",
"bytes": "165055"
},
{
"name": "SCSS",
"bytes": "5957"
},
{
"name": "Sass",
"bytes": "302"
},
{
"name": "Shell",
"bytes": "4512"
},
{
"name": "TypeScript",
"bytes": "4906530"
}
],
"symlink_target": ""
} |
<?php
namespace Mmoreram\Extractor\tests\Adapter;
use Mmoreram\Extractor\Adapter\ZipExtractorAdapter;
use Mmoreram\Extractor\Filesystem\TemporaryDirectory;
use PHPUnit_Framework_TestCase;
/**
* Class ZipExtractorAdapterTest
*/
class ZipExtractorAdapterTest extends PHPUnit_Framework_TestCase
{
/**
* Setup
*/
public function setUp()
{
$filesystem = new TemporaryDirectory();
$zipExtractorAdapter = new ZipExtractorAdapter($filesystem);
if (!$zipExtractorAdapter->isAvailable()) {
$this->markTestSkipped('PHP Zip extension not installed');
}
}
/**
* Test extract
*/
public function testExtract()
{
$filesystem = new TemporaryDirectory();
$zipExtractorAdapter = new ZipExtractorAdapter($filesystem);
$finder = $zipExtractorAdapter->extract(dirname(__FILE__) . '/Fixtures/file.zip');
$this->assertEquals($finder->count(), 3);
}
}
| {
"content_hash": "799e826eeb93bc9e323e094895e4b138",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 90,
"avg_line_length": 24.125,
"alnum_prop": 0.6601036269430052,
"repo_name": "mmoreram/extractor",
"id": "52f4f96e52b8b2f9d3c05bfb944f6e1a37ce176e",
"size": "1247",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/Adapter/ZipExtractorAdapterTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "38698"
}
],
"symlink_target": ""
} |
package com.evolveum.midpoint.web.page.admin.resources.content;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.AuthorizationAction;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.AjaxSubmitButton;
import com.evolveum.midpoint.web.component.prism.ContainerStatus;
import com.evolveum.midpoint.web.component.prism.ObjectWrapper;
import com.evolveum.midpoint.web.component.prism.PrismObjectPanel;
import com.evolveum.midpoint.web.component.util.LoadableModel;
import com.evolveum.midpoint.web.component.util.ObjectWrapperUtil;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.resources.PageAdminResources;
import com.evolveum.midpoint.web.page.admin.resources.PageResources;
import com.evolveum.midpoint.web.resource.img.ImgResources;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.web.util.WebModelUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.util.string.StringValue;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author lazyman
*/
@PageDescriptor(url = "/admin/resources/account", encoder = OnePageParameterEncoder.class, action = {
@AuthorizationAction(actionUri = PageAdminResources.AUTH_RESOURCE_ALL,
label = PageAdminResources.AUTH_RESOURCE_ALL_LABEL,
description = PageAdminResources.AUTH_RESOURCE_ALL_DESCRIPTION),
@AuthorizationAction(actionUri = AuthorizationConstants.NS_AUTHORIZATION + "#resourcesAccount",
label = "PageAccount.auth.resourcesAccount.label",
description = "PageAccount.auth.resourcesAccount.description")})
public class PageAccount extends PageAdminResources {
private static final Trace LOGGER = TraceManager.getTrace(PageAccount.class);
private static final String DOT_CLASS = PageAccount.class.getName() + ".";
private static final String OPERATION_LOAD_ACCOUNT = DOT_CLASS + "loadAccount";
private static final String OPERATION_SAVE_ACCOUNT = DOT_CLASS + "saveAccount";
private static final String ID_PROTECTED_MESSAGE = "protectedMessage";
private IModel<ObjectWrapper> accountModel;
public PageAccount() {
accountModel = new LoadableModel<ObjectWrapper>(false) {
@Override
protected ObjectWrapper load() {
return loadAccount();
}
};
initLayout();
}
private ObjectWrapper loadAccount() {
OperationResult result = new OperationResult(OPERATION_LOAD_ACCOUNT);
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(
ShadowType.F_RESOURCE, GetOperationOptions.createResolve());
StringValue oid = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
PrismObject<ShadowType> account = WebModelUtils.loadObject(ShadowType.class, oid.toString(), options,
result, PageAccount.this);
if (account == null) {
getSession().error(getString("pageAccount.message.cantEditAccount"));
showResultInSession(result);
throw new RestartResponseException(PageResources.class);
}
ObjectWrapper wrapper = ObjectWrapperUtil.createObjectWrapper(null, null, account, ContainerStatus.MODIFYING, this);
OperationResultType fetchResult = account.getPropertyRealValue(ShadowType.F_FETCH_RESULT, OperationResultType.class);
wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult));
wrapper.setShowEmpty(false);
return wrapper;
}
private void initLayout() {
Form mainForm = new Form("mainForm");
mainForm.setMultiPart(true);
add(mainForm);
WebMarkupContainer protectedMessage = new WebMarkupContainer(ID_PROTECTED_MESSAGE);
protectedMessage.add(new VisibleEnableBehaviour() {
@Override
public boolean isVisible() {
ObjectWrapper wrapper = accountModel.getObject();
return wrapper.isProtectedAccount();
}
});
mainForm.add(protectedMessage);
PrismObjectPanel userForm = new PrismObjectPanel("account", accountModel, new PackageResourceReference(
ImgResources.class, ImgResources.HDD_PRISM), mainForm) {
@Override
protected IModel<String> createDescription(IModel<ObjectWrapper> model) {
return createStringResource("pageAccount.description");
}
};
mainForm.add(userForm);
initButtons(mainForm);
}
private void initButtons(Form mainForm) {
AjaxSubmitButton save = new AjaxSubmitButton("save", createStringResource("pageAccount.button.save")) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
savePerformed(target);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
target.add(getFeedbackPanel());
}
};
save.add(new VisibleEnableBehaviour() {
@Override
public boolean isVisible() {
ObjectWrapper wrapper = accountModel.getObject();
return !wrapper.isProtectedAccount();
}
});
mainForm.add(save);
AjaxButton back = new AjaxButton("back", createStringResource("pageAccount.button.back")) {
@Override
public void onClick(AjaxRequestTarget target) {
cancelPerformed(target);
}
};
mainForm.add(back);
}
@Override
protected IModel<String> createPageSubTitleModel() {
return new LoadableModel<String>(false) {
@Override
protected String load() {
PrismObject<ShadowType> account = accountModel.getObject().getObject();
ResourceType resource = account.asObjectable().getResource();
String name = WebMiscUtil.getName(resource);
return new StringResourceModel("page.subTitle", PageAccount.this, null, null, name).getString();
}
};
}
private void savePerformed(AjaxRequestTarget target) {
LOGGER.debug("Saving account changes.");
OperationResult result = new OperationResult(OPERATION_SAVE_ACCOUNT);
ObjectWrapper wrapper = accountModel.getObject();
try {
ObjectDelta<ShadowType> delta = wrapper.getObjectDelta();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Account delta computed from form:\n{}", new Object[]{delta.debugDump(3)});
}
if (delta == null || delta.isEmpty()) {
return;
}
WebMiscUtil.encryptCredentials(delta, true, getMidpointApplication());
Task task = createSimpleTask(OPERATION_SAVE_ACCOUNT);
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
deltas.add(delta);
getModelService().executeChanges(deltas, null, task, result);
result.recomputeStatus();
} catch (Exception ex) {
result.recordFatalError("Couldn't save account.", ex);
LoggingUtils.logException(LOGGER, "Couldn't save account", ex);
}
if (!result.isSuccess()) {
showResult(result);
target.add(getFeedbackPanel());
} else {
showResultInSession(result);
returnToAccountList();
}
}
private void cancelPerformed(AjaxRequestTarget target) {
returnToAccountList();
}
private void returnToAccountList() {
PrismObject<ShadowType> account = accountModel.getObject().getObject();
ResourceType resource = account.asObjectable().getResource();
PageParameters parameters = new PageParameters();
parameters.add(OnePageParameterEncoder.PARAMETER, resource.getOid());
setResponsePage(PageContentAccounts.class, parameters);
}
} | {
"content_hash": "d1417819de5aa71a3e138dab75039972",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 125,
"avg_line_length": 41.275862068965516,
"alnum_prop": 0.693922305764411,
"repo_name": "sabriarabacioglu/engerek",
"id": "a02fc5e019e869f4a29231185422c7c4eab88f9f",
"size": "10176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/content/PageAccount.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "374009"
},
{
"name": "Groovy",
"bytes": "10361"
},
{
"name": "Java",
"bytes": "14663183"
},
{
"name": "JavaScript",
"bytes": "71684"
},
{
"name": "Shell",
"bytes": "3606"
}
],
"symlink_target": ""
} |
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
<cbid>CROMU_00001</cbid>
<replay>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>3\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>upfbtfhf\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>pnkrpjojwcqxjhvzykccs\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>kskndwkjdfz\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1: kskndwkjdfz\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>5\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>4\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>jfojgqa\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>jxpfwixbdngzmgtkcmgg\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: jxpfwixbdngzmgtkcmgg\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>3\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: jxpfwixbdngzmgtkcmgg\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>sgudquohobfchiarsfguqcdkw\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3: sgudquohobfchiarsfguqcdkw\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: jxpfwixbdngzmgtkcmgg\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>yusawdbnkkvjybxqtpobtokhy\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4: yusawdbnkkvjybxqtpobtokhy\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>5\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1: upfbtfhf\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: pnkrpjojwcqxjhvzykccs\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3: jfojgqa\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>lmkkqzlcxcrpocsgjluifvlur\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>5\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>3\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1: upfbtfhf\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: pnkrpjojwcqxjhvzykccs\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3: jfojgqa\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1: upfbtfhf\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>bfthcngikrbzwnaf\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4: bfthcngikrbzwnaf\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>ulhkarg\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>gqyhwowfm\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>4\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>3\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>4\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4: bfthcngikrbzwnaf\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>oowqtmdqzdthrdfkehe\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5: oowqtmdqzdthrdfkehe\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>omysnrn\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>lhfwnflgfwktnyseqnbjneuaat\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6: lhfwnflgfwktnyseqnbjneuaat\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>6\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6: lhfwnflgfwktnyseqnbjneuaat\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>6\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Exiting...\n</data></match></read>
</replay>
</pov>
| {
"content_hash": "d044fa79bacb171b14e2c8f90a571148",
"timestamp": "",
"source": "github",
"line_count": 379,
"max_line_length": 110,
"avg_line_length": 81.55408970976254,
"alnum_prop": 0.6129606263547834,
"repo_name": "f0rki/cb-multios",
"id": "ad98ee7ce88c7cadc7ba3157aa83c0bfc465cc15",
"size": "30909",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "original-challenges/basic_messaging/poller/for-release/POLL_00809.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6510"
},
{
"name": "C",
"bytes": "83182317"
},
{
"name": "C++",
"bytes": "2007200"
},
{
"name": "CMake",
"bytes": "4910"
},
{
"name": "GDB",
"bytes": "114"
},
{
"name": "Groff",
"bytes": "262159"
},
{
"name": "Logos",
"bytes": "2944"
},
{
"name": "Makefile",
"bytes": "9008"
},
{
"name": "Objective-C",
"bytes": "98709"
},
{
"name": "Python",
"bytes": "11805403"
},
{
"name": "Ruby",
"bytes": "4515"
},
{
"name": "Shell",
"bytes": "3779"
}
],
"symlink_target": ""
} |
package org.springframework.boot.actuate.metrics.web.client;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.stream.StreamSupport;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
import org.springframework.test.web.client.response.MockRestResponseCreators;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MetricsRestTemplateCustomizer}.
*
* @author Jon Schneider
* @author Brian Clozel
*/
public class MetricsRestTemplateCustomizerTests {
private MeterRegistry registry;
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
private MetricsRestTemplateCustomizer customizer;
@Before
public void setup() {
this.registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
this.customizer = new MetricsRestTemplateCustomizer(this.registry,
new DefaultRestTemplateExchangeTagsProvider(), "http.client.requests");
this.customizer.customize(this.restTemplate);
}
@Test
public void interceptRestTemplate() {
this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123"))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withSuccess("OK",
MediaType.APPLICATION_JSON));
String result = this.restTemplate.getForObject("/test/{id}", String.class, 123);
assertThat(this.registry.find("http.client.requests").meters())
.anySatisfy((m) -> assertThat(
StreamSupport.stream(m.getId().getTags().spliterator(), false)
.map(Tag::getKey)).doesNotContain("bucket"));
assertThat(this.registry.get("http.client.requests")
.tags("method", "GET", "uri", "/test/{id}", "status", "200").timer()
.count()).isEqualTo(1);
assertThat(result).isEqualTo("OK");
this.mockServer.verify();
}
@Test
public void avoidDuplicateRegistration() {
this.customizer.customize(this.restTemplate);
assertThat(this.restTemplate.getInterceptors()).hasSize(1);
this.customizer.customize(this.restTemplate);
assertThat(this.restTemplate.getInterceptors()).hasSize(1);
}
@Test
public void normalizeUriToContainLeadingSlash() {
this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123"))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withSuccess("OK",
MediaType.APPLICATION_JSON));
String result = this.restTemplate.getForObject("test/{id}", String.class, 123);
this.registry.get("http.client.requests").tags("uri", "/test/{id}").timer();
assertThat(result).isEqualTo("OK");
this.mockServer.verify();
}
@Test
public void interceptRestTemplateWithUri() throws URISyntaxException {
this.mockServer
.expect(MockRestRequestMatchers.requestTo("http://localhost/test/123"))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withSuccess("OK",
MediaType.APPLICATION_JSON));
String result = this.restTemplate
.getForObject(new URI("http://localhost/test/123"), String.class);
assertThat(result).isEqualTo("OK");
this.registry.get("http.client.requests").tags("uri", "/test/123").timer();
this.mockServer.verify();
}
}
| {
"content_hash": "877d16ba01f082a15fc065ee9e81d89c",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 82,
"avg_line_length": 36.95192307692308,
"alnum_prop": 0.7717928701535259,
"repo_name": "tsachev/spring-boot",
"id": "ead7838d65fc53a4c461584ad013b3d5d1bb43ca",
"size": "4463",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1948"
},
{
"name": "CSS",
"bytes": "5769"
},
{
"name": "FreeMarker",
"bytes": "3599"
},
{
"name": "Groovy",
"bytes": "51602"
},
{
"name": "HTML",
"bytes": "69601"
},
{
"name": "Java",
"bytes": "13587483"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Kotlin",
"bytes": "25029"
},
{
"name": "Ruby",
"bytes": "1308"
},
{
"name": "Shell",
"bytes": "31455"
},
{
"name": "Smarty",
"bytes": "2885"
},
{
"name": "XSLT",
"bytes": "36394"
}
],
"symlink_target": ""
} |
//
// This file is part of Wiggly project
//
// Created by JC on 03/31/13.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
#import <Foundation/Foundation.h>
/**
* Contain information about a route parameter
*/
@interface WIRoutePlaceholder : NSObject
@property(nonatomic, copy, readonly)NSString *name;
@property(nonatomic, strong)NSString *conditions;
@property(nonatomic)BOOL required;
- (id)initWithName:(NSString *)name;
/**
* Check that value respect the conditions
*
* @param value the value to check conditions on
* @return YES if conditions are fulfilled, NO otherwise
*/
- (BOOL)matchConditions:(NSString *)value;
@end
| {
"content_hash": "291450d5c05f16fd3ec09a760c0f0aff",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 74,
"avg_line_length": 25.366666666666667,
"alnum_prop": 0.7030223390275953,
"repo_name": "KptainO/Wiggly",
"id": "0ea46c609fbfef99a035eeb2af81361afb60692b",
"size": "761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Wiggly/WIRoutePlaceholder.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "38218"
},
{
"name": "Ruby",
"bytes": "609"
}
],
"symlink_target": ""
} |
package api;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
public class VerifySigning extends APIServlet.APIRequestHandler {
public static void popupRequest(JSONObject info)
{
}
static final VerifySigning instance = new VerifySigning();
private VerifySigning() {
super(new APITag[] {});
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) {
return null;
}
} | {
"content_hash": "bafc15a99ad0a1d42ccdd416c6de1a7e",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 65,
"avg_line_length": 19.192307692307693,
"alnum_prop": 0.7274549098196392,
"repo_name": "jonesnxt/jaywallet",
"id": "37257400c09d8e919e23abc344c7d0e6e00dcad7",
"size": "499",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/api/VerifySigning.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "124561"
},
{
"name": "Java",
"bytes": "144911"
},
{
"name": "JavaScript",
"bytes": "886308"
}
],
"symlink_target": ""
} |
learnGATK
=========
[PGG]learn GATK workflow with a few genomic data
| {
"content_hash": "f40b4f92e35e9ab643d10640772afcdc",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 48,
"avg_line_length": 17.5,
"alnum_prop": 0.6857142857142857,
"repo_name": "WANGxiaoji/learnGATK",
"id": "4e36d593bc4fc1ba1053f3fb8076baa4a254556c",
"size": "70",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq.Mapping;
using OpenRiaServices.DomainServices.Server;
namespace OpenRiaServices.DomainServices.LinqToSql
{
internal class LinqToSqlDomainServiceDescriptionProvider : DomainServiceDescriptionProvider
{
private static Dictionary<Type, LinqToSqlTypeDescriptionContext> tdpContextMap = new Dictionary<Type, LinqToSqlTypeDescriptionContext>();
private LinqToSqlTypeDescriptionContext _typeDescriptionContext;
private Dictionary<Type, ICustomTypeDescriptor> _descriptors = new Dictionary<Type, ICustomTypeDescriptor>();
public LinqToSqlDomainServiceDescriptionProvider(Type domainServiceType, Type dataContextType, DomainServiceDescriptionProvider parent)
: base(domainServiceType, parent)
{
lock (tdpContextMap)
{
if (!tdpContextMap.TryGetValue(dataContextType, out this._typeDescriptionContext))
{
// create and cache a context for this provider type
this._typeDescriptionContext = new LinqToSqlTypeDescriptionContext(dataContextType);
tdpContextMap.Add(dataContextType, this._typeDescriptionContext);
}
}
}
public override bool LookupIsEntityType(Type type)
{
MetaType metaType = this._typeDescriptionContext.MetaModel.GetMetaType(type);
return metaType.IsEntity;
}
/// <summary>
/// Returns a custom type descriptor for the specified entity type
/// </summary>
/// <param name="objectType">Type of object for which we need the descriptor</param>
/// <param name="parent">The parent type descriptor</param>
/// <returns>a custom type descriptor for the specified entity type</returns>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, ICustomTypeDescriptor parent)
{
// No need to deal with concurrency... Worst case scenario we have multiple
// instances of this thing.
ICustomTypeDescriptor td = null;
if (!this._descriptors.TryGetValue(objectType, out td))
{
// call into base so the TDs are chained
parent = base.GetTypeDescriptor(objectType, parent);
MetaType metaType = this._typeDescriptionContext.MetaModel.GetMetaType(objectType);
if (metaType.IsEntity)
{
// only add an LTS TypeDescriptor if the type is a LTS Entity type
td = new LinqToSqlTypeDescriptor(this._typeDescriptionContext, metaType, parent);
}
else
{
td = parent;
}
this._descriptors[objectType] = td;
}
return td;
}
}
}
| {
"content_hash": "3ee853871a5770ecb112ab3a5a3b8a42",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 145,
"avg_line_length": 43.55882352941177,
"alnum_prop": 0.6350438892640108,
"repo_name": "jeffhandley/OpenRiaServices",
"id": "d58ac97f7f302e1ce6e5531f91a8f77564047034",
"size": "2964",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OpenRiaServices.DomainServices.LinqToSql/Framework/LinqToSqlDomainServiceDescriptionProvider.cs",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "814"
},
{
"name": "C#",
"bytes": "19300576"
},
{
"name": "CSS",
"bytes": "3899"
},
{
"name": "HTML",
"bytes": "8541"
},
{
"name": "PowerShell",
"bytes": "1793"
},
{
"name": "Visual Basic",
"bytes": "4874395"
}
],
"symlink_target": ""
} |
int main(int argc, const char * argv[]) {
typedef hellodjinni::HelloDjinni HelloDjinni;
auto hd = HelloDjinni::create();
auto result = hd->get_hello_djinni();
std::cout << result << std::endl;
return 0;
}
| {
"content_hash": "6c119026302d764b917aef5d184afc14",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 49,
"avg_line_length": 25.22222222222222,
"alnum_prop": 0.6299559471365639,
"repo_name": "joinAero/XCalculator",
"id": "6100e460f6727ea00552e567a8aa16a984934944",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sample/hellodjinni/project/cpp/HelloDjinni/HelloDjinni/main.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "1199"
},
{
"name": "Java",
"bytes": "5319"
},
{
"name": "Makefile",
"bytes": "5579"
},
{
"name": "Objective-C",
"bytes": "3974"
},
{
"name": "Objective-C++",
"bytes": "331"
},
{
"name": "Python",
"bytes": "1630"
},
{
"name": "Shell",
"bytes": "9174"
}
],
"symlink_target": ""
} |
/*
* Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleSystemsManagement.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListAssociations operation
/// </summary>
public class ListAssociationsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListAssociationsResponse response = new ListAssociationsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Associations", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Association, AssociationUnmarshaller>(AssociationUnmarshaller.Instance);
response.Associations = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerError"))
{
return new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidNextToken"))
{
return new InvalidNextTokenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonSimpleSystemsManagementException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static ListAssociationsResponseUnmarshaller _instance = new ListAssociationsResponseUnmarshaller();
internal static ListAssociationsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListAssociationsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | {
"content_hash": "00fe133ee1fa3cd9ceb1dec5307c7837",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 178,
"avg_line_length": 38.6530612244898,
"alnum_prop": 0.6430834213305174,
"repo_name": "mwilliamson-firefly/aws-sdk-net",
"id": "11033e721937f7556f747ecf4ca515b054ada667",
"size": "4375",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/ListAssociationsResponseUnmarshaller.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "73553647"
},
{
"name": "CSS",
"bytes": "18119"
},
{
"name": "HTML",
"bytes": "24362"
},
{
"name": "JavaScript",
"bytes": "6576"
},
{
"name": "PowerShell",
"bytes": "12587"
},
{
"name": "XSLT",
"bytes": "7010"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_paramsetter"
>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txt_operator"
/>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_operator"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/txt_product_type"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_product_type"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/txt_product_id"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_product_id"
/>
</TableRow>
<TableRow
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/txt_produce_date"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_produce_date"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/txt_measure_date"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_measure_date"
/>
</TableRow>
<TableRow
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/txt_comment"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="@string/txt_edt_hint"
android:id="@+id/edt_comment"
/>
</TableRow>
</LinearLayout> | {
"content_hash": "137b75e107f6858944eb0c4ba5f38e5e",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 72,
"avg_line_length": 37.625,
"alnum_prop": 0.5523255813953488,
"repo_name": "ChinoMars/bccAndroidController",
"id": "b57685230b64a3e6ecd7f9e3baf124a044d0d0c1",
"size": "3612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/parameditor.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "69695"
}
],
"symlink_target": ""
} |
import { compile } from '../utils/helpers';
QUnit.module('ember-htmlbars: compile');
QUnit.test('calls template on the compiled function', function() {
let templateString = '{{foo}} -- {{some-bar blah=\'foo\'}}';
let actual = compile(templateString);
ok(actual.isTop, 'sets isTop via template function');
ok(actual.isMethod === false, 'sets isMethod via template function');
});
| {
"content_hash": "47833f5ce628e8c9f56359b6f8e6b088",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 71,
"avg_line_length": 30.153846153846153,
"alnum_prop": 0.6836734693877551,
"repo_name": "skeate/ember.js",
"id": "29b3fa3fe2174f7341b34c153c361395736db09a",
"size": "392",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "packages/ember-htmlbars-template-compiler/tests/system/compile_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7365"
},
{
"name": "JavaScript",
"bytes": "3453634"
},
{
"name": "Ruby",
"bytes": "1925"
},
{
"name": "Shell",
"bytes": "2490"
}
],
"symlink_target": ""
} |
// +build darwin
/*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package disk
import (
"strconv"
"syscall"
)
// fsType2StrinMap - list of filesystems supported by donut
var fsType2StringMap = map[string]string{
"11": "HFS",
}
// getFSType returns the filesystem type of the underlying mounted filesystem
func getFSType(path string) (string, error) {
s := syscall.Statfs_t{}
err := syscall.Statfs(path, &s)
if err != nil {
return "", err
}
fsTypeHex := strconv.FormatUint(uint64(s.Type), 16)
fsTypeString, ok := fsType2StringMap[fsTypeHex]
if !ok {
return "UNKNOWN", nil
}
return fsTypeString, nil
}
| {
"content_hash": "805ecdbd4852f026577b3ee97f3fe543",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 77,
"avg_line_length": 26.863636363636363,
"alnum_prop": 0.7157360406091371,
"repo_name": "koolhead17/minio",
"id": "c000e1a08fbdfac1ce2e1952c582ba4123fb1a3f",
"size": "1182",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "pkg/disk/type_darwin.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2594515"
},
{
"name": "Makefile",
"bytes": "3666"
},
{
"name": "Shell",
"bytes": "12089"
}
],
"symlink_target": ""
} |
/* HTML5 ✰ Boilerplate */
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
blockquote, q { quotes: none; }
blockquote:before, blockquote:after,
q:before, q:after { content: ''; content: none; }
ins { background-color: #ff9; color: #000; text-decoration: none; }
mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; }
del { text-decoration: line-through; }
abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; }
table { border-collapse: collapse; border-spacing: 0; }
hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }
input, select { vertical-align: middle; }
body {font:12px/18px Lucida Sans, sans-serif;}
select, input, textarea, button { font:99% sans-serif; }
pre, code, kbd, samp { font-family: monospace, sans-serif; }
a:hover, a:active, *:focus, input:focus, button:focus { outline: none; }
ul, ol { margin-left: 2em; }
ol { list-style-type: decimal; }
nav ul, nav li { margin: 0; list-style:none; list-style-image: none; }
small { font-size: 85%; }
strong, th { font-weight: bold; }
td { vertical-align: top; }
sub, sup { font-size: 75%; line-height: 0; position: relative; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; padding: 15px; }
textarea { overflow: auto; }
.ie6 legend, .ie7 legend { margin-left: -7px; }
input[type="radio"] { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; }
.ie7 input[type="checkbox"] { vertical-align: baseline; }
.ie6 input { vertical-align: text-bottom; }
label, input[type="button"], input[type="submit"], input[type="image"], button { cursor: pointer; }
button, input, select, textarea { margin: 0; }
input:valid, textarea:valid { }
input:invalid, textarea:invalid { border-radius: 1px; -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; box-shadow: 0px 0px 5px red; }
.no-boxshadow input:invalid, .no-boxshadow textarea:invalid { background-color: #f0dddd; }
::-moz-selection{ background: #a1d8f0; color:#fff; text-shadow: none; }
::selection { background:#a1d8f0; color:#fff; text-shadow: none; }
a:link { -webkit-tap-highlight-color: #a1d8f0; }
button { width: auto; overflow: visible; }
.ie7 img { -ms-interpolation-mode: bicubic; }
body, select, input, textarea {color: #444; }
a, a:active, a:visited { color: #666; text-decoration:none; }
a:hover { color: #c00; }
.ir { display: block; text-indent: -999em; overflow: hidden; background-repeat: no-repeat; text-align: left; direction: ltr; }
.hidden { display: none; visibility: hidden; }
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; }
.invisible { visibility: hidden; }
.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }
@media all and (orientation:portrait) {
}
@media all and (orientation:landscape) {
}
@media screen and (max-device-width: 480px) {
/* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */
}
@media print {
* { background: transparent !important; color: black !important; text-shadow: none !important; filter:none !important;
-ms-filter: none !important; }
a, a:visited { color: #444 !important; text-decoration: underline; }
a[href]:after { content: " (" attr(href) ")"; }
abbr[title]:after { content: " (" attr(title) ")"; }
.ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }
pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
thead { display: table-header-group; }
tr, img { page-break-inside: avoid; }
@page { margin: 0.5cm; }
p, h2, h3 { orphans: 3; widows: 3; }
h2, h3{ page-break-after: avoid; }
}
| {
"content_hash": "071dc05bde1cb0c0771d741d20717f0b",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 155,
"avg_line_length": 41.75221238938053,
"alnum_prop": 0.6596015260703688,
"repo_name": "orlk/hopitrepo",
"id": "e2f3a4cbd66b34f4692b207af427dfc3972f4010",
"size": "4720",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "web/web/css/reset.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "Batchfile",
"bytes": "373"
},
{
"name": "CSS",
"bytes": "102659"
},
{
"name": "HTML",
"bytes": "155478"
},
{
"name": "JavaScript",
"bytes": "130336"
},
{
"name": "PHP",
"bytes": "257295"
},
{
"name": "Shell",
"bytes": "593"
}
],
"symlink_target": ""
} |
ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin
DEPS_PLT=$(CURDIR)/.deps_plt
# =============================================================================
# Verify that the programs we need to run are installed on this system
# =============================================================================
ERL = $(shell which erl)
ifeq ($(ERL),)
$(error "Erlang not available on this system")
endif
REBAR=$(shell which rebar)
# If building on travis, use the rebar in the current directory
ifeq ($(TRAVIS),true)
REBAR=$(CURDIR)/rebar
endif
ifeq ($(REBAR),)
REBAR=$(CURDIR)/rebar
endif
.PHONY: all compile test dialyzer clean distclean doc
all: compile test dialyzer
REBAR_URL=https://github.com/rebar/rebar/wiki/rebar
$(REBAR):
curl -Lo rebar $(REBAR_URL) || wget $(REBAR_URL)
chmod a+x rebar
get-rebar: $(REBAR)
compile: $(REBAR)
$(REBAR) compile
eunit: compile clean-common-test-data
$(REBAR) skip_deps=true eunit
ct: compile clean-common-test-data
mkdir -p $(CURDIR) logs
ct_run -pa $(CURDIR)/ebin \
-pa $(CURDIR)/deps/*/ebin \
-logdir $(CURDIR)/logs \
-dir $(CURDIR)/test/ \
-cover cover.spec
test: compile dialyzer eunit ct
$(DEPS_PLT): compile
@echo Building local erts plt at $(DEPS_PLT)
@echo
$(DIALYZER) --output_plt $(DEPS_PLT) --build_plt \
--apps erts kernel stdlib -r deps
dialyzer: compile $(DEPS_PLT)
@dialyzer -Wunderspecs -r ebin
doc:
$(REBAR) doc skip_deps=true
clean-common-test-data:
# We have to do this because of the unique way we generate test
# data. Without this rebar eunit gets very confused
- rm -rf $(CURDIR)/test/*_SUITE_data
clean: clean-common-test-data $(REBAR)
- rm -rf $(CURDIR)/test/*.beam
- rm -rf $(CURDIR)/logs
- rm -rf $(CURDIR)/ebin
$(REBAR) skip_deps=true clean
distclean: clean
- rm -rf $(DEPS_PLT)
$(REBAR) delete-deps
demo_shell: compile test
@erl -pa .eunit ebin -config pooler-example -s pooler manual_start
| {
"content_hash": "b25e456de2082e3d7f56a4b9bf28c720",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 79,
"avg_line_length": 24.175,
"alnum_prop": 0.6365046535677352,
"repo_name": "layerhq/pooler",
"id": "fc106c183ccfbd15d42733f2e7062c99b8509090",
"size": "1934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Erlang",
"bytes": "90740"
}
],
"symlink_target": ""
} |
set -e
supportRoot="$(cd $(dirname $0)/.. && pwd)"
checkoutRoot="$(cd ${supportRoot}/../.. && pwd)"
function die() {
echo "$@" >&2
exit 1
}
function usage() {
violation="$1"
die "
Usage: $0 <git treeish>
$0 <path>:<git treeish> <path>:<git treeish>
Validates that libraries built from the given versions are the same as
the build outputs built at HEAD. This can be used to validate that a refactor
did not change the outputs. If a git treeish is given with no path, the path is considered to be frameworks/support
Example: $0 HEAD^
Example: $0 prebuilts/androidx/external:HEAD^ frameworks/support:work^
* A git treeish is what you type when you run 'git checkout <git treeish>'
See also https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddeftree-ishatree-ishalsotreeish .
"
return 1
}
# Fills in a default repository path of "frameworks/support:" for any args that don't specify
# their repository. Given an input of: "work^ prebuilts/androidx/external:HEAD^", should return
# "frameworks/support:work^ prebuilts/androidx/external:HEAD^".
function expandCommitArgs() {
inputSpecs="$@"
outputSpecs=""
for spec in $inputSpecs; do
if echo "$spec" | grep -v ":" >/dev/null; then
spec="frameworks/support:$spec"
fi
outputSpecs="$outputSpecs $spec"
done
echo $outputSpecs
}
# Given a list of paths like "frameworks/support prebuilts/androidx/external",
# runs `git checkout -` in each
function uncheckout() {
repositoryPaths="$@"
for repositoryPath in $repositoryPaths; do
echoAndDo git -C "$checkoutRoot/$repositoryPath" checkout -
done
}
# Given a list of version specs like "a/b:c d/e:f", returns just the paths: "a/b d/e"
function getParticipatingProjectPaths() {
specs="$@"
result=""
for arg in $specs; do
echo parsing $arg >&2
repositoryPath="$(echo $arg | sed 's|\([^:]*\):\([^:]*\)|\1|')"
otherVersion="$(echo $arg | sed 's|\([^:]*\):\([^:]*\)|\2|')"
if [ "$otherVersion" != "HEAD" ]; then
result="$result $repositoryPath"
fi
done
echo $result
}
# Given a list of paths, returns a string containing the currently checked-out version of each
function getCurrentCommits() {
repositoryPaths="$@"
result=""
for repositoryPath in $repositoryPaths; do
currentVersion="$(cd $checkoutRoot/$repositoryPath && git log -1 --format=%H)"
result="$result $repositoryPath:$currentVersion"
done
echo $result
}
function echoAndDo() {
echo "$*"
eval "$*"
}
# Given a list of version specs like "a/b:c d/e:f", checks out the appropriate version in each
# In this example it would be `cd a/b && git checkout e` and `cd e/e && git checkout f`
function checkout() {
versionSpecs="$1"
for versionSpec in $versionSpecs; do
project="$(echo $versionSpec | sed 's|\([^:]*\):\([^:]*\)|\1|')"
ref="$(echo $versionSpec | sed 's|\([^:]*\):\([^:]*\)|\2|')"
echo "checking out $ref in project $project"
echoAndDo git -C "$checkoutRoot/$project" checkout "$ref"
done
}
function doBuild() {
# build androidx
echoAndDo ./gradlew createArchive generateDocs --no-daemon --rerun-tasks --offline
archiveName="top-of-tree-m2repository-all-0.zip"
echoAndDo unzip -q "${tempOutPath}/dist/${archiveName}" -d "${tempOutPath}/dist/${archiveName}.unzipped"
}
oldCommits="$(expandCommitArgs $@)"
projectPaths="$(getParticipatingProjectPaths $oldCommits)"
if echo $projectPaths | grep external/dokka >/dev/null; then
if [ "$BUILD_DOKKA" == "" ]; then
echo "It doesn't make sense to include the external/dokka project without also setting BUILD_DOKKA=true. Did you mean to set BUILD_DOKKA=true?"
exit 1
fi
fi
echo old commits: $oldCommits
if [ "$oldCommits" == "" ]; then
usage
fi
newCommits="$(getCurrentCommits $projectPaths)"
cd "$supportRoot"
echo new commits: $newCommits
oldOutPath="${checkoutRoot}/out-old"
newOutPath="${checkoutRoot}/out-new"
tempOutPath="${checkoutRoot}/out"
rm -rf "$oldOutPath" "$newOutPath" "$tempOutPath"
echo building new commit
doBuild
mv "$tempOutPath" "$newOutPath"
echo building previous commit
checkout "$oldCommits"
if doBuild; then
echo previous build succeeded
else
echo previous build failed
uncheckout "$projectPaths"
exit 1
fi
uncheckout "$projectPaths"
mv "$tempOutPath" "$oldOutPath"
echo
echo diffing results
# Don't care about maven-metadata files because they have timestamps in them
# We might care to know whether .sha1 or .md5 files have changed, but changes in those files will always be accompanied by more meaningful changes in other files, so we don't need to show changes in .sha1 or .md5 files
# We also don't care about several specific files, either
echoAndDo diff -r -x "*.md5*" -x "*.sha*" -x "*maven-metadata.xml" -x buildSrc.jar -x jetpad-integration.jar -x "top-of-tree-m2repository-all-0.zip" -x noto-emoji-compat-java.jar -x versionedparcelable-annotation.jar -x dokkaTipOfTreeDocs-0.zip "$oldOutPath/dist" "$newOutPath/dist"
echo end of difference
| {
"content_hash": "4e6264849625697e83a3f910876cdbdf",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 282,
"avg_line_length": 34.42758620689655,
"alnum_prop": 0.6975160256410257,
"repo_name": "AndroidX/androidx",
"id": "1609834f7331c0bc3fe69fae349fc25cf4082754",
"size": "5618",
"binary": false,
"copies": "3",
"ref": "refs/heads/androidx-main",
"path": "development/validateRefactor.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "263978"
},
{
"name": "ANTLR",
"bytes": "19860"
},
{
"name": "C",
"bytes": "4764"
},
{
"name": "C++",
"bytes": "9020585"
},
{
"name": "CMake",
"bytes": "11999"
},
{
"name": "HTML",
"bytes": "21175"
},
{
"name": "Java",
"bytes": "59499889"
},
{
"name": "JavaScript",
"bytes": "1343"
},
{
"name": "Kotlin",
"bytes": "66123157"
},
{
"name": "Python",
"bytes": "292398"
},
{
"name": "Shell",
"bytes": "167367"
},
{
"name": "Swift",
"bytes": "3153"
},
{
"name": "TypeScript",
"bytes": "7599"
}
],
"symlink_target": ""
} |
<?php
function blog_magazine_style($atts, $i){
global $post, $mk_options;
extract($atts);
$output = '';
$image_height = $grid_image_height;
$lightbox_full_size = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$post_type = get_post_meta($post->ID, '_single_post_type', true);
if($i == 1){
if ($layout == 'full') {
$image_width = $grid_width - 40;
$image_height = ($image_width)*0.6;
} else {
$image_width = (($content_width / 100) * $grid_width) - 40;
$image_height = ($image_width)*0.6;
}
switch ($image_size) {
case 'full':
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$image_output_src = $image_src_array[0];
break;
case 'crop':
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$image_output_src = bfi_thumb($image_src_array[0], array(
'width' => $image_width * $image_quality,
'height' => $image_height * $image_quality
));
break;
case 'large':
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'large', true);
$image_output_src = $image_src_array[0];
break;
case 'medium':
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium', true);
$image_output_src = $image_src_array[0];
break;
default:
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$image_output_src = bfi_thumb($image_src_array[0], array(
'width' => $image_width * $image_quality,
'height' => $image_height * $image_quality
));
break;
}
if ($post_type == '') {
$post_type = 'image';
}
$output .= '<article id="' . get_the_ID() . '" class="mk-blog-magazine-item magazine-featured-post mk-isotop-item"><div class="blog-item-holder">';
if (has_post_thumbnail()) {
$show_lightbox = get_post_meta($post->ID, '_disable_post_lightbox', true);
if (($show_lightbox == 'true' || $show_lightbox == '') && $disable_lightbox == 'true') {
$lightbox_code = ' class="mk-lightbox blog-newspaper-lightbox" data-fancybox-group="blog-magazine" href="' . $lightbox_full_size[0] . '"';
} else {
$lightbox_code = ' href="' . get_permalink() . '"';
}
$output .= '<div class="featured-image"><a title="' . get_the_title() . '"' . $lightbox_code . '>';
$output .= ' <img alt="' . get_the_title() . '" title="' . get_the_title() . '" src="' . mk_thumbnail_image_gen($image_output_src, $image_width, $image_height) . '" itemprop="image" />';
$output .= ' <div class="image-gradient-overlay"></div>';
$output .= '</a></div>';
}
$output .= '<div class="item-wrapper">';
$output .= ' <h3 class="the-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
$output .= ' <div class="mk-blog-meta">';
$output .= ' <time datetime="' . get_the_date() . '">
<a href="' . get_month_link(get_the_time("Y"), get_the_time("m")) . '">' . get_the_date() . '</a>
</time>
<span class="mk-categories"> ' . __('', 'mk_framework') . ' ' . get_the_category_list(', ') . '</span>
';
$output .= ' <div class="clearboth"></div>';
$output .= ' </div>';
if($excerpt_length != 0) {
ob_start();
the_excerpt_max_charlength($excerpt_length);
$output .= '<div class="the-excerpt"><p>' . ob_get_clean() . '</p></div>';
}
if ($disable_comments_share != 'false') {
$output .= '<div class="blog-magazine-social-section">';
if ($mk_options['enable_blog_single_comments'] == 'true'):
if (get_post_meta($post->ID, '_disable_comments', true) != 'false') {
ob_start();
comments_number('0', '1', '%');
$output .= '<a href="' . get_permalink() . '#comments" class="blog-magazine-comment"><i class="mk-moon-bubble-9"></i><span>' . ob_get_contents() . '</span></a>';
ob_get_clean();
}
endif;
if (function_exists('mk_love_this')) {
ob_start();
mk_love_this();
$output .= '<div class="mk-love-holder">' . ob_get_contents() . '</div>';
ob_get_clean();
}
$output .= '</div>';
}
$output .= '</div>';
$output .= '</article>' . "\n\n\n";
}
else{
$image_width = 200;
$image_height = 200;
$output .= '<article id="' . get_the_ID() . '" class="mk-blog-magazine-item magazine-thumb-post"><div class="blog-item-holder">';
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$image_src = bfi_thumb($image_src_array[0], array(
'width' => $image_width,
'height' => $image_height,
'crop' => true
));
if (has_post_thumbnail()) {
$output .= '<div class="featured-image"><a title="' . get_the_title() . '" href="' . get_permalink() . '">';
$output .= '<img alt="' . get_the_title() . '" width="' . $image_width . '" class="item-featured-image" height="' . $image_height . '" title="' . get_the_title() . '" src="' . mk_thumbnail_image_gen($image_src, $image_width, $image_height). '" itemprop="image" />';
$output .= '</a></div>';
}
$output .= '<div class="item-wrapper">';
$output .= ' <h3 class="the-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
$output .= '<div class="mk-blog-meta">';
$output .= ' <time datetime="' . get_the_date() . '" itemprop="datePublished" pubdate>';
$output .= ' <a href="' . get_month_link(get_the_time("Y"), get_the_time("m")) . '">' . get_the_date() . ' </a>';
$output .= ' </time>';
$output .= '<span class="mk-categories">' . get_the_category_list(', ') . '</span>';
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="clearboth"></div>';
$output .= '</article>';
}
return $output;
}
?>
| {
"content_hash": "6e115f343b84ee71c6bb9b153249af03",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 275,
"avg_line_length": 47.048611111111114,
"alnum_prop": 0.4740959409594096,
"repo_name": "FabioQ/WP-fabioquinzi.com",
"id": "c4e90a495986fc25f19f28063078f71614aa68d1",
"size": "6775",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/wp-content/themes/jupiter/blog-styles/magazine.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1188"
},
{
"name": "CSS",
"bytes": "4109623"
},
{
"name": "HTML",
"bytes": "92252"
},
{
"name": "JavaScript",
"bytes": "2914308"
},
{
"name": "PHP",
"bytes": "15400631"
}
],
"symlink_target": ""
} |
from loguru import logger
from flexget import plugin
from flexget.event import event
from flexget.plugin import PluginError
logger = logger.bind(name='list_clear')
class ListClear:
schema = {
'type': 'object',
'properties': {
'what': {
'type': 'array',
'items': {
'allOf': [
{'$ref': '/schema/plugins?interface=list'},
{
'maxProperties': 1,
'error_maxProperties': 'Plugin options within list_clear plugin must be indented '
'2 more spaces than the first letter of the plugin name.',
'minProperties': 1,
},
]
},
},
'phase': {'type': 'string', 'enum': plugin.task_phases, 'default': 'start'},
},
'required': ['what'],
}
def __getattr__(self, phase):
# enable plugin in regular task phases
if phase.replace('on_task_', '') in plugin.task_phases:
return self.clear
@plugin.priority(plugin.PRIORITY_FIRST)
def clear(self, task, config):
for item in config['what']:
for plugin_name, plugin_config in item.items():
try:
thelist = plugin.get(plugin_name, self).get_list(plugin_config)
except AttributeError:
raise PluginError('Plugin %s does not support list interface' % plugin_name)
if thelist.immutable:
raise plugin.PluginError(thelist.immutable)
if config['phase'] == task.current_phase:
if task.manager.options.test and thelist.online:
logger.info(
'would have cleared all items from {} - {}', plugin_name, plugin_config
)
continue
logger.verbose('clearing all items from {} - {}', plugin_name, plugin_config)
thelist.clear()
@event('plugin.register')
def register_plugin():
plugin.register(ListClear, 'list_clear', api_ver=2)
| {
"content_hash": "ca6a147d7901ed0bec7a7846c7aa53d8",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 110,
"avg_line_length": 37.15,
"alnum_prop": 0.4952893674293405,
"repo_name": "ianstalk/Flexget",
"id": "e9a386c203a295bcb20a0d724b346d2e21baeeed",
"size": "2229",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "flexget/components/managed_lists/list_clear.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56725"
},
{
"name": "HTML",
"bytes": "35670"
},
{
"name": "JavaScript",
"bytes": "455222"
},
{
"name": "Python",
"bytes": "2063551"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class BusinessProcessBatchItemContentImport
| Picturepark.SDK.V1 API </title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class BusinessProcessBatchItemContentImport
| Picturepark.SDK.V1 API ">
<meta name="generator" content="docfx 2.59.4.0">
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="../styles/docfx.vendor.css">
<link rel="stylesheet" href="../styles/docfx.css">
<link rel="stylesheet" href="../styles/main.css">
<meta property="docfx:navrel" content="../toc.html">
<meta property="docfx:tocrel" content="toc.html">
<meta property="docfx:rel" content="../">
</head>
<body data-spy="scroll" data-target="#affix" data-offset="120">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">
<img id="logo" class="svg" src="../logo.svg" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
</div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div class="container body-content">
<div id="search-results">
<div class="search-list">Search Results for <span></span></div>
<div class="sr-items">
<p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
</div>
<ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
</div>
</div>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div id="sidetoc"></div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport">
<h1 id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport">Class BusinessProcessBatchItemContentImport
</h1>
<div class="markdown level0 summary"></div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><span class="xref">System.Object</span></div>
<div class="level1"><a class="xref" href="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemBase.html">BusinessProcessBatchItemBase</a></div>
<div class="level2"><span class="xref">BusinessProcessBatchItemContentImport</span></div>
</div>
<div class="inheritedMembers">
<h5>Inherited Members</h5>
<div>
<span class="xref">System.Object.ToString()</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object)</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.GetHashCode()</span>
</div>
<div>
<span class="xref">System.Object.GetType()</span>
</div>
<div>
<span class="xref">System.Object.MemberwiseClone()</span>
</div>
</div>
<h6><strong>Namespace</strong>: System.Dynamic.ExpandoObject</h6>
<h5 id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_syntax">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public class BusinessProcessBatchItemContentImport : BusinessProcessBatchItemBase</code></pre>
</div>
<h3 id="properties">Properties
</h3>
<a id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_Items_" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.Items*"></a>
<h4 id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_Items" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.Items"><a href="#collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_Items" class="expander" data-toggle="collapse">Items</a></h4>
<div id="collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_Items" class="collapse in">
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public ICollection<ContentImportResult> Items { get; set; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table>
<tr>
<td>
<span class="xref">System.Collections.Generic.ICollection</span><<a class="xref" href="Picturepark.SDK.V1.Contract.ContentImportResult.html">ContentImportResult</a>>
<p>
</td>
</tr>
</table>
</div>
<h3 id="methods">Methods
</h3>
<a id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_FromJson_" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.FromJson*"></a>
<h4 id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_FromJson_System_String_" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.FromJson(System.String)"><a href="#collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_FromJson_System_String_" class="expander" data-toggle="collapse">FromJson(String)</a></h4>
<div id="collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_FromJson_System_String_" class="collapse in">
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static BusinessProcessBatchItemContentImport FromJson(string data)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table>
<tr>
<td>
<span class="pull-right"><span class="xref">System.String</span></span>
<span class="parametername">data</span>
<p>
</td>
</tr>
</table>
<h5 class="returns">Returns</h5>
<table>
<tr>
<td>
<a class="xref" href="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.html">BusinessProcessBatchItemContentImport</a>
<p>
</td>
</tr>
</table>
</div>
<a id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_ToJson_" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.ToJson*"></a>
<h4 id="Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_ToJson" data-uid="Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.ToJson"><a href="#collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_ToJson" class="expander" data-toggle="collapse">ToJson()</a></h4>
<div id="collapsible-Picturepark_SDK_V1_Contract_BusinessProcessBatchItemContentImport_ToJson" class="collapse in">
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string ToJson()</code></pre>
</div>
<h5 class="returns">Returns</h5>
<table>
<tr>
<td>
<span class="xref">System.String</span>
<p>
</td>
</tr>
</table>
</div>
</article>
</div>
<div class="contribution-panel mobile-hide">
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
<span>Generated by <strong>DocFX</strong></span>
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../styles/docfx.js"></script>
<script type="text/javascript" src="../styles/main.js"></script>
</body>
</html>
| {
"content_hash": "9d5e4bfe7b85a14c478103d31cdd3207",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 380,
"avg_line_length": 35.153310104529616,
"alnum_prop": 0.6306868867082962,
"repo_name": "Picturepark/Picturepark.SDK.DotNet",
"id": "9666ff8fa604e6fd02f359fe6ddb516d9c73c5f7",
"size": "10091",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/sdk/site/api/Picturepark.SDK.V1.Contract.BusinessProcessBatchItemContentImport.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1481"
},
{
"name": "C#",
"bytes": "8219178"
},
{
"name": "PostScript",
"bytes": "2927"
},
{
"name": "PowerShell",
"bytes": "2869"
}
],
"symlink_target": ""
} |
<?php
/**
* Affects how a map's elements will be styled.
* Each MapTypeStyler should contain one and only one key. If more than one key
* is specified in a single MapTypeStyler, all but one will be ignored.
* For example: var rule = {hue: '#ff0000'}.
*/
class EGmap3MapTypeStyler extends EGmap3OptionBase
{
/**
* @var float Modifies the gamma by raising the lightness to the given power.
* Valid values: Floating point numbers, [0.01, 10],
* with 1.0 representing no change.
*/
public $gamma;
/**
* @var string Sets the hue of the feature to match the hue of the color
* supplied. Note that the saturation and lightness of the feature is
* conserved, which means that the feature will not match the color supplied
* exactly. Valid values: An RGB hex string, i.e. '#ff0000'.
*/
public $hue;
/**
* @var boolean Inverts lightness. A value of true will invert the lightness
* of the feature while preserving the hue and saturation.
*/
public $invert_lightness;
/**
* @var integer Shifts lightness of colors by a percentage of the original
* value if decreasing and a percentage of the remaining value if increasing.
* Valid values: [-100, 100].
*/
public $lightness;
/**
* @var integer Shifts the saturation of colors by a percentage of the
* original value if decreasing and a percentage of the remaining value if
* increasing. Valid values: [-100, 100].
*/
public $saturation;
/**
* @var type Valid values: 'on', 'off' or 'simplifed'.
*/
public $visibility;
public function getOptionChecks()
{
return array(
'visibility' => array('on', 'off', 'simplifed'),
);
}
}
| {
"content_hash": "cb547df84b7277e64e30a829cd7adde0",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 79,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.6941391941391941,
"repo_name": "illibejiep/YiiBoilerplate",
"id": "6d5312a53d76d8c00c235b9c041125e07ef96ca2",
"size": "1885",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "common/extensions/jquery-gmap/EGmap3MapTypeStyler.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "49212"
},
{
"name": "Batchfile",
"bytes": "1263"
},
{
"name": "CSS",
"bytes": "111863"
},
{
"name": "Gherkin",
"bytes": "514"
},
{
"name": "HTML",
"bytes": "4160678"
},
{
"name": "JavaScript",
"bytes": "1744248"
},
{
"name": "PHP",
"bytes": "33269841"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
package com.dream.example.presenter;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.dream.example.App;
import com.dream.example.R;
import com.dream.example.data.support.AppConsts;
import com.dream.example.presenter.base.AppBaseActivityPresenter;
import com.dream.example.ui.activity.base.AppBaseAppCompatActivity;
import com.dream.example.utils.SPUtil;
import com.dream.example.view.ILoginView;
import org.yapp.core.ui.inject.annotation.ViewInject;
import org.yapp.utils.Toast;
/**
* Description: LoginPresenter. <br>
* Date: 2016/08/17 16:59 <br>
* Author: ysj
*/
public class LoginPresenter extends
AppBaseActivityPresenter implements ILoginView, View.OnClickListener {
@ViewInject(R.id.login_uname)
private AutoCompleteTextView mUnameView;
@ViewInject(R.id.login_pwd)
private EditText mPasswordView;
@ViewInject(R.id.login_progress)
private View mProgressView;
@ViewInject(R.id.login_form)
private View mLoginFormView;
@ViewInject(R.id.login_btn_ok)
private Button mSignInButton;
@ViewInject(R.id.login_register)
private TextView mRegisterView;
@ViewInject(R.id.login_forgot)
private TextView mForgotView;
private String clientPlatform;
private String clientInfo;
private String iosServiceToken;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_btn_ok:
attemptLogin();
break;
case R.id.login_register:
// go(RegisterAActivity.class);
break;
case R.id.login_forgot:
// TODO
break;
}
}
@Override
public void onInit() {
setTitle(R.string.title_activity_login);
String uname = (String) SPUtil.get(getContext(), AppConsts._UNAME, "");
String passwd = (String) SPUtil.get(getContext(), AppConsts._PASSWD, "");
if (!TextUtils.isEmpty(uname) && !TextUtils.isEmpty(passwd)) {
mUnameView.setText(uname);
mPasswordView.setText(passwd);
}
Snackbar.make(mLoginFormView, "请先登录", Snackbar.LENGTH_LONG).setAction("Action", null).show();
mSignInButton.setOnClickListener(this);
mRegisterView.setOnClickListener(this);
mForgotView.setOnClickListener(this);
}
@Override
public void onClear() {
mUnameView = null;
mPasswordView = null;
mProgressView = null;
mLoginFormView = null;
mSignInButton = null;
mRegisterView = null;
mForgotView = null;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
@Override
public void attemptLogin() {
// Reset errors.
mUnameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String uname = mUnameView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(uname) && TextUtils.isEmpty(password)) {
// go(RegisterAActivity.class);
return;
}
// Check for a valid email address.
if (TextUtils.isEmpty(uname)) {
mUnameView.setError(getContext().getString(R.string.error_field_required));
focusView = mUnameView;
cancel = true;
}
// else if (!isUnameValid(uname)) {
// mUnameView.setError(getString(R.string.error_invalid_email));
// focusView = mUnameView;
// cancel = true;
// }
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getContext().getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (!isPasswordValid(password)) {
mPasswordView.setError(getContext().getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
// login(uname, password, app.getDeviceId(), app.getVersionName());
}
}
@Override
public boolean isEmailValid(String email) {
//TODO: Replace getContent() with your own logic
return (email.contains("@"));
}
@Override
public boolean isPasswordValid(String password) {
//TODO: Replace getContent() with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public void showError(Throwable ex) {
showDialog(ex.getMessage());
}
@Override
public void loginSuccess() {
SPUtil.put(getContext(), AppConsts._UNAME, mUnameView.getText().toString());
SPUtil.put(getContext(), AppConsts._PASSWD, mPasswordView.getText().toString());
Toast.showMessageForButtomShort("登陆成功");
getContext().finish();
}
}
| {
"content_hash": "321fd4719f6eabcb5d0186a85fc00442",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 111,
"avg_line_length": 34.8294930875576,
"alnum_prop": 0.6307224133368616,
"repo_name": "Jay-Y/yApp",
"id": "8bd01397651bbbb5b496f16ca7fae7f6f44390fc",
"size": "7574",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/dream/example/presenter/LoginPresenter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "473710"
}
],
"symlink_target": ""
} |
using System;
namespace Midi.Events.MetaEvents
{
public sealed class MIDIChannelPrefixEvent : MetaEvent
{
public readonly byte channel;
public MIDIChannelPrefixEvent(int delta_time, byte channel)
: base(delta_time, 0x20)
{
if (channel < 0 || channel > 15)
{
throw new ArgumentOutOfRangeException();
}
this.channel = channel;
}
public override string ToString()
{
return "MIDIChannelPrefixEvent(" + base.ToString() + ", channel: " + channel + ")";
}
}
} | {
"content_hash": "4ed97a54a192636bec84cda001a1f636",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 95,
"avg_line_length": 24.53846153846154,
"alnum_prop": 0.5250783699059561,
"repo_name": "JannikArndt/MIDI-parser",
"id": "892c8fed80f6a1865c6c27dff984ad0a7576c69f",
"size": "1704",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Midi/Events/MetaEvents/MIDIChannelPrefixEvent.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "82848"
}
],
"symlink_target": ""
} |
.class public Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
.super Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;
.source ""
# static fields
.field private static final serialVersionUID:J = 0x1L
# instance fields
.field protected final _annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
.field protected final _creatorIndex:I
.field protected final _injectableValueId:Ljava/lang/Object;
# direct methods
.method protected constructor <init>(Lcom/fasterxml/jackson/databind/deser/CreatorProperty;Lcom/fasterxml/jackson/databind/JsonDeserializer;)V
.locals 1
.annotation system Ldalvik/annotation/Signature;
value = {
"(Lcom/fasterxml/jackson/databind/deser/CreatorProperty;Lcom/fasterxml/jackson/databind/JsonDeserializer<*>;)V"
}
.end annotation
.line 96
invoke-direct {p0, p1, p2}, Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;-><init>(Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;Lcom/fasterxml/jackson/databind/JsonDeserializer;)V
.line 97
iget-object v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
iput-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
.line 98
iget v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
iput v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
.line 99
iget-object v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
iput-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
.line 100
return-void
.end method
.method protected constructor <init>(Lcom/fasterxml/jackson/databind/deser/CreatorProperty;Ljava/lang/String;)V
.locals 1
.line 89
invoke-direct {p0, p1, p2}, Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;-><init>(Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;Ljava/lang/String;)V
.line 90
iget-object v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
iput-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
.line 91
iget v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
iput v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
.line 92
iget-object v0, p1, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
iput-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
.line 93
return-void
.end method
.method public constructor <init>(Ljava/lang/String;Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/PropertyName;Lcom/fasterxml/jackson/databind/jsontype/TypeDeserializer;Lcom/fasterxml/jackson/databind/util/Annotations;Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;ILjava/lang/Object;Z)V
.locals 7
.line 82
move-object v0, p0
move-object v1, p1
move-object v2, p2
move-object v3, p3
move-object v4, p4
move-object v5, p5
move/from16 v6, p9
invoke-direct/range {v0 .. v6}, Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;-><init>(Ljava/lang/String;Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/PropertyName;Lcom/fasterxml/jackson/databind/jsontype/TypeDeserializer;Lcom/fasterxml/jackson/databind/util/Annotations;Z)V
.line 83
iput-object p6, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
.line 84
iput p7, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
.line 85
iput-object p8, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
.line 86
return-void
.end method
.method public constructor <init>(Ljava/lang/String;Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/jsontype/TypeDeserializer;Lcom/fasterxml/jackson/databind/util/Annotations;Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;ILjava/lang/Object;)V
.locals 10
.annotation runtime Ljava/lang/Deprecated;
.end annotation
.line 60
move-object v0, p0
move-object v1, p1
move-object v2, p2
move-object v4, p3
move-object v5, p4
move-object v6, p5
move/from16 v7, p6
move-object/from16 v8, p7
const/4 v3, 0x0
const/4 v9, 0x1
invoke-direct/range {v0 .. v9}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;-><init>(Ljava/lang/String;Lcom/fasterxml/jackson/databind/JavaType;Lcom/fasterxml/jackson/databind/PropertyName;Lcom/fasterxml/jackson/databind/jsontype/TypeDeserializer;Lcom/fasterxml/jackson/databind/util/Annotations;Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;ILjava/lang/Object;Z)V
.line 62
return-void
.end method
# virtual methods
.method public deserializeAndSet(Lcom/fasterxml/jackson/core/JsonParser;Lcom/fasterxml/jackson/databind/DeserializationContext;Ljava/lang/Object;)V
.locals 1
.line 165
invoke-virtual {p0, p1, p2}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->deserialize(Lcom/fasterxml/jackson/core/JsonParser;Lcom/fasterxml/jackson/databind/DeserializationContext;)Ljava/lang/Object;
move-result-object v0
invoke-virtual {p0, p3, v0}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->set(Ljava/lang/Object;Ljava/lang/Object;)V
.line 166
return-void
.end method
.method public deserializeSetAndReturn(Lcom/fasterxml/jackson/core/JsonParser;Lcom/fasterxml/jackson/databind/DeserializationContext;Ljava/lang/Object;)Ljava/lang/Object;
.locals 1
.line 173
invoke-virtual {p0, p1, p2}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->deserialize(Lcom/fasterxml/jackson/core/JsonParser;Lcom/fasterxml/jackson/databind/DeserializationContext;)Ljava/lang/Object;
move-result-object v0
invoke-virtual {p0, p3, v0}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->setAndReturn(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v0
return-object v0
.end method
.method public findInjectableValue(Lcom/fasterxml/jackson/databind/DeserializationContext;Ljava/lang/Object;)Ljava/lang/Object;
.locals 3
.line 118
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
if-nez v0, :cond_0
.line 119
new-instance v0, Ljava/lang/IllegalStateException;
new-instance v1, Ljava/lang/StringBuilder;
const-string v2, "Property \'"
invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
invoke-virtual {p0}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->getName()Ljava/lang/String;
move-result-object v2
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, "\' (type "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/Class;->getName()Ljava/lang/String;
move-result-object v2
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, ") has no injectable value id configured"
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V
throw v0
.line 122
:cond_0
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
invoke-virtual {p1, v0, p0, p2}, Lcom/fasterxml/jackson/databind/DeserializationContext;->findInjectableValue(Ljava/lang/Object;Lcom/fasterxml/jackson/databind/BeanProperty;Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v0
return-object v0
.end method
.method public getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
.locals 1
.annotation system Ldalvik/annotation/Signature;
value = {
"<A::Ljava/lang/annotation/Annotation;>(Ljava/lang/Class<TA;>;)TA;"
}
.end annotation
.line 142
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
if-nez v0, :cond_0
.line 143
const/4 v0, 0x0
return-object v0
.line 145
:cond_0
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
invoke-virtual {v0, p1}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;->getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;
move-result-object v0
return-object v0
.end method
.method public getCreatorIndex()I
.locals 1
.line 151
iget v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_creatorIndex:I
return v0
.end method
.method public getInjectableValueId()Ljava/lang/Object;
.locals 1
.line 193
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
return-object v0
.end method
.method public getMember()Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;
.locals 1
.line 148
iget-object v0, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_annotated:Lcom/fasterxml/jackson/databind/introspect/AnnotatedParameter;
return-object v0
.end method
.method public inject(Lcom/fasterxml/jackson/databind/DeserializationContext;Ljava/lang/Object;)V
.locals 1
.line 131
invoke-virtual {p0, p1, p2}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->findInjectableValue(Lcom/fasterxml/jackson/databind/DeserializationContext;Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v0
invoke-virtual {p0, p2, v0}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->set(Ljava/lang/Object;Ljava/lang/Object;)V
.line 132
return-void
.end method
.method public set(Ljava/lang/Object;Ljava/lang/Object;)V
.locals 3
.line 182
new-instance v0, Ljava/lang/IllegalStateException;
new-instance v1, Ljava/lang/StringBuilder;
const-string v2, "Method should never be called on a "
invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/Class;->getName()Ljava/lang/String;
move-result-object v2
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V
throw v0
.end method
.method public setAndReturn(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
.locals 0
.line 188
return-object p1
.end method
.method public toString()Ljava/lang/String;
.locals 2
.line 197
new-instance v0, Ljava/lang/StringBuilder;
const-string v1, "[creator property, name \'"
invoke-direct {v0, v1}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
invoke-virtual {p0}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->getName()Ljava/lang/String;
move-result-object v1
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v0
const-string v1, "\'; inject id \'"
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v0
iget-object v1, p0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->_injectableValueId:Ljava/lang/Object;
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v0
const-string v1, "\']"
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v0
invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v0
return-object v0
.end method
.method public withName(Ljava/lang/String;)Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
.locals 1
.line 104
new-instance v0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
invoke-direct {v0, p0, p1}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;-><init>(Lcom/fasterxml/jackson/databind/deser/CreatorProperty;Ljava/lang/String;)V
return-object v0
.end method
.method public bridge synthetic withName(Ljava/lang/String;)Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;
.locals 1
.line 29
invoke-virtual {p0, p1}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->withName(Ljava/lang/String;)Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
move-result-object v0
return-object v0
.end method
.method public withValueDeserializer(Lcom/fasterxml/jackson/databind/JsonDeserializer;)Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
.locals 1
.annotation system Ldalvik/annotation/Signature;
value = {
"(Lcom/fasterxml/jackson/databind/JsonDeserializer<*>;)Lcom/fasterxml/jackson/databind/deser/CreatorProperty;"
}
.end annotation
.line 109
new-instance v0, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
invoke-direct {v0, p0, p1}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;-><init>(Lcom/fasterxml/jackson/databind/deser/CreatorProperty;Lcom/fasterxml/jackson/databind/JsonDeserializer;)V
return-object v0
.end method
.method public bridge synthetic withValueDeserializer(Lcom/fasterxml/jackson/databind/JsonDeserializer;)Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;
.locals 1
.line 29
invoke-virtual {p0, p1}, Lcom/fasterxml/jackson/databind/deser/CreatorProperty;->withValueDeserializer(Lcom/fasterxml/jackson/databind/JsonDeserializer;)Lcom/fasterxml/jackson/databind/deser/CreatorProperty;
move-result-object v0
return-object v0
.end method
| {
"content_hash": "9df877c064a08399325b76d18cd3cb08",
"timestamp": "",
"source": "github",
"line_count": 438,
"max_line_length": 394,
"avg_line_length": 34.80821917808219,
"alnum_prop": 0.7546241637150728,
"repo_name": "mmmsplay10/QuizUpWinner",
"id": "9815529ca630f3a6552267c8abc162d2cf1b6e01",
"size": "15246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com.quizup.core/smali/com/fasterxml/jackson/databind/deser/CreatorProperty.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6075"
},
{
"name": "Java",
"bytes": "23608889"
},
{
"name": "JavaScript",
"bytes": "6345"
},
{
"name": "Python",
"bytes": "933916"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Uromyces briardii Har.
### Remarks
null | {
"content_hash": "39cd5bd864bf266af3dd86d70caff05b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 22,
"avg_line_length": 9.76923076923077,
"alnum_prop": 0.7007874015748031,
"repo_name": "mdoering/backbone",
"id": "bdead153488553ddf97e386b0a665a60df8597c0",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Uromyces/Uromyces briardii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "89cc8b96e6019b1356c377be8dc01623",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "4dc43b6e18aab34787c56791678aa726c1b0d04b",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Nolana/Nolana tarapacana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.jongo.marshall.jackson.configuration;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
class MapperFeatureModifier implements MapperModifier {
private final MapperFeature feature;
private final boolean enable;
public MapperFeatureModifier(MapperFeature feature, boolean enable) {
this.feature = feature;
this.enable = enable;
}
public void modify(ObjectMapper mapper) {
if (enable)
mapper.enable(feature);
else
mapper.disable(feature);
}
}
| {
"content_hash": "5baaa81f02ac4a0357344418ca3e814c",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 73,
"avg_line_length": 25.82608695652174,
"alnum_prop": 0.7070707070707071,
"repo_name": "bguerout/jongo",
"id": "f97b62cf0afaaf79cfa2d7b10ef802ec97362768",
"size": "1280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/jongo/marshall/jackson/configuration/MapperFeatureModifier.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "456407"
},
{
"name": "Shell",
"bytes": "5965"
}
],
"symlink_target": ""
} |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "base/strings/utf_string_conversions.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/browser/ui/views/payments/payment_request_browsertest_base.h"
#include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/data_model/credit_card.h"
#include "components/payments/content/payment_request.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/styled_label.h"
#include "url/gurl.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/system_web_apps/system_web_app_manager.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#endif
namespace payments {
namespace {
using ::testing::UnorderedElementsAre;
class PaymentRequestTest : public PaymentRequestBrowserTestBase {};
// If the page creates multiple PaymentRequest objects, it should not crash.
IN_PROC_BROWSER_TEST_F(PaymentRequestTest, MultipleRequests) {
NavigateTo("/payment_request_multiple_requests.html");
const std::vector<PaymentRequest*> payment_requests = GetPaymentRequests();
EXPECT_EQ(5U, payment_requests.size());
}
class PaymentRequestNoShippingTest : public PaymentRequestBrowserTestBase {
public:
PaymentRequestNoShippingTest(const PaymentRequestNoShippingTest&) = delete;
PaymentRequestNoShippingTest& operator=(const PaymentRequestNoShippingTest&) =
delete;
protected:
PaymentRequestNoShippingTest() = default;
void OpenPaymentRequestDialog() {
// Installs two apps so that the Payment Request UI will be shown.
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_no_shipping_test.html");
InvokePaymentRequestUIWithJs(content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name));
}
};
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, OpenAndNavigateTo404) {
OpenPaymentRequestDialog();
ResetEventWaiter(DialogEvent::DIALOG_CLOSED);
NavigateTo("/non-existent.html");
WaitForObservedEvent();
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, OpenAndNavigateToSame) {
OpenPaymentRequestDialog();
ResetEventWaiter(DialogEvent::DIALOG_CLOSED);
NavigateTo("/payment_request_no_shipping_test.html");
WaitForObservedEvent();
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, OpenAndReload) {
OpenPaymentRequestDialog();
ResetEventWaiter(DialogEvent::DIALOG_CLOSED);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
WaitForObservedEvent();
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, OpenAndClickCancel) {
OpenPaymentRequestDialog();
ResetEventWaiter(DialogEvent::DIALOG_CLOSED);
ClickOnDialogViewAndWait(DialogViewID::CANCEL_BUTTON,
/*wait_for_animation=*/false);
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest,
OrderSummaryAndClickCancel) {
OpenPaymentRequestDialog();
OpenOrderSummaryScreen();
ResetEventWaiter(DialogEvent::DIALOG_CLOSED);
ClickOnDialogViewAndWait(DialogViewID::CANCEL_BUTTON,
/*wait_for_animation=*/false);
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, InactiveBrowserWindow) {
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_no_shipping_test.html");
SetBrowserWindowInactive();
EXPECT_EQ(
"Cannot show PaymentRequest UI in a preview page or a background tab.",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name)));
}
IN_PROC_BROWSER_TEST_F(PaymentRequestNoShippingTest, InvalidSSL) {
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_no_shipping_test.html");
SetInvalidSsl();
EXPECT_EQ(
"Invalid SSL certificate",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name)));
}
using PaymentRequestAbortTest = PaymentRequestBrowserTestBase;
// Testing the use of the abort() JS API.
IN_PROC_BROWSER_TEST_F(PaymentRequestAbortTest, OpenThenAbort) {
// Installs two apps so that the Payment Request UI will be shown.
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_abort_test.html");
InvokePaymentRequestUIWithJs(content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name));
ResetEventWaiterForSequence(
{DialogEvent::ABORT_CALLED, DialogEvent::DIALOG_CLOSED});
content::WebContents* web_contents = GetActiveWebContents();
const std::string click_buy_button_js =
"(function() { document.getElementById('abort').click(); })();";
ASSERT_TRUE(content::ExecuteScript(web_contents, click_buy_button_js));
WaitForObservedEvent();
ExpectBodyContains({"Aborted"});
// The web-modal dialog should now be closed.
web_modal::WebContentsModalDialogManager* web_contents_modal_dialog_manager =
web_modal::WebContentsModalDialogManager::FromWebContents(web_contents);
EXPECT_FALSE(web_contents_modal_dialog_manager->IsDialogActive());
}
using PaymentRequestPaymentMethodIdentifierTest = PaymentRequestBrowserTestBase;
// A url-based payment method identifier is only supported if it has an https
// scheme.
IN_PROC_BROWSER_TEST_F(PaymentRequestPaymentMethodIdentifierTest, Url_Valid) {
// Installs two apps so that the Payment Request UI will be shown.
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_payment_method_identifier_test.html");
InvokePaymentRequestUIWithJs(content::JsReplace(
"buyHelper([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name));
std::vector<PaymentRequest*> requests = GetPaymentRequests();
EXPECT_EQ(1u, requests.size());
std::vector<GURL> url_payment_method_identifiers =
requests[0]->spec()->url_payment_method_identifiers();
EXPECT_EQ(2u, url_payment_method_identifiers.size());
EXPECT_EQ("https://", url_payment_method_identifiers[0].spec().substr(0, 8));
}
// Test harness integrating with DialogBrowserTest to present the dialog in an
// interactive manner for visual testing.
class PaymentsRequestVisualTest
: public SupportsTestDialog<PaymentRequestNoShippingTest> {
public:
PaymentsRequestVisualTest(const PaymentsRequestVisualTest&) = delete;
PaymentsRequestVisualTest& operator=(const PaymentsRequestVisualTest&) =
delete;
protected:
PaymentsRequestVisualTest() = default;
// TestBrowserDialog:
void ShowUi(const std::string& name) override {
InvokePaymentRequestUIWithJs(content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name_, b_method_name_));
}
bool AlwaysCloseAsynchronously() override {
// Bypassing Widget::CanClose() causes payments::JourneyLogger to see the
// show, but not the close, resulting in a DCHECK in its destructor.
return true;
}
std::string a_method_name_;
std::string b_method_name_;
};
IN_PROC_BROWSER_TEST_F(PaymentsRequestVisualTest, InvokeUi_NoShipping) {
// Installs two apps so that the Payment Request UI will be shown.
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name_);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name_);
NavigateTo("/payment_request_no_shipping_test.html");
ShowAndVerifyUi();
}
using PaymentRequestSettingsLinkTest = PaymentRequestBrowserTestBase;
// Tests that clicking the settings link brings the user to settings.
IN_PROC_BROWSER_TEST_F(PaymentRequestSettingsLinkTest, ClickSettingsLink) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Install the Settings App.
ash::SystemWebAppManager::GetForTest(browser()->profile())
->InstallSystemAppsForTesting();
#endif
// Installs two apps so that the Payment Request UI will be shown.
std::string a_method_name;
InstallPaymentApp("a.com", "payment_request_success_responder.js",
&a_method_name);
std::string b_method_name;
InstallPaymentApp("b.com", "payment_request_success_responder.js",
&b_method_name);
NavigateTo("/payment_request_no_shipping_test.html");
// Click on the settings link in the payment request dialog window.
InvokePaymentRequestUIWithJs(content::JsReplace(
"buyWithMethods([{supportedMethods:$1}, {supportedMethods:$2}]);",
a_method_name, b_method_name));
views::StyledLabel* styled_label =
static_cast<views::StyledLabel*>(dialog_view()->GetViewByID(
static_cast<int>(DialogViewID::DATA_SOURCE_LABEL)));
EXPECT_TRUE(styled_label);
content::WebContentsAddedObserver web_contents_added_observer;
styled_label->ClickFirstLinkForTesting();
content::WebContents* new_tab_contents =
web_contents_added_observer.GetWebContents();
EXPECT_EQ(
std::string(chrome::kChromeUISettingsURL) + chrome::kPaymentsSubPage,
new_tab_contents->GetVisibleURL().spec());
}
} // namespace
} // namespace payments
| {
"content_hash": "7097d2ce375591a2a76d699a0743882e",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 80,
"avg_line_length": 38.52758620689655,
"alnum_prop": 0.7232614338136579,
"repo_name": "nwjs/chromium.src",
"id": "c5eaddbe8ba66a65e6faf996417227745f0d603a",
"size": "11173",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "chrome/browser/ui/views/payments/payment_request_browsertest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
from django.conf.urls import url
from django.views import generic
from . import views
urlpatterns = [
url('^$', generic.View.as_view(), name="index"),
url('^url_timeout\.html$', views.UrlTimeoutView.as_view(), name='url_timeout'),
# 申込み用フォーム(車室の一時確保に必要な項目)【個人・法人共通】
url('^user_subscription_simple_step1/(?P<signature>[^/]+)\.html$', views.UserSubscriptionSimpleStep1View.as_view(),
name="user_subscription_simple_step1"),
url('^user_subscription_simple_step2/(?P<signature>[^/]+)\.html$', views.UserSubscriptionSimpleStep2View.as_view(),
name="user_subscription_simple_step2"),
# 審査用フォーム
url('^user_subscription_inspection_step1/(?P<signature>[^/]+)\.html$',
views.UserSubscriptionInspectionStep1View.as_view(),
name="user_subscription_inspection_step1"),
url('^user_subscription_inspection_step2/(?P<signature>[^/]+)\.html$',
views.UserSubscriptionInspectionStep2View.as_view(),
name="user_subscription_inspection_step2"),
# # ユーザー申込み
# url('^user_subscription_step1/(?P<signature>[^/]+)\.html$', views.UserSubscriptionStep1View.as_view(),
# name="user_subscription_step1"),
# url('^user_subscription_step2/(?P<signature>[^/]+)\.html$', views.UserSubscriptionStep2View.as_view(),
# name="user_subscription_step2"),
# url('^user_subscription_step3/(?P<signature>[^/]+)\.html$', views.UserSubscriptionStep3View.as_view(),
# name="user_subscription_step3"),
# url('^user_subscription_step4/(?P<signature>[^/]+)\.html$', views.UserSubscriptionStep4View.as_view(),
# name="user_subscription_step4"),
# url('^user_subscription_step5/(?P<signature>[^/]+)\.html$', views.UserSubscriptionStep5View.as_view(),
# name="user_subscription_step5"),
url('^subscription_confirm/(?P<subscription_id>\d+)/$',
views.SubscriptionConfirmView.as_view(), name="report_subscription_confirm"),
url('^subscription/(?P<subscription_id>\d+)/$',
views.SubscriptionView.as_view(), name="report_subscription"),
# ユーザー契約
url('^user_contract_step1/(?P<signature>[^/]+)\.html$', views.UserContractStep1View.as_view(),
name="user_contract_step1"),
url('^user_contract_step2/(?P<signature>[^/]+)\.html$', views.UserContractStep2View.as_view(),
name="user_contract_step2"),
url('^user_contract_step3/(?P<signature>[^/]+)\.html$', views.UserContractStep3View.as_view(),
name="user_contract_step3"),
url('^user_contract_step4/(?P<signature>[^/]+)\.html$', views.UserContractStep4View.as_view(),
name="user_contract_step4"),
url('^user_contract_step5/(?P<signature>[^/]+)\.html$', views.UserContractStep5View.as_view(),
name="user_contract_step5"),
# 一般解約
url('^user_contract_cancellation_step1/(?P<signature>[^/]+)\.html$', views.ContractCancellationStep1View.as_view(),
name="user_contract_cancellation_step1"),
url('^user_contract_cancellation_step2/(?P<signature>[^/]+)\.html$', views.ContractCancellationStep2View.as_view(),
name="user_contract_cancellation_step2"),
# Download PDF
url('^download/pdf/subscription_confirm/(?P<subscription_id>\d+)/$',
views.GenerateSubscriptionConfirmPdfView.as_view(), name='download_report_subscription_confirm'),
url('^download/pdf/subscription/(?P<subscription_id>\d+)/$',
views.GenerateSubscriptionPdfView.as_view(), name='download_report_subscription'),
]
| {
"content_hash": "297365804ae134b090c4a7110b4ca255",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 119,
"avg_line_length": 58.52542372881356,
"alnum_prop": 0.6689834926151172,
"repo_name": "YangWanjun/areaparking",
"id": "7f9a9b1df041b8373fd229eb77d8322b5695e18b",
"size": "3561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "format/urls.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "715"
},
{
"name": "CSS",
"bytes": "16603"
},
{
"name": "HTML",
"bytes": "696337"
},
{
"name": "JavaScript",
"bytes": "1412226"
},
{
"name": "Python",
"bytes": "2820285"
},
{
"name": "SQLPL",
"bytes": "2281"
},
{
"name": "Shell",
"bytes": "882"
}
],
"symlink_target": ""
} |
id: 587d7da9367417b2b2512b68
title: Use the reduce Method to Analyze Data
challengeType: 1
forumTopicId: 301313
localeTitle: Используйте метод reduce для анализа данных
---
## Description
<section id='description'>
<code>Array.prototype.reduce()</code> или просто <code>reduce()</code>, является наиболее общей из всех операций с массивами в JavaScript. Вы можете решить практически любую проблему обработки массива с помощью метода <code>reduce</code> . Это не относится к методам <code>filter</code> и <code>map</code> поскольку они не позволяют взаимодействовать между двумя различными элементами массива. Например, если вы хотите сравнить элементы массива или добавить их вместе, <code>filter</code> или <code>map</code> не смогут обработать это. Метод <code>reduce</code> позволяет использовать более общие формы обработки массивов, и можно показать, что как <code>filter</code>, так и <code>map</code> могут быть реализованы через <code>reduce</code>. Однако, прежде чем мы перейдем к этому, давайте сначала научимся использовать <code>reduce</code>.
</section>
## Instructions
<section id='instructions'>
Переменная <code>watchList</code> содержит массив объектов с информацией о нескольких фильмах. Используйте <code>reduce</code> чтобы найти средний рейтинг IMDB фильмов <strong>режиссера Кристофера Нолана</strong>. Вспомните предыдущие задачи, как применять к данным <code>filter</code> и <code>map</code>, чтобы вытащить то, что вам нужно. Возможно, вам придется создавать другие переменные, но сохранить окончательное среднее значение в переменной <code>averageRating</code>. Обратите внимание, что значения рейтинга сохраняются как строки в объекте и должны быть преобразованы в числа, прежде чем они будут использоваться в любых математических операциях.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>watchList</code> variable should not change.
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: Your code should use the <code>reduce</code> method.
testString: assert(code.match(/\.reduce/g));
- text: The <code>getRating(watchList)</code> should equal 8.675.
testString: assert(getRating(watchList) === 8.675);
- text: Your code should not use a <code>for</code> loop.
testString: assert(!code.match(/for\s*?\(.*\)/g));
- text: Your code should return correct output after modifying the <code>watchList</code> object.
testString: assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
function getRating(watchList){
// Add your code below this line
var averageRating;
// Add your code above this line
return averageRating;
}
console.log(getRating(watchList));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
function getRating(watchList){
var averageRating;
const rating = watchList
.filter(obj => obj.Director === "Christopher Nolan")
.map(obj => Number(obj.imdbRating));
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
return averageRating;
}
```
</section>
| {
"content_hash": "95d15cb01cb9d248c22efde3f3e13912",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 841,
"avg_line_length": 52.629139072847686,
"alnum_prop": 0.5239083931043161,
"repo_name": "jonathanihm/freeCodeCamp",
"id": "350c9eeee86ab643bc703d367737de5703a7a5de",
"size": "16858",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.russian.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "193850"
},
{
"name": "HTML",
"bytes": "100244"
},
{
"name": "JavaScript",
"bytes": "522335"
}
],
"symlink_target": ""
} |
package org.apache.beam.sdk.io;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.beam.sdk.io.FileBasedSink.CompressionType;
import org.apache.beam.sdk.io.FileBasedSink.FileBasedWriteOperation;
import org.apache.beam.sdk.io.FileBasedSink.FileBasedWriter;
import org.apache.beam.sdk.io.FileBasedSink.FileResult;
import org.apache.beam.sdk.io.FileBasedSink.WritableByteChannelFactory;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.util.IOChannelUtils;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for FileBasedSink.
*/
@RunWith(JUnit4.class)
public class FileBasedSinkTest {
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
private String baseOutputFilename = "output";
private String tempDirectory = "temp";
private String appendToTempFolder(String filename) {
return Paths.get(tmpFolder.getRoot().getPath(), filename).toString();
}
private String getBaseOutputFilename() {
return appendToTempFolder(baseOutputFilename);
}
private String getBaseTempDirectory() {
return appendToTempFolder(tempDirectory);
}
/**
* FileBasedWriter opens the correct file, writes the header, footer, and elements in the
* correct order, and returns the correct filename.
*/
@Test
public void testWriter() throws Exception {
String testUid = "testId";
String expectedFilename = IOChannelUtils.resolve(getBaseTempDirectory(), testUid);
SimpleSink.SimpleWriter writer = buildWriter();
List<String> values = Arrays.asList("sympathetic vulture", "boresome hummingbird");
List<String> expected = new ArrayList<>();
expected.add(SimpleSink.SimpleWriter.HEADER);
expected.addAll(values);
expected.add(SimpleSink.SimpleWriter.FOOTER);
writer.open(testUid);
for (String value : values) {
writer.write(value);
}
FileResult result = writer.close();
assertEquals(expectedFilename, result.getFilename());
assertFileContains(expected, expectedFilename);
}
/**
* Assert that a file contains the lines provided, in the same order as expected.
*/
private void assertFileContains(List<String> expected, String filename) throws Exception {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
List<String> actual = new ArrayList<>();
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
actual.add(line);
}
assertEquals(expected, actual);
}
}
/**
* Write lines to a file.
*/
private void writeFile(List<String> lines, File file) throws Exception {
try (PrintWriter writer = new PrintWriter(new FileOutputStream(file))) {
for (String line : lines) {
writer.println(line);
}
}
}
/**
* Removes temporary files when temporary and output filenames differ.
*/
@Test
public void testRemoveWithTempFilename() throws Exception {
testRemoveTemporaryFiles(3, tempDirectory);
}
/**
* Removes only temporary files, even if temporary and output files share the same base filename.
*/
@Test
public void testRemoveWithSameFilename() throws Exception {
testRemoveTemporaryFiles(3, baseOutputFilename);
}
/**
* Finalize copies temporary files to output files and removes any temporary files.
*/
@Test
public void testFinalize() throws Exception {
List<File> files = generateTemporaryFilesForFinalize(3);
runFinalize(buildWriteOperation(), files);
}
/**
* Finalize can be called repeatedly.
*/
@Test
public void testFinalizeMultipleCalls() throws Exception {
List<File> files = generateTemporaryFilesForFinalize(3);
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation();
runFinalize(writeOp, files);
runFinalize(writeOp, files);
}
/**
* Finalize can be called when some temporary files do not exist and output files exist.
*/
@Test
public void testFinalizeWithIntermediateState() throws Exception {
List<File> files = generateTemporaryFilesForFinalize(3);
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation();
runFinalize(writeOp, files);
// create a temporary file
tmpFolder.newFolder(tempDirectory);
tmpFolder.newFile(tempDirectory + "/1");
runFinalize(writeOp, files);
}
/**
* Generate n temporary files using the temporary file pattern of FileBasedWriter.
*/
private List<File> generateTemporaryFilesForFinalize(int numFiles) throws Exception {
List<File> temporaryFiles = new ArrayList<>();
for (int i = 0; i < numFiles; i++) {
String temporaryFilename =
FileBasedWriteOperation.buildTemporaryFilename(tempDirectory, "" + i);
File tmpFile = new File(tmpFolder.getRoot(), temporaryFilename);
tmpFile.getParentFile().mkdirs();
assertTrue(tmpFile.createNewFile());
temporaryFiles.add(tmpFile);
}
return temporaryFiles;
}
/**
* Finalize and verify that files are copied and temporary files are optionally removed.
*/
private void runFinalize(SimpleSink.SimpleWriteOperation writeOp, List<File> temporaryFiles)
throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
int numFiles = temporaryFiles.size();
List<File> outputFiles = new ArrayList<>();
List<FileResult> fileResults = new ArrayList<>();
List<String> outputFilenames = writeOp.generateDestinationFilenames(numFiles);
// Create temporary output bundles and output File objects
for (int i = 0; i < numFiles; i++) {
fileResults.add(new FileResult(temporaryFiles.get(i).toString()));
outputFiles.add(new File(outputFilenames.get(i)));
}
writeOp.finalize(fileResults, options);
for (int i = 0; i < numFiles; i++) {
assertTrue(outputFiles.get(i).exists());
assertFalse(temporaryFiles.get(i).exists());
}
assertFalse(new File(writeOp.tempDirectory.get()).exists());
// Test that repeated requests of the temp directory return a stable result.
assertEquals(writeOp.tempDirectory.get(), writeOp.tempDirectory.get());
}
/**
* Create n temporary and output files and verify that removeTemporaryFiles only
* removes temporary files.
*/
private void testRemoveTemporaryFiles(int numFiles, String baseTemporaryFilename)
throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(baseTemporaryFilename);
List<File> temporaryFiles = new ArrayList<>();
List<File> outputFiles = new ArrayList<>();
for (int i = 0; i < numFiles; i++) {
File tmpFile = new File(tmpFolder.getRoot(),
FileBasedWriteOperation.buildTemporaryFilename(baseTemporaryFilename, "" + i));
tmpFile.getParentFile().mkdirs();
assertTrue(tmpFile.createNewFile());
temporaryFiles.add(tmpFile);
File outputFile = tmpFolder.newFile(baseOutputFilename + i);
outputFiles.add(outputFile);
}
writeOp.removeTemporaryFiles(Collections.<String>emptyList(), options);
for (int i = 0; i < numFiles; i++) {
assertFalse(temporaryFiles.get(i).exists());
assertTrue(outputFiles.get(i).exists());
}
}
/**
* Output files are copied to the destination location with the correct names and contents.
*/
@Test
public void testCopyToOutputFiles() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation();
List<String> inputFilenames = Arrays.asList("input-3", "input-2", "input-1");
List<String> inputContents = Arrays.asList("3", "2", "1");
List<String> expectedOutputFilenames = Arrays.asList(
"output-00002-of-00003.test", "output-00001-of-00003.test", "output-00000-of-00003.test");
List<String> inputFilePaths = new ArrayList<>();
List<String> expectedOutputPaths = new ArrayList<>();
for (int i = 0; i < inputFilenames.size(); i++) {
// Generate output paths.
File outputFile = tmpFolder.newFile(expectedOutputFilenames.get(i));
expectedOutputPaths.add(outputFile.toString());
// Generate and write to input paths.
File inputTmpFile = tmpFolder.newFile(inputFilenames.get(i));
List<String> lines = Arrays.asList(inputContents.get(i));
writeFile(lines, inputTmpFile);
inputFilePaths.add(inputTmpFile.toString());
}
// Copy input files to output files.
List<String> actual = writeOp.copyToOutputFiles(inputFilePaths, options);
// Assert that the expected paths are returned.
assertThat(expectedOutputPaths, containsInAnyOrder(actual.toArray()));
// Assert that the contents were copied.
for (int i = 0; i < expectedOutputPaths.size(); i++) {
assertFileContains(Arrays.asList(inputContents.get(i)), expectedOutputPaths.get(i));
}
}
/**
* Output filenames use the supplied naming template.
*/
@Test
public void testGenerateOutputFilenamesWithTemplate() {
List<String> expected;
List<String> actual;
SimpleSink sink = new SimpleSink(getBaseOutputFilename(), "test", ".SS.of.NN");
SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink);
expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"),
appendToTempFolder("output.01.of.03.test"), appendToTempFolder("output.02.of.03.test"));
actual = writeOp.generateDestinationFilenames(3);
assertEquals(expected, actual);
expected = Arrays.asList(appendToTempFolder("output.00.of.01.test"));
actual = writeOp.generateDestinationFilenames(1);
assertEquals(expected, actual);
expected = new ArrayList<>();
actual = writeOp.generateDestinationFilenames(0);
assertEquals(expected, actual);
// Also validate that we handle the case where the user specified "." that we do
// not prefix an additional "." making "..test"
sink = new SimpleSink(getBaseOutputFilename(), ".test", ".SS.of.NN");
writeOp = new SimpleSink.SimpleWriteOperation(sink);
expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"),
appendToTempFolder("output.01.of.03.test"), appendToTempFolder("output.02.of.03.test"));
actual = writeOp.generateDestinationFilenames(3);
assertEquals(expected, actual);
expected = Arrays.asList(appendToTempFolder("output.00.of.01.test"));
actual = writeOp.generateDestinationFilenames(1);
assertEquals(expected, actual);
expected = new ArrayList<>();
actual = writeOp.generateDestinationFilenames(0);
assertEquals(expected, actual);
}
/**
* Output filenames are generated correctly when an extension is supplied.
*/
@Test
public void testGenerateOutputFilenamesWithExtension() {
List<String> expected;
List<String> actual;
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation();
expected = Arrays.asList(
appendToTempFolder("output-00000-of-00003.test"),
appendToTempFolder("output-00001-of-00003.test"),
appendToTempFolder("output-00002-of-00003.test"));
actual = writeOp.generateDestinationFilenames(3);
assertEquals(expected, actual);
expected = Arrays.asList(appendToTempFolder("output-00000-of-00001.test"));
actual = writeOp.generateDestinationFilenames(1);
assertEquals(expected, actual);
expected = new ArrayList<>();
actual = writeOp.generateDestinationFilenames(0);
assertEquals(expected, actual);
}
/**
* Reject non-distinct output filenames.
*/
@Test
public void testCollidingOutputFilenames() {
SimpleSink sink = new SimpleSink("output", "test", "-NN");
SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink);
// A single shard doesn't need to include the shard number.
assertEquals(Arrays.asList("output-01.test"),
writeOp.generateDestinationFilenames(1));
// More than one shard does.
try {
writeOp.generateDestinationFilenames(3);
fail("Should have failed.");
} catch (IllegalStateException exn) {
assertEquals("Shard name template '-NN' only generated 1 distinct file names for 3 files.",
exn.getMessage());
}
}
/**
* Output filenames are generated correctly when an extension is not supplied.
*/
@Test
public void testGenerateOutputFilenamesWithoutExtension() {
List<String> expected;
List<String> actual;
SimpleSink sink = new SimpleSink(appendToTempFolder(baseOutputFilename), "");
SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink);
expected = Arrays.asList(appendToTempFolder("output-00000-of-00003"),
appendToTempFolder("output-00001-of-00003"), appendToTempFolder("output-00002-of-00003"));
actual = writeOp.generateDestinationFilenames(3);
assertEquals(expected, actual);
expected = Arrays.asList(appendToTempFolder("output-00000-of-00001"));
actual = writeOp.generateDestinationFilenames(1);
assertEquals(expected, actual);
expected = new ArrayList<>();
actual = writeOp.generateDestinationFilenames(0);
assertEquals(expected, actual);
}
/**
* {@link CompressionType#BZIP2} correctly writes Gzipped data.
*/
@Test
public void testCompressionTypeBZIP2() throws FileNotFoundException, IOException {
final File file =
writeValuesWithWritableByteChannelFactory(CompressionType.BZIP2, "abc", "123");
// Read Bzip2ed data back in using Apache commons API (de facto standard).
assertReadValues(new BufferedReader(new InputStreamReader(
new BZip2CompressorInputStream(new FileInputStream(file)), StandardCharsets.UTF_8.name())),
"abc", "123");
}
/**
* {@link CompressionType#GZIP} correctly writes Gzipped data.
*/
@Test
public void testCompressionTypeGZIP() throws FileNotFoundException, IOException {
final File file = writeValuesWithWritableByteChannelFactory(CompressionType.GZIP, "abc", "123");
// Read Gzipped data back in using standard API.
assertReadValues(new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream(file)), StandardCharsets.UTF_8.name())), "abc",
"123");
}
/**
* {@link CompressionType#GZIP} correctly writes Gzipped data.
*/
@Test
public void testCompressionTypeUNCOMPRESSED() throws FileNotFoundException, IOException {
final File file =
writeValuesWithWritableByteChannelFactory(CompressionType.UNCOMPRESSED, "abc", "123");
// Read uncompressed data back in using standard API.
assertReadValues(new BufferedReader(new InputStreamReader(
new FileInputStream(file), StandardCharsets.UTF_8.name())), "abc",
"123");
}
private void assertReadValues(final BufferedReader br, String... values) throws IOException {
try (final BufferedReader _br = br) {
for (String value : values) {
assertEquals(String.format("Line should read '%s'", value), value, _br.readLine());
}
}
}
private File writeValuesWithWritableByteChannelFactory(final WritableByteChannelFactory factory,
String... values)
throws IOException, FileNotFoundException {
final File file = tmpFolder.newFile("test.gz");
final WritableByteChannel channel =
factory.create(Channels.newChannel(new FileOutputStream(file)));
for (String value : values) {
channel.write(ByteBuffer.wrap((value + "\n").getBytes(StandardCharsets.UTF_8)));
}
channel.close();
return file;
}
/**
* {@link FileBasedWriter} writes to the {@link WritableByteChannel} provided by
* {@link DrunkWritableByteChannelFactory}.
*/
@Test
public void testFileBasedWriterWithWritableByteChannelFactory() throws Exception {
final String testUid = "testId";
SimpleSink.SimpleWriteOperation writeOp =
new SimpleSink(getBaseOutputFilename(), "txt", new DrunkWritableByteChannelFactory())
.createWriteOperation(null);
final FileBasedWriter<String> writer =
writeOp.createWriter(null);
final String expectedFilename = IOChannelUtils.resolve(writeOp.tempDirectory.get(), testUid);
final List<String> expected = new ArrayList<>();
expected.add("header");
expected.add("header");
expected.add("a");
expected.add("a");
expected.add("b");
expected.add("b");
expected.add("footer");
expected.add("footer");
writer.open(testUid);
writer.write("a");
writer.write("b");
final FileResult result = writer.close();
assertEquals(expectedFilename, result.getFilename());
assertFileContains(expected, expectedFilename);
}
/**
* A simple FileBasedSink that writes String values as lines with header and footer lines.
*/
private static final class SimpleSink extends FileBasedSink<String> {
public SimpleSink(String baseOutputFilename, String extension) {
super(baseOutputFilename, extension);
}
public SimpleSink(String baseOutputFilename, String extension,
WritableByteChannelFactory writableByteChannelFactory) {
super(baseOutputFilename, extension, writableByteChannelFactory);
}
public SimpleSink(String baseOutputFilename, String extension, String fileNamingTemplate) {
super(baseOutputFilename, extension, fileNamingTemplate);
}
@Override
public SimpleWriteOperation createWriteOperation(PipelineOptions options) {
return new SimpleWriteOperation(this);
}
private static final class SimpleWriteOperation extends FileBasedWriteOperation<String> {
public SimpleWriteOperation(SimpleSink sink, String tempOutputFilename) {
super(sink, tempOutputFilename);
}
public SimpleWriteOperation(SimpleSink sink) {
super(sink);
}
@Override
public SimpleWriter createWriter(PipelineOptions options) throws Exception {
return new SimpleWriter(this);
}
}
private static final class SimpleWriter extends FileBasedWriter<String> {
static final String HEADER = "header";
static final String FOOTER = "footer";
private WritableByteChannel channel;
public SimpleWriter(SimpleWriteOperation writeOperation) {
super(writeOperation);
}
private static ByteBuffer wrap(String value) throws Exception {
return ByteBuffer.wrap((value + "\n").getBytes("UTF-8"));
}
@Override
protected void prepareWrite(WritableByteChannel channel) throws Exception {
this.channel = channel;
}
@Override
protected void writeHeader() throws Exception {
channel.write(wrap(HEADER));
}
@Override
protected void writeFooter() throws Exception {
channel.write(wrap(FOOTER));
}
@Override
public void write(String value) throws Exception {
channel.write(wrap(value));
}
}
}
/**
* Build a SimpleSink with default options.
*/
private SimpleSink buildSink() {
return new SimpleSink(getBaseOutputFilename(), "test");
}
/**
* Build a SimpleWriteOperation with default options and the given base temporary filename.
*/
private SimpleSink.SimpleWriteOperation buildWriteOperation(String baseTemporaryFilename) {
SimpleSink sink = buildSink();
return new SimpleSink.SimpleWriteOperation(sink, appendToTempFolder(baseTemporaryFilename));
}
/**
* Build a write operation with the default options for it and its parent sink.
*/
private SimpleSink.SimpleWriteOperation buildWriteOperation() {
SimpleSink sink = buildSink();
return new SimpleSink.SimpleWriteOperation(sink, getBaseTempDirectory());
}
/**
* Build a writer with the default options for its parent write operation and sink.
*/
private SimpleSink.SimpleWriter buildWriter() {
SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation();
return new SimpleSink.SimpleWriter(writeOp);
}
}
| {
"content_hash": "b2b503f97358b51d637a833003170601",
"timestamp": "",
"source": "github",
"line_count": 599,
"max_line_length": 100,
"avg_line_length": 35.158597662771285,
"alnum_prop": 0.7144349477682811,
"repo_name": "jasonkuster/incubator-beam",
"id": "9f0c424b3cf362df3102bbfc998ea43eae011509",
"size": "21865",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "sdks/java/core/src/test/java/org/apache/beam/sdk/io/FileBasedSinkTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "20493"
},
{
"name": "Java",
"bytes": "9562053"
},
{
"name": "Protocol Buffer",
"bytes": "1407"
},
{
"name": "Shell",
"bytes": "10104"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'layouts/nav/sidebar/_admin' do
shared_examples 'page has active tab' do |title|
it "activates #{title} tab" do
render
expect(rendered).to have_selector('.nav-sidebar .sidebar-top-level-items > li.active', count: 1)
expect(rendered).to have_css('.nav-sidebar .sidebar-top-level-items > li.active', text: title)
end
end
shared_examples 'page has active sub tab' do |title|
it "activates #{title} sub tab" do
render
expect(rendered).to have_css('.sidebar-sub-level-items > li.active', text: title)
end
end
context 'on home page' do
before do
allow(controller).to receive(:controller_name).and_return('dashboard')
end
it_behaves_like 'page has active tab', 'Overview'
end
context 'on projects' do
before do
allow(controller).to receive(:controller_name).and_return('projects')
allow(controller).to receive(:controller_path).and_return('admin/projects')
end
it_behaves_like 'page has active tab', 'Overview'
it_behaves_like 'page has active sub tab', 'Projects'
end
context 'on groups' do
before do
allow(controller).to receive(:controller_name).and_return('groups')
end
it_behaves_like 'page has active tab', 'Overview'
it_behaves_like 'page has active sub tab', 'Groups'
end
context 'on users' do
before do
allow(controller).to receive(:controller_name).and_return('users')
end
it_behaves_like 'page has active tab', 'Overview'
it_behaves_like 'page has active sub tab', 'Users'
end
context 'on logs' do
before do
allow(controller).to receive(:controller_name).and_return('logs')
end
it_behaves_like 'page has active tab', 'Monitoring'
it_behaves_like 'page has active sub tab', 'Logs'
end
context 'on messages' do
before do
allow(controller).to receive(:controller_name).and_return('broadcast_messages')
end
it_behaves_like 'page has active tab', 'Messages'
end
context 'on hooks' do
before do
allow(controller).to receive(:controller_name).and_return('hooks')
end
it_behaves_like 'page has active tab', 'Hooks'
end
context 'on background jobs' do
before do
allow(controller).to receive(:controller_name).and_return('background_jobs')
end
it_behaves_like 'page has active tab', 'Monitoring'
it_behaves_like 'page has active sub tab', 'Background Jobs'
end
end
| {
"content_hash": "d8c7b85baa37f97eb5298ef944e20eb8",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 102,
"avg_line_length": 27.4,
"alnum_prop": 0.6715328467153284,
"repo_name": "dreampet/gitlab",
"id": "05c2f61a60660aec53c3205372adf35cb1863c32",
"size": "2466",
"binary": false,
"copies": "2",
"ref": "refs/heads/11-7-stable-zh",
"path": "spec/views/layouts/nav/sidebar/_admin.html.haml_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "675415"
},
{
"name": "Clojure",
"bytes": "79"
},
{
"name": "Dockerfile",
"bytes": "1907"
},
{
"name": "HTML",
"bytes": "1329381"
},
{
"name": "JavaScript",
"bytes": "4251148"
},
{
"name": "Ruby",
"bytes": "19538796"
},
{
"name": "Shell",
"bytes": "44183"
},
{
"name": "Vue",
"bytes": "1051808"
}
],
"symlink_target": ""
} |
/**
* Pull in required modules
**/
const async = require('async');
const url = require('url');
const dns = require('dns');
const _ = require('lodash');
const S = require('string');
/**
* Expose our creation class that will be called
* with properties.
**/
module.exports = exports = function(params) {
/**
* The Report object to return that we can use
**/
var Balance = _.extend({}, require('./common')(params));
/**
* Returns the amount used for the billing run
**/
Balance.getUsed = function() { return params.used; };
/**
* Returns the total credit that was availabelt his billing run
**/
Balance.getCount = function() { return params.count; };
/**
* Returns the current url of the Balance
**/
Balance.getAvailable = function() { return params.available; };
// return the Balance object to use
return Balance;
};
| {
"content_hash": "85748806a16507749bbbca34105f3767",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 65,
"avg_line_length": 23.358974358974358,
"alnum_prop": 0.6114160263446762,
"repo_name": "passmarked/cli",
"id": "393f48703f49db15ca69b8b22bd34960493abb51",
"size": "911",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/models/balance.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "15424"
}
],
"symlink_target": ""
} |
class CloseAllTaxAdjustments < ActiveRecord::Migration
def up
Spree::Adjustment.tax.update_all(finalized: true)
end
end
| {
"content_hash": "8774da234d041df6edf8aed41b71d4c8",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 54,
"avg_line_length": 25.6,
"alnum_prop": 0.7734375,
"repo_name": "solidusio/solidus_avatax",
"id": "1132bf61875d6cdf29c8216cb39c3cad4f049ff2",
"size": "128",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "db/migrate/20140617222244_close_all_tax_adjustments.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "93"
},
{
"name": "JavaScript",
"bytes": "90"
},
{
"name": "Ruby",
"bytes": "119517"
}
],
"symlink_target": ""
} |
<?php
class Twig_Tests_Node_Expression_TestTest extends Twig_Test_NodeTestCase
{
/**
* @covers Twig_Node_Expression_Test::__construct
*/
public function testConstructor()
{
$expr = new Twig_Node_Expression_Constant('foo', 1);
$name = new Twig_Node_Expression_Constant('null', 1);
$args = new Twig_Node();
$node = new Twig_Node_Expression_Test($expr, $name, $args, 1);
$this->assertEquals($expr, $node->getNode('node'));
$this->assertEquals($args, $node->getNode('arguments'));
$this->assertEquals($name, $node->getAttribute('name'));
}
/**
* @covers Twig_Node_Expression_Test::compile
* @dataProvider getTests
*/
public function testCompile($node, $source, $environment = null)
{
parent::testCompile($node, $source, $environment);
}
public function getTests()
{
$tests = array();
$expr = new Twig_Node_Expression_Constant('foo', 1);
$node = new Twig_Node_Expression_Test_Null($expr, 'null', new Twig_Node(array()), 1);
$tests[] = array($node, '(null === "foo")');
return $tests;
}
/**
* @covers Twig_Node_Expression_Filter::compile
* @expectedException Twig_Error_Syntax
* @expectedExceptionMessage The test "nul" does not exist. Did you mean "null" at line 1
*/
public function testUnknownTest()
{
$node = $this->createTest(new Twig_Node_Expression_Constant('foo', 1), 'nul');
$node->compile($this->getCompiler());
}
protected function createTest($node, $name, array $arguments = array())
{
return new Twig_Node_Expression_Test($node, $name, new Twig_Node($arguments), 1);
}
}
| {
"content_hash": "60f450a23f2974105d3d0c7d45ce4233",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 93,
"avg_line_length": 31.017241379310345,
"alnum_prop": 0.5780989438576987,
"repo_name": "lrt/lrt",
"id": "739033b5a7d21d53ae49b90957e5bccafbbe3b20",
"size": "1999",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/twig/twig/test/Twig/Tests/Node/Expression/TestTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "143710"
},
{
"name": "PHP",
"bytes": "256054"
},
{
"name": "Perl",
"bytes": "1091"
},
{
"name": "Shell",
"bytes": "2275"
}
],
"symlink_target": ""
} |
package com.arthurb.adapter.ducks;
/**
* Created by Blackwood on 01.03.2016 0:12.
*/
// Простейшие реализации выводят сообщения о выполняемой операции
public class MallardDuck implements Duck {
@Override
public void quack() {
System.out.println("Quack");
}
@Override
public void fly() {
System.out.println("I'm flying");
}
}
| {
"content_hash": "ede4af0ed49704b4f112e0a30af3587a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 65,
"avg_line_length": 20.555555555555557,
"alnum_prop": 0.6513513513513514,
"repo_name": "NeverNight/SimplesPatterns.Java",
"id": "53a852d26978d0251fc9d2eeb77eb708b886f77c",
"size": "426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/arthurb/adapter/ducks/MallardDuck.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "272777"
}
],
"symlink_target": ""
} |
import React from 'react';
import { Route, Redirect, IndexRedirect } from 'react-router';
import App from './containers/App';
import ScenarioContainer from './containers/Scenario';
import SidebarContainer from './containers/Sidebar';
import SubscribeContainer from './containers/Subscribe';
import Faq from './components/Faq';
import NotFound from './components/NotFound';
export default (
<Route path="/" component={App}>
<IndexRedirect to="generators/random" />
<Route path="generators" component={SidebarContainer} />
<Route path="subscribe" component={SubscribeContainer} />
<Route path="generators/:id" component={ScenarioContainer} />
<Route path="generators/:id/scenario/:uuid" component={ScenarioContainer} />
<Route path="faq" component={Faq} />
<Redirect from="game/:id" to="generators/:id" />
<Redirect from="game/:id/scenario/:uuid" to="generators/:id/scenario/:uuid" />
<Route path="*" component={NotFound} />
</Route>
);
| {
"content_hash": "afc47319a6f214281379b2abcc5625f6",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 82,
"avg_line_length": 44.36363636363637,
"alnum_prop": 0.7100409836065574,
"repo_name": "scenario-generator/frontend",
"id": "02ab173240af7e089eab6a86486792f0c348c341",
"size": "976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1483"
},
{
"name": "JavaScript",
"bytes": "83161"
}
],
"symlink_target": ""
} |
Demo of "include","XML Drawable","9-patch".
This is a small demo ----RemoteControl.
| {
"content_hash": "24eb301502f494b2b2cc745fba7703bb",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 43,
"avg_line_length": 42,
"alnum_prop": 0.7023809523809523,
"repo_name": "cyanstone/RemoteControl",
"id": "b52c43a0b58acb9fe755b5f4419c3647300f9b61",
"size": "100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4143"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<title>flexbox | multicol on flexbox items</title>
<link rel="author" href="http://opera.com" title="Opera Software">
<style>
div {
background: blue;
}
p {
font-family: monospace;
background: yellow;
column-rule: 1em solid lime;
columns: 2;
width: 200px;
margin: 0 auto;
}
</style>
<div>
<p>one two three four five</p>
</div>
| {
"content_hash": "27f79b627e0086f0c34324d2d3f6ae5e",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 66,
"avg_line_length": 17.55,
"alnum_prop": 0.6780626780626781,
"repo_name": "google-ar/WebARonARCore",
"id": "3c8e1f475a337e111b7290465b67ede2b35ac4bb",
"size": "351",
"binary": false,
"copies": "106",
"ref": "refs/heads/webarcore_57.0.2987.5",
"path": "third_party/WebKit/LayoutTests/external/csswg-test/css-flexbox-1/flexbox_columns-flexitems-expected.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import sys
sys.path.append("../src/app")
import unittest
from app.functions import get_config,safe_get_config
class FunctionsTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_config_key_missing(self):
self.assertIsNone(get_config('hackathon-api.endpoint_test'))
def test_get_config_format_error(self):
self.assertIsNone(get_config('mysql.sql'))
def test_get_config(self):
self.assertEqual(get_config('login.session_minutes'),60)
def test_safe_get_config_default(self):
self.assertIsNone(get_config('mysql.sql'))
self.assertEqual(safe_get_config('mysql.sql','default'),'default')
def test_safe_get_config_value(self):
self.assertEqual(get_config('login.session_minutes'),60)
self.assertEqual(safe_get_config('login.session_minutes',66666),60) | {
"content_hash": "5ff05fa8647c006afe7f181daf45997e",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 75,
"avg_line_length": 26.147058823529413,
"alnum_prop": 0.6805399325084365,
"repo_name": "mshubian/BAK_open-hackathon",
"id": "5a560701fbe765e6a268c93f1a7c7db78b8d0f68",
"size": "889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "open-hackathon-adminUI/test/app/test_functions.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "294659"
},
{
"name": "HTML",
"bytes": "206952"
},
{
"name": "Java",
"bytes": "8220"
},
{
"name": "JavaScript",
"bytes": "791759"
},
{
"name": "Perl",
"bytes": "889"
},
{
"name": "Python",
"bytes": "259754"
},
{
"name": "Ruby",
"bytes": "154828"
},
{
"name": "Shell",
"bytes": "5227"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.init;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import org.chromium.base.ThreadUtils;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.content.browser.ChildProcessLauncher;
import java.util.ArrayList;
import java.util.List;
/**
* This class controls the different asynchronous states during our initialization:
* 1. During startBackgroundTasks(), we'll kick off loading the library and yield the call stack.
* 2. We may receive a onStart() / onStop() call any point after that, whether or not
* the library has been loaded.
*/
class NativeInitializationController {
private static final String TAG = "NativeInitializationController";
private final Context mContext;
private final ChromeActivityNativeDelegate mActivityDelegate;
private final Handler mHandler;
private boolean mOnStartPending;
private boolean mOnResumePending;
private List<Intent> mPendingNewIntents;
private List<ActivityResult> mPendingActivityResults;
private boolean mWaitingForFirstDraw;
private boolean mHasDoneFirstDraw;
private boolean mInitializationComplete;
/**
* This class encapsulates a call to onActivityResult that has to be deferred because the native
* library is not yet loaded.
*/
static class ActivityResult {
public final int requestCode;
public final int resultCode;
public final Intent data;
public ActivityResult(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
}
/**
* Create the NativeInitializationController using the main loop and the application context.
* It will be linked back to the activity via the given delegate.
* @param context The context to pull the application context from.
* @param activityDelegate The activity delegate for the owning activity.
*/
public NativeInitializationController(Context context,
ChromeActivityNativeDelegate activityDelegate) {
mContext = context.getApplicationContext();
mHandler = new Handler(Looper.getMainLooper());
mActivityDelegate = activityDelegate;
}
/**
* Start loading the native library in the background. This kicks off the native initialization
* process.
*
* @param allocateChildConnection Whether a spare child connection should be allocated. Set to
* false if you know that no new renderer is needed.
*/
public void startBackgroundTasks(final boolean allocateChildConnection) {
// TODO(yusufo) : Investigate using an AsyncTask for this.
new Thread() {
@Override
public void run() {
try {
LibraryLoader libraryLoader =
LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER);
libraryLoader.ensureInitialized(mContext.getApplicationContext());
// The prefetch is done after the library load for two reasons:
// - It is easier to know the library location after it has
// been loaded.
// - Testing has shown that this gives the best compromise,
// by avoiding performance regression on any tested
// device, and providing performance improvement on
// some. Doing it earlier delays UI inflation and more
// generally startup on some devices, most likely by
// competing for IO.
// For experimental results, see http://crbug.com/460438.
libraryLoader.asyncPrefetchLibrariesToMemory();
} catch (ProcessInitException e) {
Log.e(TAG, "Unable to load native library.", e);
mActivityDelegate.onStartupFailure();
return;
}
if (allocateChildConnection) ChildProcessLauncher.warmUp(mContext);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
onLibraryLoaded();
}
});
}
}.start();
}
private void onLibraryLoaded() {
if (mHasDoneFirstDraw) {
// First draw is done
onNativeLibraryLoaded();
} else {
mWaitingForFirstDraw = true;
}
}
/**
* Called when the current activity has finished its first draw pass. This and the library
* load has to be completed to start the chromium browser process.
*/
public void firstDrawComplete() {
mHasDoneFirstDraw = true;
if (mWaitingForFirstDraw) {
mWaitingForFirstDraw = false;
// Allow the UI thread to continue its initialization
mHandler.post(new Runnable() {
@Override
public void run() {
onNativeLibraryLoaded();
}
});
}
}
private void onNativeLibraryLoaded() {
// Callback from LibraryLoader on UI thread, when the load has completed.
if (mActivityDelegate.isActivityDestroyed()) return;
mActivityDelegate.onCreateWithNative();
}
/**
* Called when native initialization for an activity has been finished.
*/
public void onNativeInitializationComplete() {
// Callback when we finished with ChromeActivityNativeDelegate.onCreateWithNative tasks
mInitializationComplete = true;
if (mOnStartPending) {
mOnStartPending = false;
startNowAndProcessPendingItems();
}
if (mOnResumePending) {
mOnResumePending = false;
onResume();
}
try {
LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER)
.onNativeInitializationComplete(mContext.getApplicationContext());
} catch (ProcessInitException e) {
Log.e(TAG, "Unable to load native library.", e);
mActivityDelegate.onStartupFailure();
return;
}
}
/**
* Called when an activity gets an onStart call and is done with java only tasks.
*/
public void onStart() {
if (mInitializationComplete) {
startNowAndProcessPendingItems();
} else {
mOnStartPending = true;
}
}
/**
* Called when an activity gets an onResume call and is done with java only tasks.
*/
public void onResume() {
if (mInitializationComplete) {
mActivityDelegate.onResumeWithNative();
} else {
mOnResumePending = true;
}
}
/**
* Called when an activity gets an onPause call and is done with java only tasks.
*/
public void onPause() {
mOnResumePending = false; // Clear the delayed resume if a pause happens first.
if (mInitializationComplete) mActivityDelegate.onPauseWithNative();
}
/**
* Called when an activity gets an onStop call and is done with java only tasks.
*/
public void onStop() {
mOnStartPending = false; // Clear the delayed start if a stop happens first.
if (!mInitializationComplete) return;
mActivityDelegate.onStopWithNative();
}
/**
* Called when an activity gets an onNewIntent call and is done with java only tasks.
* @param intent The intent that has arrived to the activity linked to the given delegate.
*/
public void onNewIntent(Intent intent) {
if (mInitializationComplete) {
mActivityDelegate.onNewIntentWithNative(intent);
} else {
if (mPendingNewIntents == null) mPendingNewIntents = new ArrayList<Intent>(1);
mPendingNewIntents.add(intent);
}
}
/**
* This is the Android onActivityResult callback deferred, if necessary,
* to when the native library has loaded.
* @param requestCode The request code for the ActivityResult.
* @param resultCode The result code for the ActivityResult.
* @param data The intent that has been sent with the ActivityResult.
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mInitializationComplete) {
mActivityDelegate.onActivityResultWithNative(requestCode, resultCode, data);
} else {
if (mPendingActivityResults == null) {
mPendingActivityResults = new ArrayList<ActivityResult>(1);
}
mPendingActivityResults.add(new ActivityResult(requestCode, resultCode, data));
}
}
private void startNowAndProcessPendingItems() {
// onNewIntent and onActivityResult are called only when the activity is paused.
// To match the non-deferred behavior, onStart should be called before any processing
// of pending intents and activity results.
// Note that if we needed ChromeActivityNativeDelegate.onResumeWithNative(), the pending
// intents and activity results processing should have happened in the corresponding
// resumeNowAndProcessPendingItems, just before the call to
// ChromeActivityNativeDelegate.onResumeWithNative().
mActivityDelegate.onStartWithNative();
if (mPendingNewIntents != null) {
for (Intent intent : mPendingNewIntents) {
mActivityDelegate.onNewIntentWithNative(intent);
}
mPendingNewIntents = null;
}
if (mPendingActivityResults != null) {
ActivityResult activityResult;
for (int i = 0; i < mPendingActivityResults.size(); i++) {
activityResult = mPendingActivityResults.get(i);
mActivityDelegate.onActivityResultWithNative(activityResult.requestCode,
activityResult.resultCode, activityResult.data);
}
mPendingActivityResults = null;
}
}
}
| {
"content_hash": "eb676a4ff924aa9c44f82d61ae04f875",
"timestamp": "",
"source": "github",
"line_count": 273,
"max_line_length": 100,
"avg_line_length": 38.78388278388278,
"alnum_prop": 0.6351530034000755,
"repo_name": "danakj/chromium",
"id": "f6e49d86921c4fcc6d34cbacb2ce496e82e50184",
"size": "10588",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/android/java/src/org/chromium/chrome/browser/init/NativeInitializationController.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package compiler
import (
"os"
"strings"
"github.com/go-task/task/v3/taskfile"
)
// GetEnviron the all return all environment variables encapsulated on a
// taskfile.Vars
func GetEnviron() *taskfile.Vars {
m := &taskfile.Vars{}
for _, e := range os.Environ() {
keyVal := strings.SplitN(e, "=", 2)
key, val := keyVal[0], keyVal[1]
m.Set(key, taskfile.Var{Static: val})
}
return m
}
| {
"content_hash": "a95fe5ece94075b49747cb7634b14c27",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 72,
"avg_line_length": 19.85,
"alnum_prop": 0.6624685138539043,
"repo_name": "go-task/task",
"id": "b68e8ac1b8fbee26bdba6a38dde588ca171bf7f8",
"size": "397",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "internal/compiler/env.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "174132"
},
{
"name": "PowerShell",
"bytes": "341"
},
{
"name": "Shell",
"bytes": "13255"
}
],
"symlink_target": ""
} |
from ale_python_interface import ALEInterface
from enduro.action import Action
from enduro.control import Controller
from enduro.state import StateExtractor
class Agent(object):
def __init__(self):
self._ale = ALEInterface()
self._ale.setInt('random_seed', 123)
self._ale.setFloat('repeat_action_probability', 0.0)
self._ale.setBool('color_averaging', False)
self._ale.loadROM('roms/enduro.bin')
self._controller = Controller(self._ale)
self._extractor = StateExtractor(self._ale)
self._image = None
def run(self, learn, episodes=1, draw=False):
""" Implements the playing/learning loop.
Args:
learn(bool): Whether the self.learn() function should be called.
episodes (int): The number of episodes to run the agent for.
draw (bool): Whether to overlay the environment state on the frame.
Returns:
None
"""
for e in range(episodes):
# Observe the environment to set the initial state
(grid, self._image) = self._extractor.run(draw=draw, scale=4.0)
self.initialise(grid)
num_frames = self._ale.getFrameNumber()
# Each episode lasts 6500 frames
while self._ale.getFrameNumber() - num_frames < 6500:
# Take an action
self.act()
# Update the environment grid
(grid, self._image) = self._extractor.run(draw=draw, scale=4.0)
self.sense(grid)
# Perform learning if required
if learn:
self.learn()
self.callback(learn, e + 1, self._ale.getFrameNumber() - num_frames)
self._ale.reset_game()
def getActionsSet(self):
""" Returns the set of all possible actions
"""
return [Action.ACCELERATE, Action.RIGHT, Action.LEFT, Action.BREAK]
def move(self, action):
""" Executes the action and advances the game to the next state.
Args:
action (int): The action which should executed. Make sure to use
the constants returned by self.getActionsSet()
Returns:
int: The obtained reward after executing the action
"""
return self._controller.move(action)
def initialise(self, grid):
""" Called at the beginning of each episode, mainly used
for state initialisation.
Args:
grid (np.ndarray): 11x10 array with the initial environment grid.
Returns:
None
"""
raise NotImplementedError
def act(self):
""" Called at each loop iteration to choose and execute an action.
Returns:
None
"""
raise NotImplementedError
def sense(self, grid):
""" Called at each loop iteration to construct the new state from
the update environment grid.
Returns:
None
"""
raise NotImplementedError
def learn(self):
""" Called at each loop iteration when the agent is learning. It should
implement the learning procedure.
Returns:
None
"""
raise NotImplementedError
def callback(self, learn, episode, iteration):
""" Called at each loop iteration mainly for reporting purposes.
Args:
learn (bool): Indicates whether the agent is learning or not.
episode (int): The number of the current episode.
iteration (int): The number of the current iteration.
Returns:
None
"""
raise NotImplementedError
| {
"content_hash": "cd88f4597a8e7fec97f1a128823e0307",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 84,
"avg_line_length": 31.168067226890756,
"alnum_prop": 0.5845241304933945,
"repo_name": "mamikonyana/mamikonyana.github.io",
"id": "1217908fe0ce3b0d525f70a5562cefbb39200914",
"size": "3709",
"binary": false,
"copies": "1",
"ref": "refs/heads/flask",
"path": "static/ml_afternoon/presentation_data/practical_s6/code/enduro/agent.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "102"
},
{
"name": "HTML",
"bytes": "11586263"
},
{
"name": "Makefile",
"bytes": "384"
},
{
"name": "Python",
"bytes": "95088"
},
{
"name": "Shell",
"bytes": "1662"
},
{
"name": "Stan",
"bytes": "872"
}
],
"symlink_target": ""
} |
"""
Definition of urls for $safeprojectname$.
"""
from django.conf.urls import include, url
import $safeprojectname$.views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', $safeprojectname$.views.home, name='home'),
# url(r'^$safeprojectname$/', include('$safeprojectname$.$safeprojectname$.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
]
| {
"content_hash": "2a193fdc3a63663e52fa05eec61299b0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 87,
"avg_line_length": 28.82608695652174,
"alnum_prop": 0.6923076923076923,
"repo_name": "DinoV/PTVS",
"id": "c9ba270513edf5e9b8f4552e418f3e521c129dd5",
"size": "663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/Templates/Django/ProjectTemplates/Python/Web/WebRoleDjango/urls.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "4035"
},
{
"name": "C",
"bytes": "4974"
},
{
"name": "C#",
"bytes": "13192050"
},
{
"name": "C++",
"bytes": "187194"
},
{
"name": "CSS",
"bytes": "7024"
},
{
"name": "HTML",
"bytes": "45289"
},
{
"name": "JavaScript",
"bytes": "85712"
},
{
"name": "Objective-C",
"bytes": "4201"
},
{
"name": "PowerShell",
"bytes": "135280"
},
{
"name": "Python",
"bytes": "943244"
},
{
"name": "Smarty",
"bytes": "8356"
},
{
"name": "Tcl",
"bytes": "24968"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_13b.html">Class Test_AbaRouteValidator_13b</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_29565_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b.html?line=56824#src-56824" >testAbaNumberCheck_29565_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:43:04
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_29565_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=13330#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {
"content_hash": "d19dff2307ba8af6e64ddfd35f24a8eb",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 297,
"avg_line_length": 43.942583732057415,
"alnum_prop": 0.5099085365853658,
"repo_name": "dcarda/aba.route.validator",
"id": "e0e675874d6a008d45b7a04e653fe3cfdbe65b76",
"size": "9184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b_testAbaNumberCheck_29565_good_aaa.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "18715254"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>minka-parent</artifactId>
<groupId>io.tilt.minka</groupId>
<version>0.3-SNAPSHOT</version>
</parent>
<artifactId>minka-server</artifactId>
<packaging>jar</packaging>
<name>Minka Server</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jersey.version>2.24</jersey.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.tilt.minka</groupId>
<artifactId>minka-spectator</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.3-M1</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<!-- LOGGING -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId>
</dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version> </dependency> <dependency> <groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId> <version>1.7.13</version> <scope>compile</scope>
</dependency> -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "5038061848e77263a623d99a122108a8",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 100,
"avg_line_length": 30.793893129770993,
"alnum_prop": 0.7077342588001984,
"repo_name": "gcristian/minka",
"id": "b78b43b3f5acff849a36de1dabbc11761c6424dc",
"size": "4034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "9444"
},
{
"name": "Java",
"bytes": "880356"
},
{
"name": "Shell",
"bytes": "864"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" id="top">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta name="robots" content="noarchive" />
<meta name="description" content="description" />
<meta name="keywords" content="bbs, board, anonymous, free, debate, discuss" />
<title>Topic: sdfdsfsdfs — MiniBBS</title>
</head>
<body class="">
<h1 class="top_text" id="logo">
<a rel="index" href="/" class="help_cursor" title="MiniBBS">MiniBBS</a>
</h1>
<div id="main_menu_wrapper">
<ul id="main_menu" class="menu">
<li class="hot_topics"><a href="/hot_topics">Hot</a> </li>
<li class="topics"><a href="/topics">Topics</a> </li>
<li class="bumps"><a href="/bumps">Bumps</a> </li>
<li class="replies"><a href="/replies">Replies</a> </li>
<li class="new_topic"><a href="/new_topic">New topic</a> </li>
<li class="history"><a href="/history">History</a> </li>
<li class="watchlist"><a href="/watchlist">Watchlist</a> </li>
<li class="bulletins"><a href="/bulletins">Bulletins</a> </li>
<li class="events"><a href="/events">Events</a> </li>
<li class="folks"><a href="/folks">Folks</a> </li>
<li class="search"><a href="/search">Search</a> </li>
<li class="shuffle"><a href="/shuffle">Shuffle</a> </li>
<li class="stuff"><a href="/stuff">Stuff</a> </li>
</ul>
</div>
<div id="body_wrapper">
<h2>
Topic: sdfdsfsdfs </h2>
<form id="dummy_form" class="noscreen" action="" method="post">
<div class="noscreen">
<input type="hidden" name="CSRF_token" value="4f042262a4fb31b0da4e6553458ca5e2" /> </div>
<div>
<input type="hidden" name="some_var" value="" /> </div>
</form>
<h3><strong>username</strong> started this discussion <strong><span class="help" title="2015-01-22 19:22:30 UTC — Thursday the 22nd of January 2015, 7:22 PM">3 days ago</span> <span class="reply_id unimportant"><a href="/topic/31777">#31,777</a></span></strong></h3>
<div class="body">dfsdfsdfsd
<ul class="menu">
<li><a href="/watch_topic/31777" onclick="return submitDummyForm('/watch_topic/31777', 'id', 31777, 'Add this topic to the watchlist?');">Watch</a> </li>
<li><a href="/new_reply/31777/quote_topic" onclick="quickQuote('OP', '%3E+dfsdfsdfsd');return false;">Quote</a> </li>
<li><a href="/trivia_for_topic/31777" class="help" title="1 reply">13 visits</a> </li>
</ul>
</div>
<h3 class="c" name="reply_446951" id="reply_446951">Anonymous <strong>B</strong> joined in and replied with this <strong><span class="help" title="2015-01-25 20:19:47 UTC — Sunday the 25th of January 2015, 8:19 PM">3 hours ago</span></strong>, 3 days later<span class="reply_id unimportant"><a href="#top">[^]</a> <a href="#bottom">[v]</a> <a href="#reply_446951">#446,951</a></span></h3>
<div class="body" id="reply_box_446951">test
<ul class="menu">
<li><a href="/new_reply/31777/quote_reply/446951" onclick="quickQuote(446951, '%3E+test');return false;">Quote</a> </li>
<li><a href="/new_reply/31777/cite_reply/446951" onclick="quickCite(446951);return false;">Cite</a> </li>
</ul>
</div>
<ul class="menu">
<li><a href="/new_reply/31777" onclick="$('#quick_reply').toggle();$('#qr_text').get(0).scrollIntoView(true);$('#qr_text').focus(); return false;">Reply</a> <span class="reply_id unimportant"><a href="#top">[Top]</a></span> </li>
</ul>
<div id="quick_reply" class="noscreen">
<form enctype="multipart/form-data" action="/new_reply/31777/4cbc7626716ad8c6dde29e1288a9b625" method="post">
<div class="noscreen">
<input type="hidden" name="CSRF_token" id="CSRF_token" value="4f042262a4fb31b0da4e6553458ca5e2" /> </div>
<input name="form_sent" type="hidden" value="1" />
<input name="e-mail" type="hidden" />
<input name="start_time" type="hidden" value="1422228137" />
<input name="image" type="hidden" value="" />
<div class="row">
<label for="name">Name</label>:
<input class="inline" id="name" name="name" type="text" size="30" placeholder="name #tripcode" maxlength="30" tabindex="2" value=""> </div>
<textarea class="inline markup_editor" name="body" id="qr_text" rows="5" cols="90" tabindex="3"></textarea>
<input type="file" name="image" id="image" tabindex="5" />
<label for="imageurl">Imgur URL:</label>
<input class="inline" type="text" name="imageurl" id="imageurl" size="21" placeholder="http://i.imgur.com/rcrlO.jpg" /> <a href="javascript:document.getElementById('imgurupload').click()" id="uploader">[upload]</a>
<br />
<input type="submit" name="preview" tabindex="6" value="Preview" class="inline" />
<input type="submit" name="post" tabindex="4" value="Post" class="inline">
<p>Please familiarise yourself with the <a href="/rules" target="_blank">rules</a> and <a href="/markup_syntax" target="_blank">markup syntax</a> before posting, also keep in mind you can minify URLs using <a href="/link" target="_blank">MiniURL</a> and generate image macros using <a href="/macro" target="_blank">MiniMacro</a>.</p>
</form>
<input style="visibility: hidden; width: 0px; height: 0px;" type="file" id="imgurupload" onchange="uploadImage(this.files[0])"> </div>
<div id="bottom"></div>
<a id='snapback_link' style='display: none' class='help_cursor' onclick='return popSnapbackLink();' title='Click me to snap back!' href='#'> <strong>↕</strong> <span> </span> </a>
</body>
</html>
| {
"content_hash": "fd3bcd987170425abaeaa65caa049ed1",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 396,
"avg_line_length": 71.30588235294118,
"alnum_prop": 0.5805972611780235,
"repo_name": "parhamr/foramora",
"id": "69ab3100a1e140aa342c233bbf0efa88a52d6302",
"size": "6069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/fixtures/minibbs/topic.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "57009"
}
],
"symlink_target": ""
} |
import { expect } from 'chai';
import $ from './data/_.nested'; // FORMS
describe('Form state extra', () => {
it('$A state.$extra should have "foo" property', () =>
expect($.$A.state.$extra).to.have.property('foo'));
it('$A state.$extra "foo" prop should be "bar"', () =>
expect($.$A.state.extra('foo')).to.be.equal('bar'));
it('$B state.extra() should be array', () =>
expect($.$B.state.extra()).to.be.instanceof(Array));
});
| {
"content_hash": "f891f7baf0f07dc3c934f51404919637",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 56,
"avg_line_length": 32.07142857142857,
"alnum_prop": 0.579064587973274,
"repo_name": "foxhound87/mobx-ajv-form",
"id": "a8fbb9fa1507dae9a63a0a550011d5bf3d9d2200",
"size": "449",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/nested.state.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2442"
},
{
"name": "JavaScript",
"bytes": "48957"
}
],
"symlink_target": ""
} |
/*jshint expr: true*/
'use strict';
var should = require('should')
, http = require('http')
, LiveReloadJsHandler = require('../lib/server').LiveReloadJsHandler;
describe('LiveReloadJsHandler', function() {
var server;
beforeEach(function() {
server = http.createServer(function(req, res) {
if (!new LiveReloadJsHandler().handle(req, res)) {
res.writeHead(500);
res.write('error');
res.end();
}
}).listen(8000);
});
afterEach(function() {
server.close();
});
it('should handle /livereload.js', function(done) {
http.get('http://localhost:8000/livereload.js', function(res) {
res.should.have.status(200);
res.should.have.header('content-type', 'application/javascript; charset=UTF-8');
res.on('data', function(data) {});
res.on('end', function(chunk) {
done();
});
});
});
it('should skip /', function(done) {
http.get('http://localhost:8000/', function(res) {
res.should.have.status(500);
done();
});
});
});
| {
"content_hash": "3dbad8ea43e66d6498bb2a41cee40fbf",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 86,
"avg_line_length": 25.609756097560975,
"alnum_prop": 0.5904761904761905,
"repo_name": "nitoyon/livereloadx",
"id": "8c896e09435202cf851067a80562aaa260e45f79",
"size": "1050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test.server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "396"
},
{
"name": "JavaScript",
"bytes": "94153"
}
],
"symlink_target": ""
} |
package sgdk.rescomp.resource;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sgdk.rescomp.Resource;
import sgdk.rescomp.tool.Util;
import sgdk.rescomp.type.Basics.Compression;
import sgdk.rescomp.type.Basics.TileEquality;
import sgdk.rescomp.type.Basics.TileOptimization;
import sgdk.rescomp.type.MapBlock;
import sgdk.rescomp.type.Metatile;
import sgdk.rescomp.type.Tile;
import sgdk.tool.ImageUtil;
import sgdk.tool.ImageUtil.BasicImageInfo;
public class Map extends Resource
{
public static Map getMap(String id, String imgFile, int mapBase, int metatileSize, List<Tileset> tilesets, Compression compression, boolean addTileset) throws Exception
{
// get 8bpp pixels and also check image dimension is aligned to tile
final byte[] image = Util.getImage8bpp(imgFile, true, true);
// happen when we couldn't retrieve palette data from RGB image
if (image == null)
throw new IllegalArgumentException(
"RGB image '" + imgFile + "' does not contains palette data (see 'Important note about image format' in the rescomp.txt file");
// b0-b3 = pixel data; b4-b5 = palette index; b7 = priority bit
// check if image try to use bit 6 (probably mean that we have too much colors in our image)
for (byte d : image)
{
// bit 6 used ?
if ((d & 0x40) != 0)
throw new IllegalArgumentException(
"'" + imgFile + "' has color index in [64..127] range, IMAGE resource requires image with a maximum of 64 colors");
}
// retrieve basic infos about the image
final BasicImageInfo imgInfo = ImageUtil.getBasicInfo(imgFile);
final int w = imgInfo.w;
// we determine 'h' from data length and 'w' as we can crop image vertically to remove palette data
final int h = image.length / w;
return new Map(id, image, w, h, mapBase, metatileSize, tilesets, compression, addTileset);
}
public final int wb;
public final int hb;
public final Compression compression;
final int hc;
public final List<Metatile> metatiles;
public final List<MapBlock> mapBlocks;
public final List<short[]> mapBlockIndexes;
public final short[] mapBlockRowOffsets;
public final List<Tileset> tilesets;
// binary data
public final Bin metatilesBin;
public final Bin mapBlocksBin;
public final Bin mapBlockIndexesBin;
public final Bin mapBlockRowOffsetsBin;
public Map(String id, byte[] image8bpp, int imageWidth, int imageHeight, int mapBase, int metatileSize, List<Tileset> tilesets, Compression compression,
boolean addTileset) throws IllegalArgumentException
{
super(id);
// get size in tile
final int wt = imageWidth / 8;
final int ht = imageHeight / 8;
// base prio, pal attributes and base tile index offset
final boolean mapBasePrio = (mapBase & Tile.TILE_PRIORITY_MASK) != 0;
final int mapBasePal = (mapBase & Tile.TILE_PALETTE_MASK) >> Tile.TILE_PALETTE_SFT;
final int mapBaseTileInd = mapBase & Tile.TILE_INDEX_MASK;
// store base tile index usage
final boolean hasBaseTileIndex = mapBaseTileInd != 0;
// store tileset
this.tilesets = tilesets;
// add tileset resources (and replace by duplicate if found)
if (addTileset)
{
for (int t = 0; t < tilesets.size(); t++)
this.tilesets.set(t, (Tileset) addInternalResource(tilesets.get(t)));
}
// store compression
this.compression = compression;
// get size in block
wb = (wt + 15) / 16;
hb = (ht + 15) / 16;
// build global TILESET
final Tileset tileset = new Tileset(tilesets);
// build METATILES
metatiles = new ArrayList<>();
// build MAPBLOCKS
mapBlocks = new ArrayList<>();
// build block indexes
mapBlockIndexes = new ArrayList<>();
// build block row offsets
mapBlockRowOffsets = new short[hb];
// set to -1 to mark that it's not yet set (we shouldn't never meet an offset of 65535 realistically)
Arrays.fill(mapBlockRowOffsets, (short) -1);
// important to always use the same loop order when building Tileset and Tilemap object
for (int j = 0; j < hb; j++)
{
int mbrii = 0;
final short[] mbRowIndexes = new short[wb];
for (int i = 0; i < wb; i++)
{
final MapBlock mb = new MapBlock();
int mbi = 0;
for (int bj = 0; bj < 8; bj++)
{
for (int bi = 0; bi < 8; bi++)
{
final Metatile mt = new Metatile();
int mtsi = 0;
for (int mj = 0; mj < metatileSize; mj++)
{
for (int mi = 0; mi < metatileSize; mi++)
{
// tile position
final int ti = ((i * 16) + (bi * 2) + (mi * 1));
final int tj = ((j * 16) + (bj * 2) + (mj * 1));
final Tile tile;
final TileEquality eq;
int index;
// outside image ?
if ((ti >= wt) || (tj >= ht))
{
// use dummy tile
tile = new Tile(new byte[64], 8, 0, false, -1);
eq = TileEquality.NONE;
index = 0;
}
else
{
tile = Tile.getTile(image8bpp, wt * 8, ht * 8, ti * 8, tj * 8, 8);
// we can use system tiles when we have a base tile offset
if (hasBaseTileIndex && tile.isPlain())
{
index = tile.getPlainValue();
eq = TileEquality.NONE;
}
else
{
// otherwise we try to get tile index in the tileset
index = tileset.getTileIndex(tile, TileOptimization.ALL);
// not found ? (should never happen)
if (index == -1)
throw new RuntimeException("Can't find tile [" + ti + "," + tj + "] in tileset, something wrong happened...");
// index > 2047 ? --> not allowed
if (index > 2047)
throw new RuntimeException("Can't have more than 2048 different tiles, try to reduce number of unique tile...");
// get equality info
eq = tile.getEquality(tileset.get(index));
// can add base index now
index += mapBaseTileInd;
}
}
// set metatile attributes
mt.set(mtsi++, (short) Tile.TILE_ATTR_FULL(mapBasePal + tile.pal, mapBasePrio | tile.prio, eq.vflip, eq.hflip, index));
}
}
// update internals (hash code)
mt.updateInternals();
// get index of metatile
int mtIndex = getMetaTileIndex(mt);
// not yet present ?
if (mtIndex == -1)
{
// get index
mtIndex = metatiles.size();
// add to MetaTiles list
metatiles.add(mt);
}
// set block attributes (metatile index only here)
mb.set(mbi++, (short) mtIndex);
}
}
// update hash code
mb.computeHashCode();
// get index of block
int mbIndex = getBlockIndex(mb);
// not yet present ?
if (mbIndex == -1)
{
// get index
mbIndex = mapBlocks.size();
// add to MapBlock list
mapBlocks.add(mb);
}
// store MapBlock index (we can't have more than 65536 blocks)
mbRowIndexes[mbrii++] = (short) mbIndex;
}
// check if we have a duplicated map block row
for (int i = 0; i < mapBlockIndexes.size(); i++)
{
// duplicated ?
if (Arrays.equals(mbRowIndexes, mapBlockIndexes.get(i)))
{
// store offset for this map block row
mapBlockRowOffsets[j] = (short) (i * wb);
break;
}
}
// not yet set ?
if (mapBlockRowOffsets[j] == -1)
{
// set offset to current row
mapBlockRowOffsets[j] = (short) (mapBlockIndexes.size() * wb);
// and add map block row indexes to list
mapBlockIndexes.add(mbRowIndexes);
}
}
// convert metatiles to array
short[] mtData = new short[metatiles.size() * (metatileSize * metatileSize)];
int offset = 0;
for (Metatile mt : metatiles)
{
// we can't use packed metatile representation when we have a base tile index
for (short attr : mt.data)
mtData[offset++] = attr;
}
// build BIN (metatiles data)
metatilesBin = (Bin) addInternalResource(new Bin(id + "_metatiles", mtData, compression));
// convert mapBlocks to array
if (metatiles.size() > 256)
{
// require 16 bit index
final short[] mbData = new short[mapBlocks.size() * (8 * 8)];
offset = 0;
for (MapBlock mb : mapBlocks)
{
for (short ind : mb.data)
mbData[offset++] = ind;
}
// build BIN (mapBlocks data)
mapBlocksBin = (Bin) addInternalResource(new Bin(id + "_mapBlocks", mbData, compression));
}
else
{
// 8 bit index
final byte[] mbData = new byte[mapBlocks.size() * (8 * 8)];
offset = 0;
for (MapBlock mb : mapBlocks)
{
for (short ind : mb.data)
mbData[offset++] = (byte) ind;
}
// build BIN (mapBlocks data)
mapBlocksBin = (Bin) addInternalResource(new Bin(id + "_mapBlocks", mbData, compression));
}
// require 16 bit index ? --> directly use mapBlockIndexes map
if (mapBlocks.size() > 256)
{
// 16 bit index
final short[] mbiData = new short[mapBlockIndexes.size() * wb];
offset = 0;
for (short[] rowIndexes : mapBlockIndexes)
for (short ind : rowIndexes)
mbiData[offset++] = ind;
// build BIN (mapBlockIndexes data)
mapBlockIndexesBin = (Bin) addInternalResource(new Bin(id + "_mapBlockIndexes", mbiData, compression));
}
else
{
// 8 bit index
final byte[] mbiData = new byte[mapBlockIndexes.size() * wb];
offset = 0;
for (short[] rowIndexes : mapBlockIndexes)
for (short ind : rowIndexes)
mbiData[offset++] = (byte) ind;
// build BIN (mapBlockIndexes data)
mapBlockIndexesBin = (Bin) addInternalResource(new Bin(id + "_mapBlockIndexes", mbiData, compression));
}
// build BIN (mapBlockRowOffsets data) - never compressed (not worthing it)
mapBlockRowOffsetsBin = (Bin) addInternalResource(new Bin(id + "_mapBlockRowOffsets", mapBlockRowOffsets, Compression.NONE));
// check if we can unpack the MAP
if (compression != Compression.NONE)
{
// get unpacked size
int ts = totalSize();
// fix for condensed encoded metatiles
if (!hasBaseTileIndex)
{
// remove metatiles binary blob size
ts -= metatilesBin.totalSize();
// add metatiles definition RAW size
ts += metatiles.size() * 4 * 2;
}
// above 48 KB ? --> error
if (ts > (48 * 1024))
throw new RuntimeException("Error: MAP '" + id + "' unpacked size = " + ts
+ " bytes, you won't have enough memory to unpack it.\nRemove compression from MAP resource definition");
// above 34 KB ? --> warning
if (ts > (34 * 1024))
System.err.println("Warning: MAP '" + id + "' unpacked size = " + ts
+ " bytes, you may not be able to unpack it.\nYou may remove compression from MAP resource definition");
}
// compute hash code
hc = tileset.hashCode() ^ metatilesBin.hashCode() ^ mapBlocksBin.hashCode() ^ mapBlockIndexesBin.hashCode() ^ mapBlockRowOffsetsBin.hashCode();
}
public int getMetaTileIndex(Metatile metatile)
{
for (int ind = 0; ind < metatiles.size(); ind++)
{
final Metatile mt = metatiles.get(ind);
// we found a matching metatile --> return its index
if (mt.equals(metatile))
return ind;
}
// not found
return -1;
}
private int getBlockIndex(MapBlock mapBlock)
{
return mapBlocks.indexOf(mapBlock);
}
/**
* Returns width in block
*/
public int getWidth()
{
return wb;
}
/**
* Returns height in block
*/
public int getHeight()
{
return hb;
}
private int getCompression()
{
int result = 0;
result += (mapBlockIndexesBin.packedData.compression.ordinal() - 1);
result <<= 4;
result += (mapBlocksBin.packedData.compression.ordinal() - 1);
result <<= 4;
result += (metatilesBin.packedData.compression.ordinal() - 1);
return result;
}
@Override
public int internalHashCode()
{
return hc;
}
@Override
public boolean internalEquals(Object obj)
{
if (obj instanceof Map)
{
final Map map = (Map) obj;
return metatiles.equals(map.metatiles) && mapBlocks.equals(map.mapBlocks) && mapBlockIndexesBin.equals(map.mapBlockIndexesBin)
&& Arrays.equals(mapBlockRowOffsets, map.mapBlockRowOffsets);
}
return false;
}
@Override
public List<Bin> getInternalBinResources()
{
return Arrays.asList(metatilesBin, mapBlocksBin, mapBlockIndexesBin, mapBlockRowOffsetsBin);
}
@Override
public int shallowSize()
{
return 2 + 2 + 2 + 2 + 4 + 4 + 4 + 4 + 4 + 4;
}
@Override
public int totalSize()
{
int result = metatilesBin.totalSize() + mapBlocksBin.totalSize() + mapBlockIndexesBin.totalSize() + mapBlockRowOffsetsBin.totalSize() + shallowSize();
return result;
}
@Override
public void out(ByteArrayOutputStream outB, StringBuilder outS, StringBuilder outH)
{
// can't store pointer so we just reset binary stream here (used for compression only)
outB.reset();
// output Image structure
Util.decl(outS, outH, "MapDefinition", id, 2, global);
// set size in block
outS.append(" dc.w " + wb + ", " + hb + "\n");
// set real height of mapBlockIndexes (can have duplicated row which aren't stored)
outS.append(" dc.w " + mapBlockIndexes.size() + "\n");
// set compression
outS.append(" dc.w " + getCompression() + "\n");
// set num metatile
outS.append(" dc.w " + metatiles.size() + "\n");
// set num mapblock
outS.append(" dc.w " + mapBlocks.size() + "\n");
// set metatile data pointer
outS.append(" dc.l " + metatilesBin.id + "\n");
// set mapblock data pointer
outS.append(" dc.l " + mapBlocksBin.id + "\n");
// set mapBlockIndexes data pointer
outS.append(" dc.l " + mapBlockIndexesBin.id + "\n");
// set mapBlockRowOffsets data pointer
outS.append(" dc.l " + mapBlockRowOffsetsBin.id + "\n");
outS.append("\n");
}
@Override
public String toString()
{
// display info about map encoding
return "MAP '" + id + "' details: " + tilesets.size() + " tilesets, " + metatiles.size() + " metatiles, " + mapBlocks.size()
+ " blocks, block grid size = " + wb + " x " + hb + " - optimized = " + wb + " x " + mapBlockIndexes.size();
}
}
| {
"content_hash": "b57acd901a835311b3a04535b608ef9c",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 172,
"avg_line_length": 38.07066381156317,
"alnum_prop": 0.5012092918611846,
"repo_name": "andwn/SGDK",
"id": "7341fbb958ae46b739b68ba7339336d6a827466e",
"size": "17779",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/rescomp/src/sgdk/rescomp/resource/Map.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "207715"
},
{
"name": "Batchfile",
"bytes": "3686"
},
{
"name": "C",
"bytes": "2542087"
},
{
"name": "Dockerfile",
"bytes": "672"
},
{
"name": "Java",
"bytes": "747744"
},
{
"name": "Makefile",
"bytes": "1456"
},
{
"name": "PowerShell",
"bytes": "3188"
},
{
"name": "ReScript",
"bytes": "171"
},
{
"name": "Shell",
"bytes": "585"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_loop_11.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-11.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: loop
* BadSink : Copy int64_t array to data using a loop
* Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_loop_11
{
#ifndef OMITBAD
void bad()
{
int64_t * data;
data = NULL;
if(globalReturnsTrue())
{
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new int64_t[50];
}
{
int64_t source[100] = {0}; /* fill with 0's */
{
size_t i;
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
for (i = 0; i < 100; i++)
{
data[i] = source[i];
}
printLongLongLine(data[0]);
delete [] data;
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */
static void goodG2B1()
{
int64_t * data;
data = NULL;
if(globalReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int64_t[100];
}
{
int64_t source[100] = {0}; /* fill with 0's */
{
size_t i;
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
for (i = 0; i < 100; i++)
{
data[i] = source[i];
}
printLongLongLine(data[0]);
delete [] data;
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int64_t * data;
data = NULL;
if(globalReturnsTrue())
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int64_t[100];
}
{
int64_t source[100] = {0}; /* fill with 0's */
{
size_t i;
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
for (i = 0; i < 100; i++)
{
data[i] = source[i];
}
printLongLongLine(data[0]);
delete [] data;
}
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_loop_11; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "28aa97eaf2cd7cda44f73066cca02511",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 135,
"avg_line_length": 27.965034965034967,
"alnum_prop": 0.5633908477119279,
"repo_name": "maurer/tiamat",
"id": "e3c81fe9ef117ee7c877c0a6aea2b30da8201803",
"size": "3999",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_loop_11.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@interface BHRSinglePageProjectItem : BHRProjectItem
@property (nonatomic, strong) UIColor *backgroundColor;
- (NSURL *)videoURL;
@end
| {
"content_hash": "ef3d831a4d383759c41b13ecf4ca2c03",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 55,
"avg_line_length": 19.714285714285715,
"alnum_prop": 0.782608695652174,
"repo_name": "bhr/WWDC2014-Scholarship-Application",
"id": "4307b33cb10a0a203c275844093f685c51c9de81",
"size": "325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Benedikt Hirmer/Source/BHRSinglePageProjectItem.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "163515"
}
],
"symlink_target": ""
} |
#include "OVR_Timer.h"
#include "OVR_Log.h"
#if defined (OVR_OS_WIN32)
#include <windows.h>
#elif defined(OVR_OS_ANDROID)
#include <time.h>
#include <android/log.h>
#else
#include <sys/time.h>
#endif
namespace OVR {
//------------------------------------------------------------------------
// *** Timer - Platform Independent functions
double ovr_GetTimeInSeconds()
{
return Timer::GetSeconds();
}
UInt64 Timer::GetProfileTicks()
{
return (GetRawTicks() * MksPerSecond) / GetRawFrequency();
}
double Timer::GetProfileSeconds()
{
static UInt64 StartTime = GetProfileTicks();
return TicksToSeconds(GetProfileTicks()-StartTime);
}
#ifndef OVR_OS_ANDROID
double Timer::GetSeconds()
{
return (double)Timer::GetRawTicks() / (double) GetRawFrequency();
}
#endif
//------------------------------------------------------------------------
// *** Android Specific Timer
#if defined(OVR_OS_ANDROID)
// Returns global high-resolution application timer in seconds.
double Timer::GetSeconds()
{
return double(Timer::GetRawTicks()) * 0.000000001;
}
UInt64 Timer::GetRawTicks()
{
// Choreographer vsync timestamp is based on.
struct timespec tp;
const int status = clock_gettime(CLOCK_MONOTONIC, &tp);
if (status != 0)
{
OVR_DEBUG_LOG(("clock_gettime status=%i", status ));
}
const UInt64 result = (UInt64)tp.tv_sec * (UInt64)(1000 * 1000 * 1000) + UInt64(tp.tv_nsec);
return result;
}
UInt64 Timer::GetRawFrequency()
{
return MksPerSecond * 1000;
}
#endif
//------------------------------------------------------------------------
// *** Win32 Specific Timer
#if defined (OVR_OS_WIN32)
CRITICAL_SECTION WinAPI_GetTimeCS;
volatile UInt32 WinAPI_OldTime = 0;
volatile UInt32 WinAPI_WrapCounter = 0;
UInt32 Timer::GetTicksMs()
{
return timeGetTime();
}
UInt64 Timer::GetTicks()
{
DWORD ticks = timeGetTime();
UInt64 result;
// On Win32 QueryPerformanceFrequency is unreliable due to SMP and
// performance levels, so use this logic to detect wrapping and track
// high bits.
::EnterCriticalSection(&WinAPI_GetTimeCS);
if (WinAPI_OldTime > ticks)
WinAPI_WrapCounter++;
WinAPI_OldTime = ticks;
result = (UInt64(WinAPI_WrapCounter) << 32) | ticks;
::LeaveCriticalSection(&WinAPI_GetTimeCS);
return result * MksPerMs;
}
UInt64 Timer::GetRawTicks()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return li.QuadPart;
}
UInt64 Timer::GetRawFrequency()
{
static UInt64 perfFreq = 0;
if (perfFreq == 0)
{
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
perfFreq = freq.QuadPart;
}
return perfFreq;
}
void Timer::initializeTimerSystem()
{
timeBeginPeriod(1);
InitializeCriticalSection(&WinAPI_GetTimeCS);
}
void Timer::shutdownTimerSystem()
{
DeleteCriticalSection(&WinAPI_GetTimeCS);
timeEndPeriod(1);
}
#else // !OVR_OS_WIN32
//------------------------------------------------------------------------
// *** Standard OS Timer
UInt32 Timer::GetTicksMs()
{
return (UInt32)(GetProfileTicks() / 1000);
}
// The profile ticks implementation is just fine for a normal timer.
UInt64 Timer::GetTicks()
{
return GetProfileTicks();
}
void Timer::initializeTimerSystem()
{
}
void Timer::shutdownTimerSystem()
{
}
#if !defined(OVR_OS_ANDROID)
UInt64 Timer::GetRawTicks()
{
// TODO: prefer rdtsc when available?
UInt64 result;
// Return microseconds.
struct timeval tv;
gettimeofday(&tv, 0);
result = (UInt64)tv.tv_sec * 1000000;
result += tv.tv_usec;
return result;
}
UInt64 Timer::GetRawFrequency()
{
return MksPerSecond;
}
#endif // !OVR_OS_ANDROID
#endif // !OVR_OS_WIN32
} // OVR
| {
"content_hash": "9ca3a99172c5f9c3cc409abf2c163587",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 96,
"avg_line_length": 18.736318407960198,
"alnum_prop": 0.6192246415294742,
"repo_name": "joeyzhang105/InspireVR",
"id": "84ff4a156af75f2a4ce98fc219724ebe388fa1d8",
"size": "4845",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "pc/OculusSDK/LibOVR/Src/Kernel/OVR_Timer.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10189"
},
{
"name": "C++",
"bytes": "2416917"
},
{
"name": "Objective-C",
"bytes": "1461"
},
{
"name": "Objective-C++",
"bytes": "13805"
}
],
"symlink_target": ""
} |
package com.netflix.hollow.api.consumer.data;
import com.netflix.hollow.core.AbstractStateEngineTest;
import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
import java.util.Collection;
import java.util.List;
import org.junit.Assert;
public abstract class AbstractPrimitiveTypeDataAccessorTest<T> extends AbstractStateEngineTest {
HollowObjectMapper objectMapper;
protected abstract Class<T> getDataModelTestClass();
protected abstract T getData(HollowObjectTypeReadState readState, int ordinal);
@Override
protected void initializeTypeStates() {
objectMapper = new HollowObjectMapper(writeStateEngine);
objectMapper.initializeTypeState(getDataModelTestClass());
}
protected void addRecord(Object obj) {
objectMapper.add(obj);
}
protected void assertObject(HollowObjectTypeReadState readState, int ordinal, T expectedValue) {
Object obj = getData(readState, ordinal);
Assert.assertEquals(expectedValue, obj);
}
protected void assertList(Collection<T> listOfObj, List<T> expectedObjs) {
int i = 0;
for (T obj : listOfObj) {
Object expectedObj = expectedObjs.get(i++);
Assert.assertEquals(expectedObj, obj);
}
}
// protected void assertUpdatedList(Collection<UpdatedRecord<T>> listOfObj, List<T> beforeValues, List<T> afterValues) {
// int i = 0;
// for (UpdatedRecord<T> obj : listOfObj) {
// T before = obj.getBefore();
// T after = obj.getAfter();
// Assert.assertNotEquals(before, after);
//
// T expBefore= beforeValues.get(i);
// T expAfter = afterValues.get(i++);
// Assert.assertNotEquals(expBefore, expAfter);
// Assert.assertEquals(expBefore, before);
// Assert.assertEquals(expAfter, after);
// }
// }
} | {
"content_hash": "1d484922c259b6f18ccc3b4a9b0575fc",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 123,
"avg_line_length": 35.107142857142854,
"alnum_prop": 0.6831129196337742,
"repo_name": "Netflix/hollow",
"id": "fdd46cf01d54b24399d8bd8a79cb56fed3cc17ca",
"size": "2604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hollow/src/test/java/com/netflix/hollow/api/consumer/data/AbstractPrimitiveTypeDataAccessorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4299"
},
{
"name": "Java",
"bytes": "4694590"
},
{
"name": "JavaScript",
"bytes": "1703"
},
{
"name": "Shell",
"bytes": "1730"
}
],
"symlink_target": ""
} |
import warnings
warnings.simplefilter('ignore', Warning)
from django.conf import settings
from core.tests.backends import *
from core.tests.fields import *
from core.tests.forms import *
from core.tests.indexes import *
from core.tests.inputs import *
from core.tests.loading import *
from core.tests.models import *
from core.tests.query import *
from core.tests.templatetags import *
from core.tests.views import *
from core.tests.utils import *
from core.tests.management_commands import *
| {
"content_hash": "527d18796478f4378e54646d57cf0f5d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 44,
"avg_line_length": 29.11764705882353,
"alnum_prop": 0.793939393939394,
"repo_name": "josesanch/django-haystack",
"id": "2aef8ad618fea691a4d5a0ecc7ed882a2b79ba12",
"size": "495",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/core/tests/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "676842"
},
{
"name": "Shell",
"bytes": "1583"
}
],
"symlink_target": ""
} |
struct system {};
system discretize(const mesh& m);
void solve(system& s);
#endif // GREATEST_BESTEST_SOLVER_INCLUDE
| {
"content_hash": "8123e94ccd3b3c83dfe1bf30831525ab",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 41,
"avg_line_length": 17.142857142857142,
"alnum_prop": 0.725,
"repo_name": "tzaffi/cpp",
"id": "1f8fe7591e3b21a9696a10a3dd49dcb1dabcf860",
"size": "224",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "DMCpp/GottschlingRepo/buildtools/solver.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2021"
},
{
"name": "C",
"bytes": "17554"
},
{
"name": "C++",
"bytes": "1110782"
},
{
"name": "CMake",
"bytes": "25110"
},
{
"name": "Makefile",
"bytes": "35509"
},
{
"name": "Shell",
"bytes": "652"
}
],
"symlink_target": ""
} |
package server
import (
"bufio"
"bytes"
"runtime"
"time"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"strings"
"code.google.com/p/go.net/websocket"
"github.com/gorilla/mux"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
"github.com/docker/docker/autogen/dockerversion"
"github.com/docker/docker/daemon"
"github.com/docker/docker/daemon/networkdriver/bridge"
"github.com/docker/docker/engine"
"github.com/docker/docker/graph"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/parsers"
"github.com/docker/docker/pkg/parsers/filters"
"github.com/docker/docker/pkg/parsers/kernel"
"github.com/docker/docker/pkg/signal"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/pkg/version"
"github.com/docker/docker/registry"
"github.com/docker/docker/runconfig"
"github.com/docker/docker/utils"
)
type ServerConfig struct {
Logging bool
EnableCors bool
CorsHeaders string
Version string
SocketGroup string
Tls bool
TlsVerify bool
TlsCa string
TlsCert string
TlsKey string
}
type Server struct {
daemon *daemon.Daemon
cfg *ServerConfig
router *mux.Router
start chan struct{}
// TODO: delete engine
eng *engine.Engine
}
func New(cfg *ServerConfig, eng *engine.Engine) *Server {
srv := &Server{
cfg: cfg,
start: make(chan struct{}),
eng: eng,
}
r := createRouter(srv, eng)
srv.router = r
return srv
}
func (s *Server) SetDaemon(d *daemon.Daemon) {
s.daemon = d
}
type serverCloser interface {
Serve() error
Close() error
}
// ServeApi loops through all of the protocols sent in to docker and spawns
// off a go routine to setup a serving http.Server for each.
func (s *Server) ServeApi(protoAddrs []string) error {
var chErrors = make(chan error, len(protoAddrs))
for _, protoAddr := range protoAddrs {
protoAddrParts := strings.SplitN(protoAddr, "://", 2)
if len(protoAddrParts) != 2 {
return fmt.Errorf("bad format, expected PROTO://ADDR")
}
go func(proto, addr string) {
logrus.Infof("Listening for HTTP on %s (%s)", proto, addr)
srv, err := s.newServer(proto, addr)
if err != nil {
chErrors <- err
return
}
s.eng.OnShutdown(func() {
if err := srv.Close(); err != nil {
logrus.Error(err)
}
})
if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
err = nil
}
chErrors <- err
}(protoAddrParts[0], protoAddrParts[1])
}
for i := 0; i < len(protoAddrs); i++ {
err := <-chErrors
if err != nil {
return err
}
}
return nil
}
type HttpServer struct {
srv *http.Server
l net.Listener
}
func (s *HttpServer) Serve() error {
return s.srv.Serve(s.l)
}
func (s *HttpServer) Close() error {
return s.l.Close()
}
type HttpApiFunc func(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
return nil, nil, err
}
// Flush the options to make sure the client sets the raw mode
conn.Write([]byte{})
return conn, conn, nil
}
func closeStreams(streams ...interface{}) {
for _, stream := range streams {
if tcpc, ok := stream.(interface {
CloseWrite() error
}); ok {
tcpc.CloseWrite()
} else if closer, ok := stream.(io.Closer); ok {
closer.Close()
}
}
}
// Check to make sure request's Content-Type is application/json
func checkForJson(r *http.Request) error {
ct := r.Header.Get("Content-Type")
// No Content-Type header is ok as long as there's no Body
if ct == "" {
if r.Body == nil || r.ContentLength == 0 {
return nil
}
}
// Otherwise it better be json
if api.MatchesContentType(ct, "application/json") {
return nil
}
return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
}
//If we don't do this, POST method without Content-type (even with empty body) will fail
func parseForm(r *http.Request) error {
if r == nil {
return nil
}
if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
}
func parseMultipartForm(r *http.Request) error {
if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
}
func httpError(w http.ResponseWriter, err error) {
statusCode := http.StatusInternalServerError
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types, we should
// create appropriate error types with clearly defined meaning.
errStr := strings.ToLower(err.Error())
if strings.Contains(errStr, "no such") {
statusCode = http.StatusNotFound
} else if strings.Contains(errStr, "bad parameter") {
statusCode = http.StatusBadRequest
} else if strings.Contains(errStr, "conflict") {
statusCode = http.StatusConflict
} else if strings.Contains(errStr, "impossible") {
statusCode = http.StatusNotAcceptable
} else if strings.Contains(errStr, "wrong login/password") {
statusCode = http.StatusUnauthorized
} else if strings.Contains(errStr, "hasn't been activated") {
statusCode = http.StatusForbidden
}
if err != nil {
logrus.Errorf("HTTP Error: statusCode=%d %v", statusCode, err)
http.Error(w, err.Error(), statusCode)
}
}
// writeJSONEnv writes the engine.Env values to the http response stream as a
// json encoded body.
func writeJSONEnv(w http.ResponseWriter, code int, v engine.Env) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
return v.Encode(w)
}
// writeJSON writes the value v to the http response stream as json with standard
// json encoding.
func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
return json.NewEncoder(w).Encode(v)
}
func streamJSON(job *engine.Job, w http.ResponseWriter, flush bool) {
w.Header().Set("Content-Type", "application/json")
if flush {
job.Stdout.Add(utils.NewWriteFlusher(w))
} else {
job.Stdout.Add(w)
}
}
func (s *Server) postAuth(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
var config *registry.AuthConfig
err := json.NewDecoder(r.Body).Decode(&config)
r.Body.Close()
if err != nil {
return err
}
status, err := s.daemon.RegistryService.Auth(config)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, &types.AuthResponse{
Status: status,
})
}
func (s *Server) getVersion(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
w.Header().Set("Content-Type", "application/json")
v := &types.Version{
Version: dockerversion.VERSION,
ApiVersion: api.APIVERSION,
GitCommit: dockerversion.GITCOMMIT,
GoVersion: runtime.Version(),
Os: runtime.GOOS,
Arch: runtime.GOARCH,
}
if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
v.KernelVersion = kernelVersion.String()
}
return writeJSON(w, http.StatusOK, v)
}
func (s *Server) postContainersKill(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
err := parseForm(r)
if err != nil {
return err
}
var sig uint64
name := vars["name"]
// If we have a signal, look at it. Otherwise, do nothing
if sigStr := vars["signal"]; sigStr != "" {
// Check if we passed the signal as a number:
// The largest legal signal is 31, so let's parse on 5 bits
sig, err = strconv.ParseUint(sigStr, 10, 5)
if err != nil {
// The signal is not a number, treat it as a string (either like
// "KILL" or like "SIGKILL")
sig = uint64(signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")])
}
if sig == 0 {
return fmt.Errorf("Invalid signal: %s", sigStr)
}
}
if err = s.daemon.ContainerKill(name, sig); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersPause(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
name := vars["name"]
cont, err := s.daemon.Get(name)
if err != nil {
return err
}
if err := cont.Pause(); err != nil {
return fmt.Errorf("Cannot pause container %s: %s", name, err)
}
cont.LogEvent("pause")
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersUnpause(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
name := vars["name"]
cont, err := s.daemon.Get(name)
if err != nil {
return err
}
if err := cont.Unpause(); err != nil {
return fmt.Errorf("Cannot unpause container %s: %s", name, err)
}
cont.LogEvent("unpause")
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) getContainersExport(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
return s.daemon.ContainerExport(vars["name"], w)
}
func (s *Server) getImagesJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
imagesConfig := graph.ImagesConfig{
Filters: r.Form.Get("filters"),
// FIXME this parameter could just be a match filter
Filter: r.Form.Get("filter"),
All: toBool(r.Form.Get("all")),
}
images, err := s.daemon.Repositories().Images(&imagesConfig)
if err != nil {
return err
}
if version.GreaterThanOrEqualTo("1.7") {
return writeJSON(w, http.StatusOK, images)
}
legacyImages := []types.LegacyImage{}
for _, image := range images {
for _, repoTag := range image.RepoTags {
repo, tag := parsers.ParseRepositoryTag(repoTag)
legacyImage := types.LegacyImage{
Repository: repo,
Tag: tag,
ID: image.ID,
Created: image.Created,
Size: image.Size,
VirtualSize: image.VirtualSize,
}
legacyImages = append(legacyImages, legacyImage)
}
}
return writeJSON(w, http.StatusOK, legacyImages)
}
func (s *Server) getImagesViz(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if version.GreaterThan("1.6") {
w.WriteHeader(http.StatusNotFound)
return fmt.Errorf("This is now implemented in the client.")
}
eng.ServeHTTP(w, r)
return nil
}
func (s *Server) getInfo(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
w.Header().Set("Content-Type", "application/json")
info, err := s.daemon.SystemInfo()
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, info)
}
func (s *Server) getEvents(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var since int64 = -1
if r.Form.Get("since") != "" {
s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
if err != nil {
return err
}
since = s
}
var until int64 = -1
if r.Form.Get("until") != "" {
u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
if err != nil {
return err
}
until = u
}
timer := time.NewTimer(0)
timer.Stop()
if until > 0 {
dur := time.Unix(until, 0).Sub(time.Now())
timer = time.NewTimer(dur)
}
ef, err := filters.FromParam(r.Form.Get("filters"))
if err != nil {
return err
}
isFiltered := func(field string, filter []string) bool {
if len(filter) == 0 {
return false
}
for _, v := range filter {
if v == field {
return false
}
if strings.Contains(field, ":") {
image := strings.Split(field, ":")
if image[0] == v {
return false
}
}
}
return true
}
d := s.daemon
es := d.EventsService
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(utils.NewWriteFlusher(w))
getContainerId := func(cn string) string {
c, err := d.Get(cn)
if err != nil {
return ""
}
return c.ID
}
sendEvent := func(ev *jsonmessage.JSONMessage) error {
//incoming container filter can be name,id or partial id, convert and replace as a full container id
for i, cn := range ef["container"] {
ef["container"][i] = getContainerId(cn)
}
if isFiltered(ev.Status, ef["event"]) || isFiltered(ev.From, ef["image"]) ||
isFiltered(ev.ID, ef["container"]) {
return nil
}
return enc.Encode(ev)
}
current, l := es.Subscribe()
defer es.Evict(l)
for _, ev := range current {
if ev.Time < since {
continue
}
if err := sendEvent(ev); err != nil {
return err
}
}
for {
select {
case ev := <-l:
jev, ok := ev.(*jsonmessage.JSONMessage)
if !ok {
continue
}
if err := sendEvent(jev); err != nil {
return err
}
case <-timer.C:
return nil
}
}
}
func (s *Server) getImagesHistory(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
history, err := s.daemon.Repositories().History(name)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, history)
}
func (s *Server) getContainersChanges(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
cont, err := s.daemon.Get(name)
if err != nil {
return err
}
changes, err := cont.Changes()
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, changes)
}
func (s *Server) getContainersTop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if version.LessThan("1.4") {
return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args"))
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, procList)
}
func (s *Server) getContainersJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
config := &daemon.ContainersConfig{
All: toBool(r.Form.Get("all")),
Size: toBool(r.Form.Get("size")),
Since: r.Form.Get("since"),
Before: r.Form.Get("before"),
Filters: r.Form.Get("filters"),
}
if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
limit, err := strconv.Atoi(tmpLimit)
if err != nil {
return err
}
config.Limit = limit
}
containers, err := s.daemon.Containers(config)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, containers)
}
func (s *Server) getContainersStats(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
return s.daemon.ContainerStats(vars["name"], utils.NewWriteFlusher(w))
}
func (s *Server) getContainersLogs(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
// Validate args here, because we can't return not StatusOK after job.Run() call
stdout, stderr := toBool(r.Form.Get("stdout")), toBool(r.Form.Get("stderr"))
if !(stdout || stderr) {
return fmt.Errorf("Bad parameters: you must choose at least one stream")
}
logsConfig := &daemon.ContainerLogsConfig{
Follow: toBool(r.Form.Get("follow")),
Timestamps: toBool(r.Form.Get("timestamps")),
Tail: r.Form.Get("tail"),
UseStdout: stdout,
UseStderr: stderr,
OutStream: utils.NewWriteFlusher(w),
}
if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil {
fmt.Fprintf(w, "Error running logs job: %s\n", err)
}
return nil
}
func (s *Server) postImagesTag(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
repo := r.Form.Get("repo")
tag := r.Form.Get("tag")
force := toBool(r.Form.Get("force"))
if err := s.daemon.Repositories().Tag(repo, tag, vars["name"], force); err != nil {
return err
}
w.WriteHeader(http.StatusCreated)
return nil
}
func (s *Server) postCommit(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if err := checkForJson(r); err != nil {
return err
}
cont := r.Form.Get("container")
pause := toBool(r.Form.Get("pause"))
if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
pause = true
}
containerCommitConfig := &daemon.ContainerCommitConfig{
Pause: pause,
Repo: r.Form.Get("repo"),
Tag: r.Form.Get("tag"),
Author: r.Form.Get("author"),
Comment: r.Form.Get("comment"),
Changes: r.Form["changes"],
Config: r.Body,
}
imgID, err := s.daemon.ContainerCommit(cont, containerCommitConfig)
if err != nil {
return err
}
return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
ID: imgID,
})
}
// Creates an image from Pull or from Import
func (s *Server) postImagesCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
image = r.Form.Get("fromImage")
repo = r.Form.Get("repo")
tag = r.Form.Get("tag")
)
authEncoded := r.Header.Get("X-Registry-Auth")
authConfig := ®istry.AuthConfig{}
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = ®istry.AuthConfig{}
}
}
if image != "" { //pull
if tag == "" {
image, tag = parsers.ParseRepositoryTag(image)
}
metaHeaders := map[string][]string{}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
imagePullConfig := &graph.ImagePullConfig{
Parallel: version.GreaterThan("1.3"),
MetaHeaders: metaHeaders,
AuthConfig: authConfig,
OutStream: utils.NewWriteFlusher(w),
}
if version.GreaterThan("1.0") {
imagePullConfig.Json = true
w.Header().Set("Content-Type", "application/json")
} else {
imagePullConfig.Json = false
}
if err := s.daemon.Repositories().Pull(image, tag, imagePullConfig, eng); err != nil {
return err
}
} else { //import
if tag == "" {
repo, tag = parsers.ParseRepositoryTag(repo)
}
src := r.Form.Get("fromSrc")
imageImportConfig := &graph.ImageImportConfig{
Changes: r.Form["changes"],
InConfig: r.Body,
OutStream: utils.NewWriteFlusher(w),
}
if version.GreaterThan("1.0") {
imageImportConfig.Json = true
w.Header().Set("Content-Type", "application/json")
} else {
imageImportConfig.Json = false
}
if err := s.daemon.Repositories().Import(src, repo, tag, imageImportConfig, eng); err != nil {
return err
}
}
return nil
}
func (s *Server) getImagesSearch(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
config *registry.AuthConfig
authEncoded = r.Header.Get("X-Registry-Auth")
headers = map[string][]string{}
)
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(&config); err != nil {
// for a search it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
config = ®istry.AuthConfig{}
}
}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
headers[k] = v
}
}
query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(query.Results)
}
func (s *Server) postImagesPush(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
metaHeaders := map[string][]string{}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
if err := parseForm(r); err != nil {
return err
}
authConfig := ®istry.AuthConfig{}
authEncoded := r.Header.Get("X-Registry-Auth")
if authEncoded != "" {
// the new format is to handle the authConfig as a header
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// to increase compatibility to existing api it is defaulting to be empty
authConfig = ®istry.AuthConfig{}
}
} else {
// the old format is supported for compatibility if there was no authConfig header
if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
}
}
job := eng.Job("push", vars["name"])
job.SetenvJson("metaHeaders", metaHeaders)
job.SetenvJson("authConfig", authConfig)
job.Setenv("tag", r.Form.Get("tag"))
if version.GreaterThan("1.0") {
job.SetenvBool("json", true)
streamJSON(job, w, true)
} else {
job.Stdout.Add(utils.NewWriteFlusher(w))
}
if err := job.Run(); err != nil {
if !job.Stdout.Used() {
return err
}
sf := streamformatter.NewStreamFormatter(version.GreaterThan("1.0"))
w.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) getImagesGet(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
if version.GreaterThan("1.0") {
w.Header().Set("Content-Type", "application/x-tar")
}
var job *engine.Job
if name, ok := vars["name"]; ok {
job = eng.Job("image_export", name)
} else {
job = eng.Job("image_export", r.Form["names"]...)
}
job.Stdout.Add(w)
return job.Run()
}
func (s *Server) postImagesLoad(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
job := eng.Job("load")
job.Stdin.Add(r.Body)
job.Stdout.Add(w)
return job.Run()
}
func (s *Server) postContainersCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return nil
}
if err := checkForJson(r); err != nil {
return err
}
var (
warnings []string
name = r.Form.Get("name")
)
config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
if err != nil {
return err
}
containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
if err != nil {
return err
}
return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
ID: containerId,
Warnings: warnings,
})
}
func (s *Server) postContainersRestart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
timeout, err := strconv.Atoi(r.Form.Get("t"))
if err != nil {
return err
}
if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainerRename(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
newName := r.Form.Get("name")
if err := s.daemon.ContainerRename(name, newName); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) deleteContainers(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
config := &daemon.ContainerRmConfig{
ForceRemove: toBool(r.Form.Get("force")),
RemoveVolume: toBool(r.Form.Get("v")),
RemoveLink: toBool(r.Form.Get("link")),
}
if err := s.daemon.ContainerRm(name, config); err != nil {
// Force a 404 for the empty string
if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
return fmt.Errorf("no such id: \"\"")
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) deleteImages(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
force := toBool(r.Form.Get("force"))
noprune := toBool(r.Form.Get("noprune"))
list, err := s.daemon.ImageDelete(name, force, noprune)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, list)
}
func (s *Server) postContainersStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
// If contentLength is -1, we can assumed chunked encoding
// or more technically that the length is unknown
// https://golang.org/src/pkg/net/http/request.go#L139
// net/http otherwise seems to swallow any headers related to chunked encoding
// including r.TransferEncoding
// allow a nil body for backwards compatibility
var hostConfig *runconfig.HostConfig
if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
if err := checkForJson(r); err != nil {
return err
}
c, err := runconfig.DecodeHostConfig(r.Body)
if err != nil {
return err
}
hostConfig = c
}
if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
if err.Error() == "Container already started" {
w.WriteHeader(http.StatusNotModified)
return nil
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersStop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
seconds, err := strconv.Atoi(r.Form.Get("t"))
if err != nil {
return err
}
if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
if err.Error() == "Container already stopped" {
w.WriteHeader(http.StatusNotModified)
return nil
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersWait(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
cont, err := s.daemon.Get(name)
if err != nil {
return err
}
status, _ := cont.WaitStop(-1 * time.Second)
return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
StatusCode: status,
})
}
func (s *Server) postContainersResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
height, err := strconv.Atoi(r.Form.Get("h"))
if err != nil {
return err
}
width, err := strconv.Atoi(r.Form.Get("w"))
if err != nil {
return err
}
cont, err := s.daemon.Get(vars["name"])
if err != nil {
return err
}
return cont.Resize(height, width)
}
func (s *Server) postContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
cont, err := s.daemon.Get(vars["name"])
if err != nil {
return err
}
inStream, outStream, err := hijackServer(w)
if err != nil {
return err
}
defer closeStreams(inStream, outStream)
var errStream io.Writer
if _, ok := r.Header["Upgrade"]; ok {
fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
} else {
fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
}
if !cont.Config.Tty && version.GreaterThanOrEqualTo("1.6") {
errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
} else {
errStream = outStream
}
logs := toBool(r.Form.Get("logs"))
stream := toBool(r.Form.Get("stream"))
var stdin io.ReadCloser
var stdout, stderr io.Writer
if toBool(r.Form.Get("stdin")) {
stdin = inStream
}
if toBool(r.Form.Get("stdout")) {
stdout = outStream
}
if toBool(r.Form.Get("stderr")) {
stderr = errStream
}
if err := cont.AttachWithLogs(stdin, stdout, stderr, logs, stream); err != nil {
fmt.Fprintf(outStream, "Error attaching: %s\n", err)
}
return nil
}
func (s *Server) wsContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
cont, err := s.daemon.Get(vars["name"])
if err != nil {
return err
}
h := websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
logs := r.Form.Get("logs") != ""
stream := r.Form.Get("stream") != ""
if err := cont.AttachWithLogs(ws, ws, ws, logs, stream); err != nil {
logrus.Errorf("Error attaching websocket: %s", err)
}
})
h.ServeHTTP(w, r)
return nil
}
func (s *Server) getContainersByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
var job = eng.Job("container_inspect", vars["name"])
if version.LessThan("1.12") {
job.SetenvBool("raw", true)
}
streamJSON(job, w, false)
return job.Run()
}
func (s *Server) getExecByID(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter 'id'")
}
eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, eConfig)
}
func (s *Server) getImagesByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
var job = eng.Job("image_inspect", vars["name"])
if version.LessThan("1.12") {
job.SetenvBool("raw", true)
}
streamJSON(job, w, false)
return job.Run()
}
func (s *Server) postBuild(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if version.LessThan("1.3") {
return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
}
var (
authEncoded = r.Header.Get("X-Registry-Auth")
authConfig = ®istry.AuthConfig{}
configFileEncoded = r.Header.Get("X-Registry-Config")
configFile = ®istry.ConfigFile{}
job = eng.Job("build")
)
// This block can be removed when API versions prior to 1.9 are deprecated.
// Both headers will be parsed and sent along to the daemon, but if a non-empty
// ConfigFile is present, any value provided as an AuthConfig directly will
// be overridden. See BuildFile::CmdFrom for details.
if version.LessThan("1.9") && authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = ®istry.AuthConfig{}
}
}
if configFileEncoded != "" {
configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
configFile = ®istry.ConfigFile{}
}
}
if version.GreaterThanOrEqualTo("1.8") {
job.SetenvBool("json", true)
streamJSON(job, w, true)
} else {
job.Stdout.Add(utils.NewWriteFlusher(w))
}
if toBool(r.FormValue("forcerm")) && version.GreaterThanOrEqualTo("1.12") {
job.Setenv("rm", "1")
} else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
job.Setenv("rm", "1")
} else {
job.Setenv("rm", r.FormValue("rm"))
}
if toBool(r.FormValue("pull")) && version.GreaterThanOrEqualTo("1.16") {
job.Setenv("pull", "1")
}
job.Stdin.Add(r.Body)
job.Setenv("remote", r.FormValue("remote"))
job.Setenv("dockerfile", r.FormValue("dockerfile"))
job.Setenv("t", r.FormValue("t"))
job.Setenv("q", r.FormValue("q"))
job.Setenv("nocache", r.FormValue("nocache"))
job.Setenv("forcerm", r.FormValue("forcerm"))
job.SetenvJson("authConfig", authConfig)
job.SetenvJson("configFile", configFile)
job.Setenv("memswap", r.FormValue("memswap"))
job.Setenv("memory", r.FormValue("memory"))
job.Setenv("cpusetcpus", r.FormValue("cpusetcpus"))
job.Setenv("cpusetmems", r.FormValue("cpusetmems"))
job.Setenv("cpushares", r.FormValue("cpushares"))
// Job cancellation. Note: not all job types support this.
if closeNotifier, ok := w.(http.CloseNotifier); ok {
finished := make(chan struct{})
defer close(finished)
go func() {
select {
case <-finished:
case <-closeNotifier.CloseNotify():
logrus.Infof("Client disconnected, cancelling job: %s", job.Name)
job.Cancel()
}
}()
}
if err := job.Run(); err != nil {
if !job.Stdout.Used() {
return err
}
sf := streamformatter.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
w.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) postContainersCopy(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := checkForJson(r); err != nil {
return err
}
cfg := types.CopyConfig{}
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
return err
}
if cfg.Resource == "" {
return fmt.Errorf("Path cannot be empty")
}
res := cfg.Resource
if res[0] == '/' {
res = res[1:]
}
cont, err := s.daemon.Get(vars["name"])
if err != nil {
logrus.Errorf("%v", err)
if strings.Contains(strings.ToLower(err.Error()), "no such id") {
w.WriteHeader(http.StatusNotFound)
return nil
}
}
data, err := cont.Copy(res)
if err != nil {
logrus.Errorf("%v", err)
if os.IsNotExist(err) {
return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
}
return err
}
defer data.Close()
w.Header().Set("Content-Type", "application/x-tar")
if _, err := io.Copy(w, data); err != nil {
return err
}
return nil
}
func (s *Server) postContainerExecCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return nil
}
var (
name = vars["name"]
job = eng.Job("execCreate", name)
stdoutBuffer = bytes.NewBuffer(nil)
outWarnings []string
warnings = bytes.NewBuffer(nil)
)
if err := job.DecodeEnv(r.Body); err != nil {
return err
}
job.Stdout.Add(stdoutBuffer)
// Read warnings from stderr
job.Stderr.Add(warnings)
// Register an instance of Exec in container.
if err := job.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error setting up exec command in container %s: %s\n", name, err)
return err
}
// Parse warnings from stderr
scanner := bufio.NewScanner(warnings)
for scanner.Scan() {
outWarnings = append(outWarnings, scanner.Text())
}
return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
ID: engine.Tail(stdoutBuffer, 1),
Warnings: outWarnings,
})
}
// TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
func (s *Server) postContainerExecStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return nil
}
var (
name = vars["name"]
job = eng.Job("execStart", name)
errOut io.Writer = os.Stderr
)
if err := job.DecodeEnv(r.Body); err != nil {
return err
}
if !job.GetenvBool("Detach") {
// Setting up the streaming http interface.
inStream, outStream, err := hijackServer(w)
if err != nil {
return err
}
defer closeStreams(inStream, outStream)
var errStream io.Writer
if _, ok := r.Header["Upgrade"]; ok {
fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
} else {
fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
}
if !job.GetenvBool("Tty") && version.GreaterThanOrEqualTo("1.6") {
errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
} else {
errStream = outStream
}
job.Stdin.Add(inStream)
job.Stdout.Add(outStream)
job.Stderr.Set(errStream)
errOut = outStream
}
// Now run the user process in container.
job.SetCloseIO(false)
if err := job.Run(); err != nil {
fmt.Fprintf(errOut, "Error starting exec command in container %s: %s\n", name, err)
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainerExecResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
height, err := strconv.Atoi(r.Form.Get("h"))
if err != nil {
return err
}
width, err := strconv.Atoi(r.Form.Get("w"))
if err != nil {
return err
}
return s.daemon.ContainerExecResize(vars["name"], height, width)
}
func (s *Server) optionsHandler(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
w.WriteHeader(http.StatusOK)
return nil
}
func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
}
func (s *Server) ping(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
_, err := w.Write([]byte{'O', 'K'})
return err
}
func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// log the request
logrus.Debugf("Calling %s %s", localMethod, localRoute)
if logging {
logrus.Infof("%s %s", r.Method, r.RequestURI)
}
if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
}
}
version := version.Version(mux.Vars(r)["version"])
if version == "" {
version = api.APIVERSION
}
if corsHeaders != "" {
writeCorsHeaders(w, r, corsHeaders)
}
if version.GreaterThan(api.APIVERSION) {
http.Error(w, fmt.Errorf("client and server don't have same version (client API version: %s, server API version: %s)", version, api.APIVERSION).Error(), http.StatusNotFound)
return
}
if err := handlerFunc(eng, version, w, r, mux.Vars(r)); err != nil {
logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
httpError(w, err)
}
}
}
// we keep enableCors just for legacy usage, need to be removed in the future
func createRouter(s *Server, eng *engine.Engine) *mux.Router {
r := mux.NewRouter()
if os.Getenv("DEBUG") != "" {
ProfilerSetup(r, "/debug/")
}
m := map[string]map[string]HttpApiFunc{
"GET": {
"/_ping": s.ping,
"/events": s.getEvents,
"/info": s.getInfo,
"/version": s.getVersion,
"/images/json": s.getImagesJSON,
"/images/viz": s.getImagesViz,
"/images/search": s.getImagesSearch,
"/images/get": s.getImagesGet,
"/images/{name:.*}/get": s.getImagesGet,
"/images/{name:.*}/history": s.getImagesHistory,
"/images/{name:.*}/json": s.getImagesByName,
"/containers/ps": s.getContainersJSON,
"/containers/json": s.getContainersJSON,
"/containers/{name:.*}/export": s.getContainersExport,
"/containers/{name:.*}/changes": s.getContainersChanges,
"/containers/{name:.*}/json": s.getContainersByName,
"/containers/{name:.*}/top": s.getContainersTop,
"/containers/{name:.*}/logs": s.getContainersLogs,
"/containers/{name:.*}/stats": s.getContainersStats,
"/containers/{name:.*}/attach/ws": s.wsContainersAttach,
"/exec/{id:.*}/json": s.getExecByID,
},
"POST": {
"/auth": s.postAuth,
"/commit": s.postCommit,
"/build": s.postBuild,
"/images/create": s.postImagesCreate,
"/images/load": s.postImagesLoad,
"/images/{name:.*}/push": s.postImagesPush,
"/images/{name:.*}/tag": s.postImagesTag,
"/containers/create": s.postContainersCreate,
"/containers/{name:.*}/kill": s.postContainersKill,
"/containers/{name:.*}/pause": s.postContainersPause,
"/containers/{name:.*}/unpause": s.postContainersUnpause,
"/containers/{name:.*}/restart": s.postContainersRestart,
"/containers/{name:.*}/start": s.postContainersStart,
"/containers/{name:.*}/stop": s.postContainersStop,
"/containers/{name:.*}/wait": s.postContainersWait,
"/containers/{name:.*}/resize": s.postContainersResize,
"/containers/{name:.*}/attach": s.postContainersAttach,
"/containers/{name:.*}/copy": s.postContainersCopy,
"/containers/{name:.*}/exec": s.postContainerExecCreate,
"/exec/{name:.*}/start": s.postContainerExecStart,
"/exec/{name:.*}/resize": s.postContainerExecResize,
"/containers/{name:.*}/rename": s.postContainerRename,
},
"DELETE": {
"/containers/{name:.*}": s.deleteContainers,
"/images/{name:.*}": s.deleteImages,
},
"OPTIONS": {
"": s.optionsHandler,
},
}
// If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
// otherwise, all head values will be passed to HTTP handler
corsHeaders := s.cfg.CorsHeaders
if corsHeaders == "" && s.cfg.EnableCors {
corsHeaders = "*"
}
for method, routes := range m {
for route, fct := range routes {
logrus.Debugf("Registering %s, %s", method, route)
// NOTE: scope issue, make sure the variables are local and won't be changed
localRoute := route
localFct := fct
localMethod := method
// build the handler function
f := makeHttpHandler(eng, s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
// add the new route
if localRoute == "" {
r.Methods(localMethod).HandlerFunc(f)
} else {
r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
}
}
}
return r
}
// ServeRequest processes a single http request to the docker remote api.
// FIXME: refactor this to be part of Server and not require re-creating a new
// router each time. This requires first moving ListenAndServe into Server.
func ServeRequest(eng *engine.Engine, apiversion version.Version, w http.ResponseWriter, req *http.Request) {
cfg := &ServerConfig{
EnableCors: true,
Version: string(apiversion),
}
api := New(cfg, eng)
daemon, _ := eng.HackGetGlobalVar("httpapi.daemon").(*daemon.Daemon)
api.AcceptConnections(daemon)
router := createRouter(api, eng)
// Insert APIVERSION into the request as a convenience
req.URL.Path = fmt.Sprintf("/v%s%s", apiversion, req.URL.Path)
router.ServeHTTP(w, req)
}
func allocateDaemonPort(addr string) error {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return err
}
intPort, err := strconv.Atoi(port)
if err != nil {
return err
}
var hostIPs []net.IP
if parsedIP := net.ParseIP(host); parsedIP != nil {
hostIPs = append(hostIPs, parsedIP)
} else if hostIPs, err = net.LookupIP(host); err != nil {
return fmt.Errorf("failed to lookup %s address in host specification", host)
}
for _, hostIP := range hostIPs {
if _, err := bridge.RequestPort(hostIP, "tcp", intPort); err != nil {
return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err)
}
}
return nil
}
func toBool(s string) bool {
s = strings.ToLower(strings.TrimSpace(s))
return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none")
}
| {
"content_hash": "78e5f74ce5e8fecbab20b9041f5a569e",
"timestamp": "",
"source": "github",
"line_count": 1678,
"max_line_length": 188,
"avg_line_length": 28.341477949940405,
"alnum_prop": 0.6699749773955463,
"repo_name": "sergeyevstifeev/docker",
"id": "50dc84ff7ff4679780c2749220a2906e37769e40",
"size": "47557",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/server/server.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2479182"
},
{
"name": "Makefile",
"bytes": "4547"
},
{
"name": "Perl",
"bytes": "2199"
},
{
"name": "Shell",
"bytes": "184676"
},
{
"name": "VimL",
"bytes": "683"
}
],
"symlink_target": ""
} |
.class public final Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.super Ljava/lang/Object;
.source "MediaDescriptionCompat.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/support/v4/media/MediaDescriptionCompat;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x19
name = "Builder"
.end annotation
# instance fields
.field private mDescription:Ljava/lang/CharSequence;
.field private mExtras:Landroid/os/Bundle;
.field private mIcon:Landroid/graphics/Bitmap;
.field private mIconUri:Landroid/net/Uri;
.field private mMediaId:Ljava/lang/String;
.field private mMediaUri:Landroid/net/Uri;
.field private mSubtitle:Ljava/lang/CharSequence;
.field private mTitle:Ljava/lang/CharSequence;
# direct methods
.method public constructor <init>()V
.registers 1
.prologue
.line 296
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 297
return-void
.end method
# virtual methods
.method public build()Landroid/support/v4/media/MediaDescriptionCompat;
.registers 11
.prologue
.line 397
new-instance v0, Landroid/support/v4/media/MediaDescriptionCompat;
iget-object v1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mMediaId:Ljava/lang/String;
iget-object v2, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mTitle:Ljava/lang/CharSequence;
iget-object v3, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mSubtitle:Ljava/lang/CharSequence;
iget-object v4, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mDescription:Ljava/lang/CharSequence;
iget-object v5, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mIcon:Landroid/graphics/Bitmap;
iget-object v6, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mIconUri:Landroid/net/Uri;
iget-object v7, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mExtras:Landroid/os/Bundle;
iget-object v8, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mMediaUri:Landroid/net/Uri;
const/4 v9, 0x0
invoke-direct/range {v0 .. v9}, Landroid/support/v4/media/MediaDescriptionCompat;-><init>(Ljava/lang/String;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/graphics/Bitmap;Landroid/net/Uri;Landroid/os/Bundle;Landroid/net/Uri;Landroid/support/v4/media/MediaDescriptionCompat$1;)V
return-object v0
.end method
.method public setDescription(Ljava/lang/CharSequence;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "description" # Ljava/lang/CharSequence;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 340
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mDescription:Ljava/lang/CharSequence;
.line 341
return-object p0
.end method
.method public setExtras(Landroid/os/Bundle;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "extras" # Landroid/os/Bundle;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 375
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mExtras:Landroid/os/Bundle;
.line 376
return-object p0
.end method
.method public setIconBitmap(Landroid/graphics/Bitmap;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "icon" # Landroid/graphics/Bitmap;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 352
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mIcon:Landroid/graphics/Bitmap;
.line 353
return-object p0
.end method
.method public setIconUri(Landroid/net/Uri;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "iconUri" # Landroid/net/Uri;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 364
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mIconUri:Landroid/net/Uri;
.line 365
return-object p0
.end method
.method public setMediaId(Ljava/lang/String;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "mediaId" # Ljava/lang/String;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 306
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mMediaId:Ljava/lang/String;
.line 307
return-object p0
.end method
.method public setMediaUri(Landroid/net/Uri;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "mediaUri" # Landroid/net/Uri;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 386
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mMediaUri:Landroid/net/Uri;
.line 387
return-object p0
.end method
.method public setSubtitle(Ljava/lang/CharSequence;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "subtitle" # Ljava/lang/CharSequence;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 328
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mSubtitle:Ljava/lang/CharSequence;
.line 329
return-object p0
.end method
.method public setTitle(Ljava/lang/CharSequence;)Landroid/support/v4/media/MediaDescriptionCompat$Builder;
.registers 2
.param p1, "title" # Ljava/lang/CharSequence;
.annotation build Landroid/support/annotation/Nullable;
.end annotation
.end param
.prologue
.line 317
iput-object p1, p0, Landroid/support/v4/media/MediaDescriptionCompat$Builder;->mTitle:Ljava/lang/CharSequence;
.line 318
return-object p0
.end method
| {
"content_hash": "e12be736526ae71b3d3abd06a385d63b",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 315,
"avg_line_length": 31.79187817258883,
"alnum_prop": 0.7430943637234552,
"repo_name": "shenxdtw/PokemonGo-Plugin",
"id": "d7af0186f70476977653618993ff3368b07bd0df",
"size": "6263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PokemonGo_Smali/android/support/v4/media/MediaDescriptionCompat$Builder.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Smali",
"bytes": "35925787"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("SimpleDB1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Blacksmith Projects")]
[assembly: AssemblyProduct("SimpleDB1")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("f19fa47e-9e0f-472e-9a31-d40b2b2d4f04")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los números de compilación y de revisión predeterminados
// mediante el carácter "*", como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "7d13a69af4cb2e2cd774d58007362b42",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 102,
"avg_line_length": 42.27777777777778,
"alnum_prop": 0.7588699080157687,
"repo_name": "hossmi/qtfkdata",
"id": "e7bc70ceb85269218eef0f6938ac3283216a80e1",
"size": "1540",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Tests/SimpleDB1/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "98951"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\video_embed_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
/**
* Plugin implementation of the video_embed_field field type.
*
* @FieldType(
* id = "video_embed_field",
* label = @Translation("Video Embed"),
* description = @Translation("Stores a video and then outputs some embed code."),
* category = @Translation("Media"),
* default_widget = "video_embed_field_textfield",
* default_formatter = "video_embed_field_video",
* constraints = {"VideoEmbedValidation" = {}}
* )
*/
class VideoEmbedField extends FieldItemBase {
/**
* The embed provider plugin manager.
*
* @var \Drupal\video_embed_field\ProviderManagerInterface
*/
protected $providerManager;
/**
* {@inheritdoc}
*/
public function __construct($definition, $name = NULL, TraversableTypedDataInterface $parent = NULL, $provider_manager = NULL) {
parent::__construct($definition, $name, $parent);
$this->providerManager = $provider_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance($definition, $name = NULL, TraversableTypedDataInterface $parent = NULL) {
$provider_manager = \Drupal::service('video_embed_field.provider_manager');
return new static($definition, $name, $parent, $provider_manager);
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar',
'length' => 256,
],
],
];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(t('Video url'))
->setRequired(TRUE);
return $properties;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$value = $this->get('value')->getValue();
return empty($value);
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$form = [];
$form['allowed_providers'] = [
'#title' => $this->t('Allowed Providers'),
'#description' => $this->t('Restrict users from entering information from the following providers. If none are selected any video provider can be used.'),
'#type' => 'checkboxes',
'#default_value' => $this->getSetting('allowed_providers'),
'#options' => $this->providerManager->getProvidersOptionList(),
];
return $form;
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return [
'allowed_providers' => [],
];
}
}
| {
"content_hash": "31bef0e91b36ca56af4c61a0fed2700e",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 160,
"avg_line_length": 27.62857142857143,
"alnum_prop": 0.6483971044467425,
"repo_name": "rlnorthcutt/acquia-cd-demo",
"id": "48b1b541731b25dc41667fa30883e2c0ac0ac7d5",
"size": "2901",
"binary": false,
"copies": "36",
"ref": "refs/heads/master",
"path": "docroot/modules/contrib/video_embed_field/src/Plugin/Field/FieldType/VideoEmbedField.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "593326"
},
{
"name": "Gherkin",
"bytes": "47803"
},
{
"name": "HTML",
"bytes": "725686"
},
{
"name": "JavaScript",
"bytes": "1153521"
},
{
"name": "Makefile",
"bytes": "3570"
},
{
"name": "PHP",
"bytes": "40105732"
},
{
"name": "Ruby",
"bytes": "910"
},
{
"name": "Shell",
"bytes": "58234"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>vue-admin</title>
</head>
<body>
<div id="app"></div>
<script src="/static/tinymce/tinymce.min.js"></script>
<!-- built files will be auto injected -->
</body>
</html>
| {
"content_hash": "6a30c2b4d7eb9d1fd64bc9c0d1e601a5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 110,
"avg_line_length": 28.23076923076923,
"alnum_prop": 0.6185286103542235,
"repo_name": "lc8882972/HuiTong",
"id": "1f2e33be7fa9cf8cac7b9164756ef6c005d7c702",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Admin/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "50113"
},
{
"name": "CSS",
"bytes": "9686"
},
{
"name": "HTML",
"bytes": "1163"
},
{
"name": "JavaScript",
"bytes": "50615"
},
{
"name": "Shell",
"bytes": "4487"
},
{
"name": "Vue",
"bytes": "40241"
}
],
"symlink_target": ""
} |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/test_file_util.h"
#include <vector>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
constexpr FilePath::CharType kDirPrefix[] =
FILE_PATH_LITERAL("test_scoped_temp_dir");
// Deletes all registered file paths upon test completion. There can only be
// one instance at a time.
class PathDeleterOnTestEnd : public testing::EmptyTestEventListener {
public:
PathDeleterOnTestEnd() {
DCHECK(!instance_);
instance_ = this;
}
~PathDeleterOnTestEnd() override {
DCHECK_EQ(instance_, this);
instance_ = nullptr;
}
PathDeleterOnTestEnd(const PathDeleterOnTestEnd&) = delete;
PathDeleterOnTestEnd& operator=(const PathDeleterOnTestEnd&) = delete;
static PathDeleterOnTestEnd* GetInstance() { return instance_; }
void DeletePathRecursivelyUponTestEnd(const FilePath& path) {
file_paths_to_delete_.push_back(path);
}
// EmptyTestEventListener overrides.
void OnTestEnd(const testing::TestInfo& test_info) override {
if (file_paths_to_delete_.empty()) {
// Nothing to delete since the last test ended.
return;
}
ScopedAllowBlockingForTesting allow_blocking;
for (const FilePath& file_path : file_paths_to_delete_) {
if (!DieFileDie(file_path, /*recurse=*/true)) {
ADD_FAILURE() << "Failed to delete temporary directory for testing: "
<< file_path;
}
}
file_paths_to_delete_.clear();
}
private:
static PathDeleterOnTestEnd* instance_;
std::vector<FilePath> file_paths_to_delete_;
};
// static
PathDeleterOnTestEnd* PathDeleterOnTestEnd::instance_ = nullptr;
} // namespace
bool EvictFileFromSystemCacheWithRetry(const FilePath& path) {
const int kCycles = 10;
const TimeDelta kDelay = TestTimeouts::action_timeout() / kCycles;
for (int i = 0; i < kCycles; i++) {
if (EvictFileFromSystemCache(path))
return true;
PlatformThread::Sleep(kDelay);
}
return false;
}
FilePath CreateUniqueTempDirectoryScopedToTest() {
ScopedAllowBlockingForTesting allow_blocking;
FilePath path;
if (!CreateNewTempDirectory(kDirPrefix, &path)) {
ADD_FAILURE() << "Failed to create unique temporary directory for testing.";
return FilePath();
}
if (!PathDeleterOnTestEnd::GetInstance()) {
// Append() transfers ownership of the listener. This means
// PathDeleterOnTestEnd::GetInstance() will return non-null until all tests
// are run and the test suite destroyed.
testing::UnitTest::GetInstance()->listeners().Append(
new PathDeleterOnTestEnd());
DCHECK(PathDeleterOnTestEnd::GetInstance());
}
PathDeleterOnTestEnd::GetInstance()->DeletePathRecursivelyUponTestEnd(path);
return path;
}
} // namespace base
| {
"content_hash": "1009ccce4b2cdd5b3e22155810b1a0f0",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 80,
"avg_line_length": 29.132075471698112,
"alnum_prop": 0.7114637305699482,
"repo_name": "nwjs/chromium.src",
"id": "834b6668a8012d292d272ec48d3d9ce468230b4b",
"size": "3088",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "base/test/test_file_util.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import Render from './core/render';
import Interpolate from './objects/interpolate';
import Objects from './objects/objectsBase';
import Util from './objects/util';
import Easing from './easing/easing-base';
import Internals from './core/internals';
import Selector from './util/selector';
// Animation
import Animation from './animation/animationBase';
// Base Components
import Components from './objects/componentsBase';
// TweenConstructor
import Tween from './tween/tweenBase';
// Interface only fromTo
import fromTo from './interface/fromTo';
import Version from './util/version';
export default {
Animation,
Components,
Tween,
fromTo,
Objects,
Easing,
Util,
Render,
Interpolate,
Internals,
Selector,
Version,
};
| {
"content_hash": "f2aa66ea0f2a1d7c9cca8d9a9a72f54c",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 50,
"avg_line_length": 20.805555555555557,
"alnum_prop": 0.7316421895861148,
"repo_name": "thednp/kute.js",
"id": "dde2f09e172d48b6b795f07cd0e3c420492f9378",
"size": "749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index-base.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "206733"
},
{
"name": "TypeScript",
"bytes": "8529"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Ao3TrackReader.Helper
{
[Flags]
public enum WorkDetailsFlags
{
SavedLoc = 1,
InReadingList = 2,
All = SavedLoc | InReadingList
}
public interface IWorkDetails
{
IWorkChapter savedLoc { get; set; }
bool? inReadingList { get; set; }
}
public sealed class WorkDetails : IWorkDetails
{
public IWorkChapter savedLoc { get; set; }
public bool? inReadingList { get; set; }
}
}
| {
"content_hash": "52501c80a5591579b7f42adcde042256",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 50,
"avg_line_length": 19.607142857142858,
"alnum_prop": 0.6174863387978142,
"repo_name": "wench/Ao3-Tracker",
"id": "b118def83d8c78b3670afc971502844cdf25a3e2",
"size": "1108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ao3TrackReader/Ao3TrackReader.Helper/WorkDetails.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "C#",
"bytes": "1075657"
},
{
"name": "CSS",
"bytes": "5782"
},
{
"name": "HTML",
"bytes": "27750"
},
{
"name": "JavaScript",
"bytes": "915110"
},
{
"name": "PowerShell",
"bytes": "428"
},
{
"name": "TypeScript",
"bytes": "200829"
}
],
"symlink_target": ""
} |
// bslstl_string.t.cpp -*-C++-*-
#include <bslstl_string.h>
#include <bslstl_allocator.h>
#include <bslstl_forwarditerator.h>
#include <bslstl_stringrefdata.h>
#include <bslma_allocator.h> // for testing only
#include <bslma_default.h> // for testing only
#include <bslma_defaultallocatorguard.h> // for testing only
#include <bslma_newdeleteallocator.h> // for testing only
#include <bslma_testallocator.h> // for testing only
#include <bslma_testallocatorexception.h> // for testing only
#include <bslmf_issame.h> // for testing only
#include <bsls_alignmentutil.h> // for testing only
#include <bsls_platform.h>
#include <bsls_types.h> // for testing only
#include <bsls_objectbuffer.h>
#include <bsls_stopwatch.h>
#include <bsls_assert.h>
#include <bsls_asserttest.h>
#include <bsls_bsltestutil.h>
#include <algorithm>
//#include <cctype>
//#include <cstdio>
//#include <cstdlib>
//#include <cstddef>
//#include <cstring>
#include <iomanip>
#include <iostream>
#include <istream>
#include <limits>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <typeinfo>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#if defined(std)
// This is a workaround for the way test drivers are built in an IDE-friendly
// manner in Visual Studio. A "normal" test driver built from the command line
// will not have 'std' defined as a macro, and so will not need this
// workaround. This workaround simply undoes the illusion that namespace 'std'
// is namespace 'bsl', so returning this test driver to its expected view.
#undef std
#endif
using namespace BloombergLP;
using namespace std;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The object under testing is a container whose interface and contract is
// dictated by the C++ standard. In particular, the standard mandates "strong"
// exception safety (with full guarantee of rollback) along with throwing
// 'std::length_error' if about to request memory for more than 'max_size()'
// elements. (Note: 'max_size' depends on the parameterized 'VALUE_TYPE'.)
// The general concerns are compliance, exception safety, and proper
// dispatching (for member function templates such as assign and insert). In
// addition, it is a value-semantic type whose salient attributes are size and
// value of each element in sequence. This container is implemented in the
// form of a class template, and thus its proper instantiation for several
// types is a concern. Regarding the allocator template argument, we use
// mostly a 'bsl::allocator' together with a 'bslma::TestAllocator' mechanism,
// but we also verify the C++ standard.
//
// This test plan follows the standard approach for components implementing
// value-semantic containers. We have chosen as *primary* *manipulators* the
// 'push_back' and 'clear' methods to be used by the generator functions
// 'g' and 'gg'. Additional helper functions are provided to facilitate
// perturbation of internal state (e.g., capacity). Note that some
// manipulators must support aliasing, and those that perform memory allocation
// must be tested for exception neutrality via the 'bslma_testallocator'
// component. After the mandatory sequence of cases (1--10) for value-semantic
// types (cases 5 and 10 are not implemented, as there is not output or
// streaming below bslstl), we test each individual constructor, manipulator,
// and accessor in subsequent cases.
//
// Regarding the allocation model, we attempt to write a general test driver
// that will work regardless of the allocation strategy chosen (short-string
// optimization, static null string, etc.) However, some testing is necessary
// to make sure we don't overallocate capacity, and for this, knowledge of the
// internal allocation model of the implementation under test is necessary, of
// course. This is done by the 'DEFAULT_CAPACITY' and
// 'INITIAL_CAPACITY_FOR_NON_EMPTY_OBJECT' constants, as well as the
// 'NUM_ALLOCS' array of constants, which would need to be adjusted if the
// allocation strategy were changed. Since this version provides access to the
// new capacity computation (in the 'Imp' class method 'computeNewCapacity'),
// we reuse that but abstract it in the test facility 'computeNewCapacity'.
//
// Abbreviations:
// --------------
// Throughout this test driver, we use
// C VALUE_TYPE (template argument, no default)
// A ALLOC (template argument, dflt: bsl::allocator<T>)
// string basic_string<C,CT,A> if template arguments not specified
// string<C,CT,A> basic_string<CHAR_TYPE,CHAR_TRAITS,ALLOCATOR>
// In the signatures, to keep one-liners, the arguments 'pos', 'pos1', pos'2',
// 'n', 'n1', and 'n2', are always of 'size_type', and 'a' is always of type
// 'const A&'.
//-----------------------------------------------------------------------------
// class string<C,CT,A> (string)
// =============================
// [11] TRAITS
//
// CREATORS:
// [ 2] string(a = A());
// [12] string(const string& str, pos, n = npos, a = A());
// [12] string(const C *s, n, a = A());
// [12] string(const C *s, a = A());
// [12] string(n, C c, a = A());
// [12] template<class InputIter>
// string(InputIter first, InputIter last, a = A());
// [ 7] string(const string& orig, a = A());
// [ 2] ~string();
//
/// MANIPULATORS:
// [ 9] operator=(const string& rhs);
// [ 9] operator=(const C *s);
// [ 9] operator=(c);
// [17] operator+=(const string& rhs);
// [17] operator+=(const C *s);
// [17] operator+=(c);
// [17] operator+=(const StringRefData& strRefData);
// [16] iterator begin();
// [16] iterator end();
// [16] reverse_iterator rbegin();
// [16] reverse_iterator rend();
// [14] void resize(size_type n);
// [14] void resize(size_type n, C c);
// [14] void reserve(size_type n);
// [ 2] void clear();
// [15] reference operator[](size_type pos);
// [15] reference at(size_type pos);
// [15] reference front();
// [15] reference back();
// [13] void assign(const string& str);
// [13] void assign(const string& str, pos, n);
// [13] void assign(const C *s, size_type n);
// [13] void assign(const C *s);
// [13] void assign(size_type n, C c);
// [13] template <class InputIter>
// void assign(InputIter first, InputIter last);
// [17] string& append(const string& str);
// [17] string& append(const string& str, pos, n);
// [17] string& append(const C *s, size_type n);
// [17] string& append(const C *s);
// [17] string& append(size_type n, C c);
// [17] template <class InputIter>
// string& append(InputIter first, InputIter last);
// [ 2] void push_back(C c);
// [18] string& insert(size_type pos1, const string& str);
// [18] string& insert(size_type pos1, const string& str, pos2, n);
// [18] string& insert(size_type pos, const C *s, n2);
// [18] string& insert(size_type pos, const C *s);
// [18] string& insert(size_type pos, size_type n, C c);
// [18] iterator insert(const_iterator p, C c);
// [18] iterator insert(const_iterator p, size_type n, C c);
// [18] template <class InputIter>
// iterator insert(const_iterator p, InputIter first, InputIter last);
// [19] void pop_back();
// [19] iterator erase(size_type pos = 0, size_type n = npos);
// [19] iterator erase(const_iterator p);
// [19] iterator erase(const_iterator first, iterator last);
// [20] string& replace(pos1, n1, const string& str);
// [20] string& replace(pos1, n1, const string& str, pos2, n2);
// [20] string& replace(pos1, n1, const C *s, n2);
// [20] string& replace(pos1, n1, const C *s);
// [20] string& replace(pos1, n1, size_type n2, C c);
// [20] replace(const_iterator first, const_iterator last, const string& str);
// [20] replace(const_iterator first, const_iterator last, const C *s, n2);
// [20] replace(const_iterator first, const_iterator last, const C *s);
// [20] replace(const_iterator first, const_iterator last, size_type n2, C c);
// [20] template <class InputIter>
// replace(const_iterator p, const_iterator q, InputIter f, InputIter l);
// [21] void swap(string&);
//
// ACCESSORS:
// [ 4] const_reference operator[](size_type pos) const;
// [ 4] const_reference at(size_type pos) const;
// [15] const_reference front() const;
// [15] const_reference back() const;
// [ ] size_type length() const;
// [ 4] size_type size() const;
// [14] size_type max_size() const;
// [14] size_type capacity() const;
// [14] bool empty() const;
// [16] const_iterator begin();
// [16] const_iterator end();
// [16] const_reverse_iterator rbegin();
// [16] const_reverse_iterator rend();
// [ ] const_iterator cbegin();
// [ ] const_iterator cend();
// [ ] const_reverse_iterator crbegin();
// [ ] const_reverse_iterator crend();
// [ ] const C *c_str() const;
// [ ] const C *data() const;
// [ ] allocator_type get_allocator() const;
// [22] size_type find(const string& str, pos = 0) const;
// [22] size_type find(const C *s, pos, n) const;
// [22] size_type find(const C *s, pos = 0) const;
// [22] size_type find(C c, pos = 0) const;
// [22] size_type rfind(const string& str, pos = 0) const;
// [22] size_type rfind(const C *s, pos, n) const;
// [22] size_type rfind(const C *s, pos = 0) const;
// [22] size_type rfind(C c, pos = 0) const;
// [22] size_type find_first_of(const string& str, pos = 0) const;
// [22] size_type find_first_of(const C *s, pos, n) const;
// [22] size_type find_first_of(const C *s, pos = 0) const;
// [22] size_type find_first_of(C c, pos = 0) const;
// [22] size_type find_last_of(const string& str, pos = 0) const;
// [22] size_type find_last_of(const C *s, pos, n) const;
// [22] size_type find_last_of(const C *s, pos = 0) const;
// [22] size_type find_last_of(C c, pos = 0) const;
// [22] size_type find_first_not_of(const string& str, pos = 0) const;
// [22] size_type find_first_not_of(const C *s, pos, n) const;
// [22] size_type find_first_not_of(const C *s, pos = 0) const;
// [22] size_type find_first_not_of(C c, pos = 0) const;
// [22] size_type find_last_not_of(const string& str, pos = 0) const;
// [22] size_type find_last_not_of(const C *s, pos, n) const;
// [22] size_type find_last_not_of(const C *s, pos = 0) const;
// [22] size_type find_last_not_of(C c, pos = 0) const;
// [23] string substr(pos, n) const;
// [23] size_type copy(char *s, n, pos = 0) const;
// [24] int compare(const string& str) const;
// [24] int compare(pos1, n1, const string& str) const;
// [24] int compare(pos1, n1, const string& str, pos2, n2) const;
// [24] int compare(const C* s) const;
// [24] int compare(pos1, n1, const C* s) const;
// [24] int compare(pos1, n1, const C* s, n2) const;
//
// FREE OPERATORS:
// [ 6] bool operator==(const string&, const string&);
// [ 6] bool operator==(const C *, const string&);
// [ 6] bool operator==(const string&, const C *);
// [ 6] bool operator!=(const string&, const string&);
// [ 6] bool operator!=(const C *, const string&);
// [ 6] bool operator!=(const string&, const C *);
// [24] bool operator<(const string&, const string&);
// [24] bool operator<(const C *, const string&);
// [24] bool operator<(const string&, const C *);
// [24] bool operator>(const string&, const string&);
// [24] bool operator>(const C *, const string&);
// [24] bool operator>(const string&, const C *);
// [24] bool operator<=(const string&, const string&);
// [24] bool operator<=(const C *, const string&);
// [24] bool operator<=(const string&, const C *);
// [24] bool operator>=(const string&, const string&);
// [24] bool operator>=(const C *, const string&);
// [24] bool operator>=(const string&, const C *);
// [21] void swap(string&, string&);
// [30] int stoi(const string& str, std::size_t* pos = 0, int base 10);
// [30] int stoi(const wstring& str, std::size_t* pos = 0, int base 10);
// [30] int stol(const string& str, std::size_t* pos = 0, int base 10);
// [30] int stol(const wstring& str, std::size_t* pos = 0, int base 10);
// [30] int stoul(const string& str, std::size_t* pos = 0, int base 10);
// [30] int stoul(const wstring& str, std::size_t* pos = 0, int base 10);
// [30] int stoll(const string& str, std::size_t* pos = 0, int base 10);
// [30] int stoll(const wstring& str, std::size_t* pos = 0, int base 10);
// [30] int stoull(const string& str, std::size_t* pos = 0, int base 10);
// [30] int stoull(const wstring& str, std::size_t* pos = 0, int base 10);
// [31] float stof(const string& str, std::size_t* pos =0);
// [31] float stof(const wstring& str, std::size_t* pos =0);
// [31] double stod(const string& str, std::size_t* pos =0);
// [31] double stod(const wstring& str, std::size_t* pos =0);
// [31] long double stold(const string& str, std::size_t* pos =0);
// [31] long double stold(const wstring& str, std::size_t* pos =0);
// [32] string to_string(int value);
// [32] string to_string(long value);
// [32] string to_string(long long value);
// [32] string to_string(unsigned value);
// [32] string to_string(unsigned long value);
// [32] string to_string(unsigned long long value);
// [32] string to_string(float value);
// [32] string to_string(double value);
// [32] string to_string(long double value);
// [32] wstring to_wstring(int value);
// [32] wstring to_wstring(long value);
// [32] wstring to_wstring(long long value);
// [32] wstring to_wstring(unsigned value);
// [32] wstring to_wstring(unsigned long value);
// [32] wstring to_wstring(unsigned long long value);
// [32] wstring to_wstring(float value);
// [32] wstring to_wstring(double value);
// [32] wstring to_wstring(long double value);
// [ 5] basic_ostream<C,CT>& operator<<(basic_ostream<C,CT>& stream,
// const string& str);
// [ 5] basic_istream<C,CT>& operator>>(basic_istream<C,CT>& stream,
// const string& str);
// [29] hashAppend(HASHALG& hashAlg, const basic_string& str);
// [29] hashAppend(HASHALG& hashAlg, const native_std::basic_string& str);
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [11] ALLOCATOR-RELATED CONCERNS
// [25] CONCERN: 'std::length_error' is used properly
//
// TEST APPARATUS: GENERATOR FUNCTIONS
// [ 3] int ggg(string *object, const char *spec, int vF = 1);
// [ 3] string& gg(string *object, const char *spec);
// [ 8] string g(const char *spec);
// [ 8] string g(size_t len, TYPE seed);
//=============================================================================
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(int c, const char *s, int i) {
if (c) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
} // close unnamed namespace
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
#define ASSERT_FAIL(expr) BSLS_ASSERTTEST_ASSERT_FAIL(expr)
#define ASSERT_PASS(expr) BSLS_ASSERTTEST_ASSERT_PASS(expr)
#define ASSERT_SAFE_FAIL(expr) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(expr)
#define ASSERT_SAFE_PASS(expr) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(expr)
#define ASSERT_FAIL_RAW(expr) BSLS_ASSERTTEST_ASSERT_FAIL_RAW(expr)
#define ASSERT_PASS_RAW(expr) BSLS_ASSERTTEST_ASSERT_PASS_RAW(expr)
#define ASSERT_SAFE_FAIL_RAW(expr) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL_RAW(expr)
#define ASSERT_SAFE_PASS_RAW(expr) BSLS_ASSERTTEST_ASSERT_SAFE_PASS_RAW(expr)
//=============================================================================
// STANDARD BDE LOOP-ASSERT TEST MACROS
//-----------------------------------------------------------------------------
// NOTE: This implementation of LOOP_ASSERT macros must use 'printf' since
// 'cout' uses new and must not be called during exception testing.
#define LOOP_ASSERT(I,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
#define LOOP2_ASSERT(I,J,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\t"); \
printf("%s", #J ": "); dbg_print(J); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
#define LOOP3_ASSERT(I,J,K,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\t"); \
printf("%s", #J ": "); dbg_print(J); printf("\t"); \
printf("%s", #K ": "); dbg_print(K); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
#define LOOP4_ASSERT(I,J,K,L,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\t"); \
printf("%s", #J ": "); dbg_print(J); printf("\t"); \
printf("%s", #K ": "); dbg_print(K); printf("\t"); \
printf("%s", #L ": "); dbg_print(L); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
#define LOOP5_ASSERT(I,J,K,L,M,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\t"); \
printf("%s", #J ": "); dbg_print(J); printf("\t"); \
printf("%s", #K ": "); dbg_print(K); printf("\t"); \
printf("%s", #L ": "); dbg_print(L); printf("\t"); \
printf("%s", #M ": "); dbg_print(M); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
#define LOOP6_ASSERT(I,J,K,L,M,N,X) { \
if (!(X)) { printf("%s", #I ": "); dbg_print(I); printf("\t"); \
printf("%s", #J ": "); dbg_print(J); printf("\t"); \
printf("%s", #K ": "); dbg_print(K); printf("\t"); \
printf("%s", #L ": "); dbg_print(L); printf("\t"); \
printf("%s", #M ": "); dbg_print(M); printf("\n"); \
printf("%s", #N ": "); dbg_print(N); printf("\n"); \
fflush(stdout); aSsErT(1, #X, __LINE__); } }
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
#define Q(X) printf("<| " #X " |>\n"); // Quote identifier literally.
#define P(X) dbg_print(#X " = ", X, "\n") // Print identifier and value.
#define P_(X) dbg_print(#X " = ", X, ", ") // P(X) without '\n'
#define L_ __LINE__ // current Line number
#define T_ putchar('\t'); // Print a tab (w/o newline)
// ============================================================================
// PRINTF FORMAT MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
// TYPES
typedef bsls::Types::Int64 Int64;
typedef bsls::Types::Uint64 Uint64;
// TEST OBJECT (unless o/w specified)
typedef char Element;
typedef bsl::basic_string<char, bsl::char_traits<char> > Obj;
typedef bsl::String_Imp<char, size_t> Imp;
// CONSTANTS
const int MAX_ALIGN = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT;
const int MAX_ALIGN_MASK = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT - 1;
const char UNINITIALIZED_VALUE = '_';
const char DEFAULT_VALUE = 'z';
const char VA = 'A';
const char VB = 'B';
const char VC = 'C';
const char VD = 'D';
const char VE = 'E';
const char VF = 'F';
const char VG = 'G';
const char VH = 'H';
const char VI = 'I';
const char VJ = 'J';
const char VK = 'K';
const char VL = 'L';
// All test types have character value type.
const int LARGE_SIZE_VALUE = 2 * bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT;
// Declare a large value for insertions into the string. Note this value
// will cause multiple resizes during insertion into the string.
const size_t SHORT_STRING_BUFFER_BYTES
= (20 + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1);
// The size of the short string buffer, according to our implementation (20
// bytes rounded to the word boundary - 1). Appending one more than this
// number of characters to a default object causes a reallocation.
const size_t INITIAL_CAPACITY_FOR_NON_EMPTY_OBJECT = 1;
// bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT - 1;
// The capacity of a default constructed object after the first
// 'push_back', according to our implementation.
const int NUM_ALLOCS[] = {
// Number of allocations (blocks) to create a string of the following size
// by using 'push_back' repeatedly (without initial reserve):
#if BSLS_PLATFORM_CPU_64_BIT
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3,
// 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4
#else
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
// 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3
#endif
};
//=============================================================================
// GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------
// Fundamental-type-specific print functions.
inline void dbg_print(char c) { printf("%c", c); fflush(stdout); }
inline void dbg_print(unsigned char c) { printf("%c", c); fflush(stdout); }
inline void dbg_print(wchar_t c) { printf("%lc", wint_t(c)); fflush(stdout); }
inline void dbg_print(signed char c) { printf("%c", c); fflush(stdout); }
inline void dbg_print(short val) { printf("%d", (int)val); fflush(stdout); }
inline void dbg_print(unsigned short val) {
printf("%d", (int)val);
fflush(stdout);
}
inline void dbg_print(int val) { printf("%d", val); fflush(stdout); }
inline void dbg_print(bsls::Types::Int64 val) {
printf("%lld", val);
fflush(stdout);
}
inline void dbg_print(size_t val) { printf(ZU, val); fflush(stdout); }
inline void dbg_print(float val) {
printf("'%f'", (double)val);
fflush(stdout);
}
inline void dbg_print(double val) { printf("'%f'", val); fflush(stdout); }
inline void dbg_print(const char *s) { printf("\"%s\"", s); fflush(stdout); }
inline void dbg_print(const void *val)
{
printf("\"%p\"", val);
fflush(stdout);
}
void dbg_print(const wchar_t *s)
{
putchar('"');
while (*s) {
dbg_print(*s);
++s;
}
putchar('"');
fflush(stdout);
}
// String-specific print function.
template <class TYPE, class TRAITS, class ALLOC>
void dbg_print(const bsl::basic_string<TYPE,TRAITS,ALLOC>& v)
{
if (v.empty()) {
printf("<empty>");
}
else {
for (size_t i = 0; i < v.size(); ++i) {
dbg_print(v[i]);
}
}
fflush(stdout);
}
// Generic debug print function (3-arguments).
template <class T>
void dbg_print(const char* s, const T& val, const char* nl)
{
printf("%s", s); dbg_print(val);
printf("%s", nl);
fflush(stdout);
}
// String utilities
size_t max(size_t lhs, size_t rhs)
{
return lhs < rhs ? rhs : lhs;
}
size_t computeNewCapacity(size_t newLength,
size_t /* initLength */,
size_t capacity,
size_t maxSize)
// Compute the expected capacity of a string constructed with the specified
// 'newLength' and 'capacity' as in by:
//..
// Obj mX(newLength, ' ', allocator);
// mX.reserve(capacity);
//..
// and later modified to the 'newLength' by inserting characters (either by
// 'insert' or 'push_back', it should not matter), assignment (using
// 'assign), or replacement (using 'replace'). We assume that none of the
// intermediate quantities can overflow the range of 'size_t', although we
// accept the specified 'maxSize' as a ceiling for the new capacity. Note
// that 'newLength' is not necessarily larger than 'initLength'.
{
// This implementation conforms to the one in the header, and is verified
// to provide constant amortized time per character for all manipulators
// (w.r.t. memory allocation).
if (newLength <= capacity) {
return capacity; // RETURN
}
// adjust capacity the same way as it's done by the string implementation
capacity += (capacity >> 1);
if (newLength > capacity) {
capacity = newLength;
}
return capacity > maxSize ? maxSize : capacity; // RETURN
}
//=============================================================================
// GLOBAL HELPER CLASSES FOR TESTING
//-----------------------------------------------------------------------------
// STATIC DATA
static int verbose, veryVerbose, veryVeryVerbose, veryVeryVeryVerbose;
static bslma::TestAllocator *globalAllocator_p,
*defaultAllocator_p,
*objectAllocator_p;
static int numCopyCtorCalls = 0;
static int numDestructorCalls = 0;
// ====================
// class ExceptionGuard
// ====================
template <class VALUE_TYPE>
struct ExceptionGuard {
// This scoped guard helps to verify the full guarantee of rollback in
// exception-throwing code.
// DATA
int d_lineNum;
VALUE_TYPE d_value;
VALUE_TYPE *d_object_p;
public:
// CREATORS
ExceptionGuard(VALUE_TYPE *object, const VALUE_TYPE& value, int line)
: d_lineNum(line)
, d_value(value)
, d_object_p(object)
{}
~ExceptionGuard() {
if (d_object_p) {
const int LINE = d_lineNum;
LOOP3_ASSERT(LINE, d_value, *d_object_p, d_value == *d_object_p);
}
}
// MANIPULATORS
void resetValue(const VALUE_TYPE& value, int line) {
d_lineNum = line;
d_value = value;
}
void release() {
d_object_p = 0;
}
};
// ==============
// class CharList
// ==============
template <class TYPE,
class TRAITS = bsl::char_traits<TYPE>,
class ALLOC = bsl::allocator<TYPE> >
class CharList {
// This array class is a simple wrapper on a 'char' array offering an input
// iterator access via the 'begin' and 'end' accessors. The iterator is
// specifically an *input* iterator and its value type is the parameterized
// 'TYPE'.
typedef bsl::basic_string<TYPE,TRAITS,ALLOC> Obj;
// DATA
Obj d_value;
public:
// TYPES
typedef bslstl::ForwardIterator<const TYPE, const TYPE*> const_iterator;
// Input iterator.
// CREATORS
CharList() {}
CharList(const Obj& value);
// ACCESSORS
const TYPE& operator[](size_t index) const;
const_iterator begin() const;
const_iterator end() const;
};
// CREATORS
template <class TYPE, class TRAITS, class ALLOC>
CharList<TYPE,TRAITS,ALLOC>::CharList(const Obj& value)
: d_value(value)
{
}
// ACCESSORS
template <class TYPE, class TRAITS, class ALLOC>
const TYPE& CharList<TYPE,TRAITS,ALLOC>::operator[](size_t index) const {
return d_value[index];
}
template <class TYPE, class TRAITS, class ALLOC>
typename CharList<TYPE,TRAITS,ALLOC>::const_iterator
CharList<TYPE,TRAITS,ALLOC>::begin() const {
return const_iterator(&*d_value.begin());
}
template <class TYPE, class TRAITS, class ALLOC>
typename CharList<TYPE,TRAITS,ALLOC>::const_iterator
CharList<TYPE,TRAITS,ALLOC>::end() const {
return const_iterator(&*d_value.end());
}
// ===============
// class CharArray
// ===============
template <class TYPE,
class TRAITS = bsl::char_traits<TYPE>,
class ALLOC = bsl::allocator<TYPE> >
class CharArray {
// This array class is a simple wrapper on a string offering an input
// iterator access via the 'begin' and 'end' accessors. The iterator is
// specifically a *random-access* iterator and its value type is the
// parameterized 'TYPE'.
typedef bsl::basic_string<TYPE,TRAITS,ALLOC> Obj;
// DATA
Obj d_value;
public:
// TYPES
typedef const TYPE *const_iterator;
// Random-access iterator.
// CREATORS
CharArray() {}
CharArray(const Obj& value);
// ACCESSORS
const TYPE& operator[](size_t index) const;
const_iterator begin() const;
const_iterator end() const;
};
// CREATORS
template <class TYPE, class TRAITS, class ALLOC>
CharArray<TYPE,TRAITS,ALLOC>::CharArray(const Obj& value)
: d_value(value)
{
}
// ACCESSORS
template <class TYPE, class TRAITS, class ALLOC>
const TYPE& CharArray<TYPE,TRAITS,ALLOC>::operator[](size_t index) const {
return d_value[index];
}
template <class TYPE, class TRAITS, class ALLOC>
typename CharArray<TYPE,TRAITS,ALLOC>::const_iterator
CharArray<TYPE,TRAITS,ALLOC>::begin() const {
return const_iterator(&*d_value.begin());
}
template <class TYPE, class TRAITS, class ALLOC>
typename CharArray<TYPE,TRAITS,ALLOC>::const_iterator
CharArray<TYPE,TRAITS,ALLOC>::end() const {
return const_iterator(&*d_value.end());
}
// ==============
// class UserChar
// ==============
template <int size>
class UserChar {
// This class is a simulation of a user-defined char type. It has a
// variable object size to test that the string works with chars larger
// than 'char' and 'wchar_t'.
private:
// DATA
union {
size_t d_words[size];
char d_char;
};
public:
// CREATORS
explicit
UserChar(char c = 10);
// ACCESSORS
bool operator==(const UserChar& rhs) const;
bool operator!=(const UserChar& rhs) const;
};
template <int size>
inline
UserChar<size>::UserChar(char c)
: d_char(c)
{}
template <int size>
inline
bool UserChar<size>::operator==(const UserChar& rhs) const {
return d_char == rhs.d_char;
}
template <int size>
inline
bool UserChar<size>::operator!=(const UserChar& rhs) const {
return !(*this == rhs);
}
// ====================
// class LimitAllocator
// ====================
template <class ALLOC>
class LimitAllocator : public ALLOC {
public:
// TYPES
typedef typename ALLOC::value_type value_type;
typedef typename ALLOC::pointer pointer;
typedef typename ALLOC::const_pointer const_pointer;
typedef typename ALLOC::reference reference;
typedef typename ALLOC::const_reference const_reference;
typedef typename ALLOC::size_type size_type;
typedef typename ALLOC::difference_type difference_type;
template <class OTHER_TYPE> struct rebind {
// It is better not to inherit the rebind template, or else
// rebind<X>::other would be ALLOC::rebind<OTHER_TYPE>::other
// instead of LimitAlloc<X>.
typedef LimitAllocator<typename ALLOC::template
rebind<OTHER_TYPE>::other > other;
};
private:
// PRIVATE TYPES
typedef ALLOC AllocBase;
// DATA
size_type d_limit;
public:
// CREATORS
LimitAllocator()
: d_limit(-1) {}
LimitAllocator(bslma::Allocator *mechanism)
: AllocBase(mechanism), d_limit(-1) { }
LimitAllocator(const ALLOC& rhs)
: AllocBase((const AllocBase&) rhs), d_limit(-1) { }
~LimitAllocator() { }
// MANIPULATORS
void setMaxSize(size_type maxSize) { d_limit = maxSize; }
// ACCESSORS
size_type max_size() const { return d_limit; }
};
template <class TYPE, class TRAITS, class ALLOC>
inline
bool isNativeString(const bsl::basic_string<TYPE,TRAITS,ALLOC>&)
{ return false; }
template <class TYPE, class TRAITS, class ALLOC>
inline
bool isNativeString(const std::basic_string<TYPE,TRAITS,ALLOC>&)
{ return true; }
//=============================================================================
// TEST DRIVER TEMPLATE
//-----------------------------------------------------------------------------
template <class TYPE,
class TRAITS = bsl::char_traits<TYPE>,
class ALLOC = bsl::allocator<TYPE> >
struct TestDriver {
// The generating functions interpret the given 'spec' in order from left
// to right to configure the object according to a custom language.
// Uppercase letters [A .. E] correspond to arbitrary (but unique) char
// values to be appended to the 'string' object. A tilde ('~') indicates
// that the logical (but not necessarily physical) state of the object is
// to be set to its initial, empty state (via the 'clear' method).
//
// LANGUAGE SPECIFICATION:
// -----------------------
//
// <SPEC> ::= <EMPTY> | <LIST>
//
// <EMPTY> ::=
//
// <LIST> ::= <ITEM> | <ITEM><LIST>
//
// <ITEM> ::= <ELEMENT> | <CLEAR>
//
// <ELEMENT> ::= 'A' | 'B' | 'C' | 'D' | 'E' | ... | 'H'
// // unique but otherwise arbitrary
// <CLEAR> ::= '~'
//
// Spec String Description
// ----------- -----------------------------------------------------------
// "" Has no effect; leaves the object empty.
// "A" Append the value corresponding to A.
// "AA" Append two values both corresponding to A.
// "ABC" Append three values corresponding to A, B and C.
// "ABC~" Append three values corresponding to A, B and C and then
// remove all the elements (set array length to 0). Note that
// this spec yields an object that is logically equivalent
// (but not necessarily identical internally) to one
// yielded by ("").
// "ABC~DE" Append three values corresponding to A, B, and C; empty
// the object; and append values corresponding to D and E.
//-------------------------------------------------------------------------
// TYPES
typedef bsl::basic_string<TYPE,TRAITS,ALLOC> Obj;
// Type under testing.
typedef typename Obj::allocator_type Allocator;
// And its allocator (may be different from 'ALLOC' via rebind).
typedef ALLOC AllocType;
// Utility typedef for xlC10 silliness.
// CONSTANTS
enum {
DEFAULT_CAPACITY = SHORT_STRING_BUFFER_BYTES / sizeof(TYPE) > 0
? SHORT_STRING_BUFFER_BYTES / sizeof(TYPE) - 1
: 0
};
typedef typename Obj::iterator iterator;
typedef typename Obj::const_iterator const_iterator;
typedef typename Obj::reverse_iterator reverse_iterator;
typedef typename Obj::const_reverse_iterator const_reverse_iterator;
// Shorthand.
// TEST APPARATUS
static int getValues(const TYPE **values);
// Load the specified 'values' with the address of an array containing
// initialized values of the parameterized 'TYPE' and return the length
// of that array.
static int ggg(Obj *object, const char *spec, int verboseFlag = 1);
// Configure the specified 'object' according to the specified 'spec',
// using only the primary manipulator function 'push_back' and
// white-box manipulator 'clear'. Optionally specify a zero
// 'verboseFlag' to suppress 'spec' syntax error messages. Return the
// index of the first invalid character, and a negative value
// otherwise. Note that this function is used to implement 'gg' as
// well as allow for verification of syntax error detection.
static Obj& gg(Obj *object, const char *spec);
// Return, by reference, the specified object with its value adjusted
// according to the specified 'spec'.
static Obj g(const char *spec);
// Return, by value, a new object corresponding to the specified
// 'spec'.
static Obj g(size_t len, TYPE seed);
// Return, by value, a new string object with the specified 'length'
// and the specified 'seed' character. The actual content of the
// string is not important, only the string length and the fact that
// two different 'seeds' produce two different results.
static void stretch(Obj *object, size_t size, const TYPE& value = TYPE());
// Using only primary manipulators, extend the length of the specified
// 'object' by the specified size by adding copies of the specified
// 'value'. The resulting value is not specified. The behavior is
// undefined unless 0 <= size.
static void stretchRemoveAll(Obj *object,
size_t size,
const TYPE& value = TYPE());
// Using only primary manipulators, extend the capacity of the
// specified 'object' to (at least) the specified size by adding copies
// of the optionally specified 'value'; then remove all elements
// leaving 'object' empty. The behavior is undefined unless
// '0 <= size'.
static void checkCompare(const Obj& X, const Obj& Y, int result);
// Compare the specified 'X' and 'Y' strings according to the
// specifications, and check that the specified 'result' agrees.
// TEST CASES
static void testCase32();
// Test to_string and to_wstring free methods.
static void testCase31();
// Test stof, stod and stold free methods.
static void testCase30();
// Test stoi, stol and stoll free methods.
static void testCase29();
// Test the hash append specialization.
static void testCase28();
// Test the short string optimization.
static void testCase26();
// Test conversions to/from native strings.
static void testCase25();
// Test proper use of 'std::length_error'.
static void testCase24();
// Test comparison free operators.
static void testCase24Negative();
// Negative test 'compare' and comparison free operators.
static void testCase23();
// Test 'copy' and 'substr' methods.
static void testCase23Negative();
// Negative test for 'copy'.
static void testCase22();
// Test 'find...' methods.
static void testCase22Negative();
// Negative test for 'find...' methods.
static void testCase21();
// Test 'swap' member.
static void testCase20();
// Test 'replace'.
template <class CONTAINER>
static void testCase20Range(const CONTAINER&);
// Test 'replace' member template.
static void testCase20Negative();
// Negative test for 'replace'.
static void testCase19();
// Test 'erase' and 'pop_back'.
static void testCase19Negative();
// Negative test for 'erase' and 'pop_back'.
static void testCase18();
// Test 'insert' and move 'push_back'.
template <class CONTAINER>
static void testCase18Range(const CONTAINER&);
// Test 'insert' member template.
static void testCase18Negative();
// Negative test for 'insert'.
static void testCase17();
// Test 'append'.
template <class CONTAINER>
static void testCase17Range(const CONTAINER&);
// Test 'append' member template.
static void testCase17Negative();
// Negative test for 'append'.
static void testCase16();
// Test iterators.
static void testCase15();
// Test element access.
static void testCase15Negative();
// Negative test for element access.
static void testCase14();
// Test reserve and capacity-related methods.
static void testCase13();
// Test 'assign' members.
template <class CONTAINER>
static void testCase13Range(const CONTAINER&);
// Test 'assign' member template.
static void testCase13Negative();
// Negative test for 'assign' members.
static void testCase12();
// Test user-supplied constructors.
static void testCase12Negative();
// Negative test for user-supplied constructors.
template <class CONTAINER>
static void testCase12Range(const CONTAINER&);
// Test user-supplied constructor templates.
static void testCase11();
// Test allocator-related concerns.
static void testCase10();
// Test streaming functionality. This test case tests nothing.
static void testCase9();
// Test assignment operator ('operator=').
static void testCase9Negative();
// Negative test for assignment operator ('operator=').
static void testCase8();
// Test generator function 'g'.
static void testCase7();
// Test copy constructor.
static void testCase6();
// Test equality operators ('operator==/!=').
static void testCase6Negative();
// Negative test for equality operators.
static void testCase5();
// Test output (<<) operator. This test case tests nothing.
static void testCase4();
// Test basic accessors ('size' and 'operator[]').
static void testCase3();
// Test generator functions 'ggg' and 'gg'.
static void testCase2();
// Test primary manipulators ('push_back' and 'clear').
static void testCase1();
// Breathing test. This test *exercises* basic functionality but
// *test* nothing.
static void testCaseM1(const int NITER, const int RANDOM_SEED);
// Performance regression test.
};
// --------------
// TEST APPARATUS
// --------------
template <class TYPE, class TRAITS, class ALLOC>
int TestDriver<TYPE,TRAITS,ALLOC>::getValues(const TYPE **valuesPtr)
{
bslma::DefaultAllocatorGuard guard(
&bslma::NewDeleteAllocator::singleton());
static TYPE values[12]; // avoid DEFAULT_VALUE and UNINITIALIZED_VALUE
values[0] = TYPE(VA);
values[1] = TYPE(VB);
values[2] = TYPE(VC);
values[3] = TYPE(VD);
values[4] = TYPE(VE);
values[5] = TYPE(VF);
values[6] = TYPE(VG);
values[7] = TYPE(VH);
values[8] = TYPE(VI);
values[9] = TYPE(VJ);
values[10] = TYPE(VK);
values[11] = TYPE(VL);
const int NUM_VALUES = 12;
*valuesPtr = values;
return NUM_VALUES;
}
template <class TYPE, class TRAITS, class ALLOC>
int TestDriver<TYPE,TRAITS,ALLOC>::ggg(Obj *object,
const char *spec,
int verboseFlag)
{
const TYPE *VALUES;
getValues(&VALUES);
enum { SUCCESS = -1 };
for (int i = 0; spec[i]; ++i) {
if ('A' <= spec[i] && spec[i] <= 'L') {
object->push_back(VALUES[spec[i] - 'A']);
}
else if ('~' == spec[i]) {
object->clear();
}
else {
if (verboseFlag) {
printf("Error, bad character ('%c') "
"in spec \"%s\" at position %d.\n", spec[i], spec, i);
}
return i; // Discontinue processing this spec. // RETURN
}
}
return SUCCESS;
}
template <class TYPE, class TRAITS, class ALLOC>
bsl::basic_string<TYPE,TRAITS,ALLOC>& TestDriver<TYPE,TRAITS,ALLOC>::gg(
Obj *object,
const char *spec)
{
ASSERT(ggg(object, spec) < 0);
return *object;
}
template <class TYPE, class TRAITS, class ALLOC>
bsl::basic_string<TYPE,TRAITS,ALLOC>
TestDriver<TYPE,TRAITS,ALLOC>::g(const char *spec)
{
Obj object((bslma::Allocator *)0);
return gg(&object, spec);
}
template <class TYPE, class TRAITS, class ALLOC>
bsl::basic_string<TYPE,TRAITS,ALLOC>
TestDriver<TYPE,TRAITS,ALLOC>::g(size_t len, TYPE seed)
{
Obj object(len, TYPE());
for (size_t i = 0; i < len; ++i) {
object[i] = TYPE(i + seed);
}
return object;
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::stretch(Obj *object,
size_t size,
const TYPE& value)
{
ASSERT(object);
for (size_t i = 0; i < size; ++i) {
object->push_back(value);
}
ASSERT(object->size() >= size);
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::stretchRemoveAll(Obj *object,
size_t size,
const TYPE& value)
{
ASSERT(object);
stretch(object, size, value);
object->clear();
ASSERT(0 == object->size());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::checkCompare(const Obj& X,
const Obj& Y,
int result)
{
// As per C++ standard, chapter 21, clause 21.3.7.9.
typename Obj::size_type rlen = std::min(X.length(), Y.length());
int ret = TRAITS::compare(X.data(), Y.data(), rlen);
if (ret) {
ASSERT(ret == result);
return; // RETURN
}
if (X.size() > Y.size()) {
ASSERT(result > 0);
return; // RETURN
}
if (X.size() < Y.size()) {
ASSERT(result < 0);
return; // RETURN
}
if (X.size() == Y.size()) {
ASSERT(result == 0);
return; // RETURN
}
ASSERT(0);
}
// ----------
// TEST CASES
// ----------
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase32(){
// ------------------------------------------------------------------------
// TESTING 'to_string' AND 'to_wstring'
//
// Concerns:
//: 1 to_string and to_wstring create the a string that is the same as what
//: springf() and swprinf() would produce for sufficiently large buffers
//
// Plan:
//: 1 use 'sprintf' and 'swprintf' with an arbitarly large buffer, (in this
//: test case the buffer size will be 500) and compare it to the output
//: of 'to_string' and 'to_wstring'.
//
// Testing:
// string to_string(int value);
// string to_string(long value);
// string to_string(long long value);
// string to_string(unsigned value);
// string to_string(unsigned long value);
// string to_string(unsigned long long value);
// string to_string(float value);
// string to_string(double value);
// string to_string(long double value);
// string to_wstring(int value);
// string to_wstring(long value);
// string to_wstring(long long value);
// string to_wstring(unsigned value);
// string to_wstring(unsigned long value);
// string to_wstring(unsigned long long value);
// string to_wstring(float value);
// string to_wstring(double value);
// string to_wstring(long double value);
// ------------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
static const struct {
int d_lineNum;
long long d_value;
} DATA[] = {
// value
{L_, 0},
{L_, 1},
{L_, -1},
{L_, 10101},
{L_, -10101},
{L_, 32767},
{L_, -32767},
{L_, 11001100},
{L_, -11001100},
{L_, 2147483647},
{L_, -2147483647},
{L_, 9223372036854775807LL},
{L_,-9223372036854775807LL},
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
Obj spec(AllocType(&testAllocator));
Obj wspec(AllocType(&testAllocator));
char tempBuf[500]; // very large char buffer
wchar_t wTempBuf[500];
if (verbose) {
printf("\nTesting 'to_string() and to_string with integrals.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti){
const int LINE = DATA[ti].d_lineNum;
const long long VALUE = DATA[ti].d_value;
if (veryVerbose){
printf("\tConverting ");P_(VALUE);
printf("to a string.\n");
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose)
{
printf("\t\tBefore: ");P_(BB);P(B);
}
if (VALUE <= std::numeric_limits<int>::max()){
sprintf(tempBuf, "%d", static_cast<int>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<int>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%d", static_cast<int>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<int>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<unsigned int>::max() && VALUE >=0){
sprintf(tempBuf, "%u", static_cast<unsigned int>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<unsigned int>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%u", static_cast<unsigned int>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<unsigned int>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<long>::max()){
sprintf(tempBuf, "%ld", static_cast<long>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<long>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%ld", static_cast<long>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<long>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<unsigned long>::max() && VALUE >=0){
sprintf(tempBuf, "%lu", static_cast<unsigned long>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<unsigned long>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%lu", static_cast<unsigned long>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<unsigned long>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<long long>::max()){
sprintf(tempBuf, "%lld", static_cast<long long>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<long long>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%lld", static_cast<long long>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<long long>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<unsigned long long>::max()&&VALUE>=0){
sprintf(tempBuf, "%llu",
static_cast<unsigned long long>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast
<unsigned long long>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf,
L"%lld", static_cast<unsigned long long>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast
<unsigned long long>(VALUE));
ASSERT(wstr == wspec);
}
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose)
{
printf("\t\tAfter: ");P_(AA);P(A);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\nTesting 'to_string() with floating points.\n");
static const struct {
int d_lineNum;
double d_value;
} DOUBLE_DATA[] = {
// value
{L_, 1.0},
{L_, 1.01},
{L_, 1.010},
{L_, 1.0101},
{L_, 1.01010},
{L_, 1.010101},
{L_, 1.01010101},
{L_, 1.0101019},
{L_, 3.1415926},
{L_, 005.156},
{L_, 24.0},
{L_, 24.1111111111111111111},
{L_, 12345.12345678},
{L_, 123456789.123456789},
{L_, 123456789012345.123456},
{L_, 1234567890123456789.123456789},
{L_, std::numeric_limits<float>::max()},
{L_, std::numeric_limits<float>::min()},
{L_, 1.79769e+308},
{L_,-1.79769e+308},
};
const int NUM_DOUBLE_DATA = sizeof DOUBLE_DATA / sizeof *DOUBLE_DATA;
for (int ti = 0; ti < NUM_DOUBLE_DATA; ++ti){
const int LINE = DOUBLE_DATA[ti].d_lineNum;
const double VALUE = DOUBLE_DATA[ti].d_value;
if (veryVerbose){
printf("\tConverting ");P_(VALUE);
printf("to a string.\n");
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose)
{
printf("\t\tBefore: ");P_(BB);P(B);
}
if (VALUE <= std::numeric_limits<float>::max()){
sprintf(tempBuf, "%f", static_cast<float>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<float>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf, L"%f",
static_cast<float>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<float>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<double>::max()){
sprintf(tempBuf, "%f", static_cast<double>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<double>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf, L"%f",
static_cast<double>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<double>(VALUE));
ASSERT(wstr == wspec);
}
if (VALUE <= std::numeric_limits<float>::max()){
sprintf(tempBuf, "%Lf", static_cast<long double>(VALUE));
string spec(tempBuf);
string str = bsl::to_string(static_cast<long double>(VALUE));
ASSERT(str == spec);
swprintf(wTempBuf, sizeof wTempBuf / sizeof *wTempBuf, L"%Lf",
static_cast<long double>(VALUE));
wstring wspec(wTempBuf);
wstring wstr = bsl::to_wstring(static_cast<long double>(VALUE));
ASSERT(wstr == wspec);
}
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose)
{
printf("\t\tAfter: ");P_(AA);P(A);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase31(){
// ------------------------------------------------------------------------
// TESTING 'stod', 'stof', 'stold'
//
// Concerns:
//: 1 stof, stod, stold parse the string properly into proper floating
//: point number
//:
//: 2 The methods discard leading white space characters and create largest
//: valid floating point number
//:
//: 3 Detects the correct base with leading 0X or 0x
//:
//: 4 The methods detect exponents correctly
//:
//: 5 The methods correctly identify INF/INFINITY as appropriate
//
// Plan:
//: 1 Use stof, stod, and stold on a variety of valid value to ensure
//: that the methods parse correctly (C-1)
//:
//: 2 Try to convert partially valid strings, ie strings that contain
//: characters that are not valid in the base of the number.
//:
//: 3 Test a variety of numbers in base 0 to check if they detect the
//: correct base
//
// Testing:
// float stof(const string& str, std::size_t* pos =0);
// float stof(const wstring& str, std::size_t* pos =0);
// double stod(const string& str, std::size_t* pos =0);
// double stod(const wstring& str, std::size_t* pos =0);
// long double stold(const string& str, std::size_t* pos =0);
// long double stold(const wstring& str, std::size_t* pos =0);
// ------------------------------------------------------------------------
static const struct {
int d_lineNum; // source line number
const char *d_input; // input
size_t d_pos; // position of character after the
// numeric value
double d_spec; // specifications
} DATA[] = {
//line input pos spec
//---- ----- --- ----
{ L_, "0", 1, 0},
{ L_, "-0", 2, 0},
{ L_, "3.145gg", 5, 3.145},
{ L_, " -5.9991", 11, -5.9991},
{ L_, "10e1", 4, 1e2},
{ L_, "10p2", 2, 10},
#if !(defined(BSLS_PLATFORM_OS_SUNOS) || defined(BSLS_PLATFORM_OS_SOLARIS) || \
(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR <=1800))
{ L_, "0xf.f", 5, 15.937500},
#endif
#if __cplusplus >= 201103L
{ L_, "inF", 3, std::numeric_limits
<double>::infinity()},
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("Testing stof, stod and stold with strings.\n");
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *INPUT = DATA[ti].d_input;
const int POS = DATA[ti].d_pos;
double SPEC = DATA[ti].d_spec;
string inV(INPUT);
{
float value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stof(inV, sz_null);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stof(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stof(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
{
double value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stod(inV, sz_null);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stod(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stod(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#if !(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR < 1800)
{
double value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stold(inV, sz_null);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stold(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stold(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#endif
}
static const struct {
int d_lineNum; // source line number
const wchar_t *d_input; // input
size_t d_pos; // position of character after the
// numeric value
double d_spec; // specifications
} WDATA[] = {
//line input pos spec
//---- ----- --- ----
{ L_, L"0", 1, 0},
{ L_, L"-0", 2, 0},
{ L_, L"3.145gg", 5, 3.145},
{ L_, L" -5.9991", 11, -5.9991},
{ L_, L"10e1", 4, 1e2},
{ L_, L"10p2", 2, 10},
#if !(defined(BSLS_PLATFORM_OS_SUNOS) || defined(BSLS_PLATFORM_OS_SOLARIS) || \
(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR <=1800))
{ L_, L"0xf.f", 5, 15.937500},
#endif
#if __cplusplus >= 201103L
{ L_, L"inF", 3, std::numeric_limits
<double>::infinity()},
#endif
};
const int NUM_WDATA = sizeof WDATA / sizeof *WDATA;
if (verbose) printf("Testing stof, stod and stold with wstrings.\n");
for (int ti = 0; ti < NUM_WDATA; ++ti) {
const int LINE = WDATA[ti].d_lineNum;
const wchar_t *INPUT = WDATA[ti].d_input;
const int POS = WDATA[ti].d_pos;
double SPEC = WDATA[ti].d_spec;
wstring inV(INPUT);
{
float value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stof(inV, sz_null);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stof(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stof(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, value, (float)SPEC, value == (float)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
{
double value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stod(inV, sz_null);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stod(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stod(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, value, (double)SPEC, value == (double)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#if !((defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR < 1800) \
|| defined(BSLS_PLATFORM_CMP_IBM))
// IBM has rounding issues in 'wcstold' that stop
// 'value == (long double)SPEC' from evaluating to true.
{
double value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stold(inV, sz_null);
LOOP3_ASSERT (ti, (double)value, (double)SPEC,
value == (long double)SPEC);
ASSERT (sz_null == NULL);
value = bsl::stold(inV, sz_valid_ptr);
LOOP3_ASSERT (ti, (double)value, (double)SPEC,
value == (long double)SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stold(inV, &sz_valid_nonptr);
LOOP3_ASSERT (ti, (double)value, (double)SPEC,
value == (long double)SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#endif
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase30(){
// ------------------------------------------------------------------------
// TESTING 'stoi', 'stol', 'stoll'
//
// Concerns:
//: 1 'stoi', 'stol', 'stoll' parse the string properly into proper integer
//:
//: 2 The methods discard leading white space characters and create largest
//: valid integral number
//:
//: 3 Detects the correct base if the base is 0
//:
//: 4 The 'stoX' functions handle null pointers to 'pos' correctly
//
// Plan:
//: 1 Use stoi, stol, and stoll on a variety of valid value to ensure
//: that the methods parse correctly (C-1)
//:
//: 2 Try to convert partially valid strings, ie strings that contain
//: characters that are not valid in the base of the number.
//:
//: 3 Test a variety of numbers in base 0 to check if they detect the
//: correct base
//
// Testing:
// int stoi(const string& str, std::size_t* pos = 0, int base = 10);
// int stoi(const wstring& str, std::size_t* pos = 0, int base = 10);
// long stol(const string& str, std::size_t* pos = 0, int base = 10);
// long stol(const wstring& str, std::size_t* pos = 0, int base = 10);
// long stoul(const string& str, std::size_t* pos = 0, int base = 10);
// long stoul(const wstring& str, std::size_t* pos = 0, int base = 10);
// long long stoll(const string& str, std::size_t* pos = 0, int base=10);
// long long stoll(const wstring& str, std::size_t* pos= 0, int base=10);
// long long stoull(const string& str,std::size_t* pos = 0, int base=10);
// long long stoull(const wstring& str,std::size_t* pos= 0, int base=10);
// ------------------------------------------------------------------------
static const struct {
int d_lineNum; // source line number
const char *d_input; // input
int d_base; // base of input
size_t d_pos; // position of character after the
// numeric value
long long d_spec; // specifications
} DATA[] = {
//line input base pos spec
//---- ----- ---- --- ----
{ L_, "0", 10, 1, 0 },
{ L_, "-0", 10, 2, 0},
{ L_, "10101", 10, 5, 10101},
{ L_, "-10101", 10, 6, -10101},
{ L_, "32767", 10, 5, 32767},
{ L_, "-32767", 10, 6, -32767},
{ L_, "000032767", 10, 9, 32767},
{ L_, "2147483647", 10, 10, 2147483647},
{ L_, "-2147483647", 10, 11, -2147483647},
{ L_, "4294967295", 10, 10, 4294967295},
{ L_, "9223372036854775807", 10, 19, 9223372036854775807LL},
{ L_, "-9223372036854775807", 10, 20, -9223372036854775807LL},
//test usage of spaces, and non valid characters with in the string
{ L_, " 515", 10, 5, 515},
{ L_, " 515 505050", 10, 5, 515},
{ L_, " 99abc99", 10, 3, 99},
{ L_, " 3.14159", 10, 2, 3},
{ L_, "0x555", 10, 1, 0},
//test different bases
{ L_, "111", 2, 3, 7},
{ L_, "101", 2, 3, 5},
{ L_, "100", 2, 3, 4},
{ L_, "101010101010 ", 2, 12, 2730},
{ L_, "1010101010102 ", 2, 12, 2730},
{ L_, "111111111111111", 2, 15, 32767},
{ L_, "-111111111111111", 2, 16, -32767},
{ L_, "77777", 8, 5, 32767},
{ L_, "-77777", 8, 6, -32767},
{ L_, "7FFF", 16, 4, 32767},
{ L_, "0x7FfF", 16, 6, 32767},
{ L_, "-00000x7FFf", 16, 6, -0},
{ L_, "ZZZZ", 36, 4, 1679615 },
// base zero
{ L_, "79FFZZZf", 0, 2, 79},
{ L_, "0xFfAb", 0, 6, 65451},
{ L_, "05471", 0, 5, 2873},
{ L_, "0X5471", 0, 6, 21617},
{ L_, "5471", 0, 4, 5471},
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("Testing stoi, stol, stoll, stoul and stoull with"
"strings.\n");
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *INPUT = DATA[ti].d_input;
const int BASE = DATA[ti].d_base;
const int POS = DATA[ti].d_pos;
const long long SPEC = DATA[ti].d_spec;
string inV(INPUT);
if (SPEC <= std::numeric_limits<int>::max() &&
SPEC >= std::numeric_limits<int>::min()){
int value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stoi(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoi(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoi(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<long>::max() &&
SPEC >= std::numeric_limits<long>::min()){
long value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stol(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stol(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stol(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<unsigned long>::max()&& SPEC >= 0){
unsigned long value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stoul(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoul(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoul(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#if !(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR < 1800)
if (SPEC <= std::numeric_limits<long long>::max()){
long long value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stoll(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoll(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoll(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<unsigned long long>::max()
&& SPEC >= 0){
unsigned long long value;
std::string::size_type *sz_null = NULL;
std::string::size_type *sz_valid_ptr =new std::string::size_type();
std::string::size_type sz_valid_nonptr;
value = bsl::stoull(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoull(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoull(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#endif
}
static const struct {
int d_lineNum; // source line number
const wchar_t *d_input; // input
int d_base; // base of input
size_t d_pos; // position of character after the
// numeric value
long long d_spec; // specifications
} WDATA[] = {
//line input base pos spec
//---- ----- ---- --- ----
{ L_, L"0", 10, 1, 0 },
{ L_, L"-0", 10, 2, 0},
{ L_, L"10101", 10, 5, 10101},
{ L_, L"-10101", 10, 6, -10101},
{ L_, L"32767", 10, 5, 32767},
{ L_, L"-32767", 10, 6, -32767},
{ L_, L"000032767", 10, 9, 32767},
{ L_, L"2147483647", 10, 10, 2147483647},
{ L_, L"-2147483647", 10, 11, -2147483647},
{ L_, L"4294967295", 10, 10, 4294967295},
{ L_, L"9223372036854775807", 10, 19, 9223372036854775807LL},
{ L_, L"-9223372036854775807", 10, 20, -9223372036854775807LL},
//test usage of spaces, and non valid characters with in the string
{ L_, L" 515", 10, 5, 515},
{ L_, L" 515 505050", 10, 5, 515},
{ L_, L" 99abc99", 10, 3, 99},
{ L_, L" 3.14159", 10, 2, 3},
{ L_, L"0x555", 10, 1, 0},
//test different bases
{ L_, L"111", 2, 3, 7},
{ L_, L"101", 2, 3, 5},
{ L_, L"100", 2, 3, 4},
{ L_, L"101010101010 ", 2, 12, 2730},
{ L_, L"1010101010102 ", 2, 12, 2730},
{ L_, L"111111111111111", 2, 15, 32767},
{ L_, L"-111111111111111", 2, 16, -32767},
{ L_, L"77777", 8, 5, 32767},
{ L_, L"-77777", 8, 6, -32767},
{ L_, L"7FFF", 16, 4, 32767},
{ L_, L"0x7FfF", 16, 6, 32767},
{ L_, L"-00000x7FFf", 16, 6, -0},
{ L_, L"ZZZZ", 36, 4, 1679615 },
// base zero
{ L_, L"79FFZZZf", 0, 2, 79},
{ L_, L"0xFfAb", 0, 6, 65451},
{ L_, L"05471", 0, 5, 2873},
{ L_, L"0X5471", 0, 6, 21617},
{ L_, L"5471", 0, 4, 5471},
};
const int NUM_WDATA = sizeof WDATA / sizeof *WDATA;
if (verbose) printf("Testing stoi, stol, stoll, stoul and stoull with"
"wstrings.\n");
for (int ti = 0; ti < NUM_WDATA; ++ti) {
const int LINE = WDATA[ti].d_lineNum;
const wchar_t *INPUT = WDATA[ti].d_input;
const int BASE = WDATA[ti].d_base;
const int POS = WDATA[ti].d_pos;
const long long SPEC = WDATA[ti].d_spec;
wstring inV(INPUT);
if (SPEC <= std::numeric_limits<int>::max() &&
SPEC >= std::numeric_limits<int>::min()){
int value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stoi(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoi(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoi(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<long>::max() &&
SPEC >= std::numeric_limits<long>::min()){
long value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stol(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stol(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stol(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<unsigned long>::max() && SPEC >= 0){
unsigned long value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stoul(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoul(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoul(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#if !(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VER_MAJOR < 1800)
if (SPEC <= std::numeric_limits<long long>::max()){
long long value;
std::cout<< "spec "<< SPEC <<std::endl;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stoll(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoll(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
P_(*sz_valid_ptr); P(POS);
value = bsl::stoll(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
P_(sz_valid_nonptr); P(POS);
delete sz_valid_ptr;
}
if (SPEC <= std::numeric_limits<unsigned long long>::max()
&& SPEC >= 0){
unsigned long long value;
std::wstring::size_type *sz_null = NULL;
std::wstring::size_type *sz_valid_ptr =
new std::wstring::size_type();
std::wstring::size_type sz_valid_nonptr;
value = bsl::stoull(inV, sz_null, BASE);
ASSERT (value == SPEC);
ASSERT (sz_null == NULL);
value = bsl::stoull(inV, sz_valid_ptr, BASE);
ASSERT (value == SPEC);
ASSERT (*sz_valid_ptr == POS);
value = bsl::stoull(inV, &sz_valid_nonptr, BASE);
ASSERT (value == SPEC);
ASSERT (sz_valid_nonptr == POS);
delete sz_valid_ptr;
}
#endif
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase29()
{
// --------------------------------------------------------------------
// TESTING 'hashAppend'
// Verify that the hashAppend function works properly and is picked
// up by 'bslh::Hash'
//
// Concerns:
//: 1 'bslh::Hash' picks up 'hashAppend(string)' and can hash strings
//:
//: 2 'hashAppend' hashes the entire string, regardless of 'char' or
//: 'wchar'
//:
//: 3 Empty strings can be hashed
//:
//: 4 Hash is not computed on data beyond the end of very short strings
//
// Plan:
//: 1 Use 'bslh::Hash' to hash a few values of strings with each char type.
//: (C-1,2)
//:
//: 2 Hash an empty string. (C-3)
//:
//: 3 Hash two very short strings with the same value and assert that they
//: produce equal hashes. (C-4)
//
// Testing:
// hashAppend(HASHALG& hashAlg, const basic_string& str);
// hashAppend(HASHALG& hashAlg, const native_std::basic_string& str);
// --------------------------------------------------------------------
typedef ::BloombergLP::bslh::Hash<> Hasher;
typedef typename Hasher::result_type HashType;
typedef native_std::basic_string<TYPE,TRAITS,ALLOC> NativeObj;
const int PRIME = 100003; // Arbitrary large prime to be used in hash-table
// like testing
int collisions[PRIME] = {};
int nativeCollisions[PRIME] = {};
Hasher hasher;
size_t prevHash = 0;
HashType hash = 0;
if (verbose) printf("Use 'bslh::Hash' to hash a few values of strings with"
" each char type. (C-1,2)\n");
{
for (int i = 0; i != PRIME; ++i) {
Obj num;
if (i > 66000){
//Make sure we're testing long strings
for (int j = 0; j < 40; ++j) {
num.push_back(TYPE('A'));
}
}
else if (i > 33000) {
//Make sure we're testing with null characters in the strings
for (int j = 0; j < 5; ++j) {
num.push_back(TYPE('A'));
num.push_back(TYPE('\0'));
}
}
num.push_back( TYPE('0' + (i/1000000) ));
num.push_back( TYPE('0' + (i/100000) %10 ));
num.push_back( TYPE('0' + (i/10000) %10 ));
num.push_back( TYPE('0' + (i/1000) %10 ));
num.push_back( TYPE('0' + (i/100) %10 ));
num.push_back( TYPE('0' + (i/10) %10 ));
num.push_back( TYPE('0' + (i) %10 ));
if (veryVerbose) dbg_print("Testing hash of ", num.data(), "\n");
prevHash = hash;
hash = hasher(num);
// Check consecutive values are not hashing to the same hash
ASSERT(prevHash != hash);
// Check that minimal collisions are happening
ASSERT(++collisions[hash % PRIME] <= 11); // Choose 11 as a max
// number collisions
Obj numCopy = num;
// Verify same hash is produced for the same value
ASSERT(num == numCopy);
ASSERT(hash == hasher(numCopy));
}
}
if (verbose) printf("Use 'bslh::Hash' to hash a few values of 'native_std'"
" strings with each char type. (C-1,2)\n");
{
for (int i = 0; i != PRIME; ++i) {
NativeObj num;
if (i > 66000){
//Make sure we're testing long strings
for (int j = 0; j < 40; ++j) {
num.push_back(TYPE('A'));
}
}
else if (i > 33000) {
//Make sure we're testing with null characters in the strings
for (int j = 0; j < 5; ++j) {
num.push_back(TYPE('A'));
num.push_back(TYPE('\0'));
}
}
num.push_back( TYPE('0' + (i/1000000) ));
num.push_back( TYPE('0' + (i/100000) %10 ));
num.push_back( TYPE('0' + (i/10000) %10 ));
num.push_back( TYPE('0' + (i/1000) %10 ));
num.push_back( TYPE('0' + (i/100) %10 ));
num.push_back( TYPE('0' + (i/10) %10 ));
num.push_back( TYPE('0' + (i) %10 ));
if (veryVerbose) dbg_print("Testing hash of ", num.data(), "\n");
prevHash = hash;
hash = hasher(num);
// Check consecutive values are not hashing to the same hash
ASSERT(prevHash != hash);
// Check that minimal collisions are happening
ASSERT(++nativeCollisions[hash % PRIME] <= 11);
// Choose 11 as a max
// number collisions
NativeObj numCopy = num;
// Verify same hash is produced for the same value
ASSERT(num == numCopy);
ASSERT(hash == hasher(numCopy));
}
}
if (verbose) printf("Hash an empty string. (C-3)\n");
{
Obj empty;
ASSERT(hasher(empty));
}
if (verbose) printf("Hash two very short strings with the same value and"
" assert that they produce equal hashes. (C-4)\n");
{
Obj small1;
Obj small2;
small1.push_back( TYPE('0') );
small2.push_back( TYPE('0') );
ASSERT(hasher(small1) == hasher(small2));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase28()
{
// --------------------------------------------------------------------
// TESTING THE SHORT STRING OPTIMIZATION
//
// Concerns:
// 1) String should have an initial non-zero capacity (short string
// buffer).
// 2) It shouldn't allocate up to that capacity.
// 3) It should work with the char_type larger than the short string
// buffer.
// 4) A Long string with length smaller than the size of the short string
// buffer copied to a new string should produce a short new string.
// 5) It should work with the NULL-terminator different from '\0' to make
// sure that the implementation always uses char_type() default
// constructor to terminate the string rather than a null literal.
//
// Plan:
// 1) Construct an empty string and check its capacity.
// 2) Construct strings with lengths from 0 to N (where N > initial
// capacity) and verify that the string class allocates when the string
// length becomes larger than the short string buffer.
// 3) Instantiate the string class with 'UserChar' char type and run it
// through this test. 'UserChar' is parameterized with size from 1 to
// 8 words.
// 4) Construct a long string. Erase some characters from it, so the
// length becomes smaller than the size of the short string buffer.
// Then make a copy of this string using the test allocator and verify
// that the new copy did not need any new memory.
// 5) Make 'UserChar' default value something other than '\0'. Make sure
// that strings of different lengths terminate with 'UserChar()' value
// rather than '\0'.
// ------------------------------------------------------------------------
if (verbose) printf("\nString has a non-zero initial capacity.\n");
{
Obj emptyStr;
ASSERT(emptyStr.capacity() == DEFAULT_CAPACITY);
}
if (verbose) printf("\nString doesn't allocate while it uses the short "
"string buffer.\n");
{
// make some reasonable number of test iterations
const size_t specSize = 2 * DEFAULT_CAPACITY > 10
? 2 * DEFAULT_CAPACITY
: 10;
char spec[specSize];
for (size_t size = 1; size < specSize; ++size) {
// construct the spec string
for (size_t i = 0; i < size; ++i) {
spec[i] = (i & 1) ? 'A' : 'B';
}
spec[size] = '\0';
// check if the string allocates
bslma::TestAllocator testAllocator(veryVeryVerbose);
Obj str(g(spec), &testAllocator);
// allocates only if larger than the short string buffer
ASSERT((size <= DEFAULT_CAPACITY) ==
(testAllocator.numBytesInUse() == 0));
ASSERT((size <= DEFAULT_CAPACITY) ==
(testAllocator.numBlocksTotal() == 0));
// check if copy-constructor allocates
Obj strCpy(str, &testAllocator);
ASSERT((size <= DEFAULT_CAPACITY)
== (testAllocator.numBytesInUse() == 0));
ASSERT((size <= DEFAULT_CAPACITY)
== (testAllocator.numBlocksTotal() == 0));
// check that copying a long string with a short length results in
// a short string
if (str.size() > DEFAULT_CAPACITY) {
Obj strLong(str);
size_t oldCapacity = strLong.capacity();
// remove some characters from the string to shorten it
strLong.erase(0, strLong.size() - DEFAULT_CAPACITY);
// check that 'erase' did not change the capacity
ASSERT(strLong.capacity() == oldCapacity);
// check that copying produces a short string now and that it
// doesn't allocate
bslma::TestAllocator testAllocatorShort(veryVeryVerbose);
Obj strShort(strLong, &testAllocatorShort);
ASSERT(testAllocatorShort.numBytesInUse() == 0);
ASSERT(testAllocatorShort.numBlocksTotal() == 0);
}
// check that the string is terminated properly with 'TYPE()' value
// rather than just '\0'
ASSERT(*(str.c_str() + str.size()) == TYPE());
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase26()
{
// --------------------------------------------------------------------
// TESTING CONVERSIONS WITH NATIVE STRINGS
//
// Testing:
// CONCERNS:
// - A bsl::basic_string is implicitly convertible to a
// native_std::basic_string with the same CHAR_TYPE and
// CHAR_TRAITS.
// - A native_std::basic_string is explicitly convertible to a
// bsl::basic_string with the same CHAR_TYPE and
// CHAR_TRAITS.
// - A bsl::basic_string and a native_std::basic_string with the
// same template parameters will have the same npos value.
//
// Plan:
// For a variety of strings of different sizes and different values, test
// that the string is implicitly convertible to native_std::string and
// that the conversion yields the same value. Test that one can
// construct a bsl::string from the native_std::string. Test that
// bslstl::string::npos compares equal to native_std::string::npos.
//
// Testing:
// npos
// operator native_stl::basic_string<CHAR, CHAR_TRAITS, ALLOC2>() const;
// basic_string(const native_stl::basic_string<CHAR,
// CHAR_TRAITS,
// ALLOC2>&);
// ------------------------------------------------------------------------
static const char *SPECS[] = {
"",
"A",
"AA",
"ABA",
"ABB",
"AAAAABAAAAAAAAA",
0 // null string required as last element
};
typedef LimitAllocator<ALLOC> AltAlloc;
typedef native_std::basic_string<TYPE, TRAITS, ALLOC> NativeObj;
typedef native_std::basic_string<TYPE, TRAITS, AltAlloc> NativeObjAlt;
if (verbose) printf("\tTesting npos\n");
LOOP2_ASSERT(Obj::npos, NativeObj::npos, Obj::npos == NativeObj::npos);
if (verbose) printf("\tTesting conversion to native string\n");
{
// Create first object
for (int si = 0; SPECS[si]; ++si) {
const char *const U_SPEC = SPECS[si];
const Obj U(g(U_SPEC));
if (veryVerbose) {
T_; T_; P_(U_SPEC); P(U);
}
NativeObjAlt v;
const NativeObjAlt& V = v;
ASSERT(! isNativeString(U));
ASSERT( isNativeString(V));
v = U; // Assignment requires implicit conversion
const NativeObjAlt V2(U); // implicit Conversion
const NativeObjAlt V3 = U; // implicit Conversion
ASSERT(Obj(V.c_str()) == Obj(U.c_str()));
const Obj U2(V); // Explicit conversion construction
ASSERT(Obj(V.c_str()) == Obj(U2.c_str()));
ASSERT(U2 == U);
// 'operator=='
ASSERT(V == U);
ASSERT(U == V);
// 'operator!='
ASSERT(!(V != U));
ASSERT(!(U != V));
for (int sj = 0; SPECS[sj]; ++sj) {
const char *const X_SPEC = SPECS[sj];
const Obj X(g(X_SPEC));
if (veryVerbose) {
T_; T_; T_; P_(X_SPEC); P(X);
}
// Since free operators for the case when both arguments are
// 'bsl::string' is thoroughly tested already, we can compare
// the results of 'std::string < bsl::string' against
// 'bsl::string < bsl::string', etc...
ASSERT((U < X) == (V < X));
ASSERT((X < U) == (X < V));
ASSERT((U > X) == (V > X));
ASSERT((X > U) == (X > V));
ASSERT((U <= X) == (V <= X));
ASSERT((X <= U) == (X <= V));
ASSERT((U >= X) == (V >= X));
ASSERT((X >= U) == (X >= V));
ASSERT((U + X) == (V + X));
ASSERT((X + U) == (X + V));
ASSERT((U + X) == (V + X));
ASSERT((X + U) == (X + V));
}
}
}
if (verbose) printf("\tTesting conversion from native string\n");
{
// Create first object
for (int si = 0; SPECS[si]; ++si) {
const char *const U_SPEC = SPECS[si];
const Obj U(g(U_SPEC));
NativeObjAlt v; const NativeObjAlt& V = v;
v = U;
if (veryVerbose) {
T_; T_; P_(U_SPEC); P(U);
}
ASSERT(!isNativeString(U));
ASSERT( isNativeString(V));
Obj bslString;
bslString = V; // Assignment requires implicit conversion
ASSERT(Obj(bslString.c_str()) == Obj(V.c_str()));
const Obj U2(V); // Explicit conversion construction
ASSERT(Obj(V.c_str()) == Obj(U2.c_str()));
ASSERT(U2 == U);
// 'operator=='
ASSERT(V == U);
ASSERT(U == V);
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase25()
{
// --------------------------------------------------------------------
// TESTING 'std::length_error'
//
// Concerns:
// 1) That any call to a constructor, 'append', 'assign', 'insert',
// 'operator+=', or 'replace' which would result in a value exceeding
// 'max_size()' throws 'std::length_error'.
// 2) That the 'max_size()' taken into consideration is that of the
// allocator, and not an absolute constant.
// 3) That the value of the string is unchanged if an exception is
// thrown.
// 4) That integer overflows are correctly handled when length_error
// exceeds 'Obj::max_size()' (which is the largest representable
// size_type).
//
// Plan:
// For concern 2, we use an allocator wrapper that provides the same
// functionality as 'ALLOC' but changes the return value of 'max_size()'
// to a 'limit' value settable at runtime. Note that the allocator
// 'max_size()' includes the null-terminating char, and so the string
// 'max_size()' is one less than the allocator; in other words, the
// operations throw unless 'length <= limit - 1', i.e., they throw if
// 'limit <= length'.
//
// Construct objects with value large enough that the constructor throws.
// For 'append', 'assign', 'insert', 'operator+=', or 'replace', we
// construct a small (non-empty) object, and use the corresponding
// function to request an increase in size that is guaranteed to result
// in a value exceeding 'max_size()'.
//
// Testing:
// Proper use of 'std::length_error'
// ------------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
LimitAllocator<ALLOC> a(&testAllocator);
a.setMaxSize((size_t)-1);
const size_t LENGTH = 32;
typedef bsl::basic_string<TYPE,TRAITS,LimitAllocator<ALLOC> > LimitObj;
LimitObj mY(LENGTH, DEFAULT_VALUE); // does not throw
const LimitObj& Y = mY;
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nConstructor 'string(str, pos, n, a = A())'.\n");
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(Y, 0, LENGTH, a); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
} catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
} catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nConstructor 'string(C *s, n, a = A())'.\n");
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(Y.c_str(), LENGTH, a); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nConstructor 'string(C *s, a = A())'.\n");
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(Y.c_str(), a); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nConstructor 'string(n, c, a = A())'.\n");
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(LENGTH, DEFAULT_VALUE, a); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nConstructor 'string<Iter>(f, l, a = A())'.\n");
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(Y.begin(), Y.end(), a); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'resize'.\n");
{
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
mX.resize(LENGTH, DEFAULT_VALUE);
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'assign'.\n");
for (int assignMethod = 0; assignMethod <= 5; ++assignMethod) {
if (veryVerbose) {
switch (assignMethod) {
case 0: printf("\tWith assign(str).\n"); break;
case 1: printf("\tWith assign(str, pos, n).\n"); break;
case 2: printf("\tWith assign(C *s, n).n"); break;
case 3: printf("\tWith assign(C *s).\n"); break;
case 4: printf("\tWith assign(n, c).n"); break;
case 5: printf("\tWith assign<Iter>(f, l).\n"); break;
default: ASSERT(0);
};
}
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\t\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
switch (assignMethod) {
case 0: {
mX.assign(Y);
} break;
case 1: {
mX.assign(Y, 0, LENGTH);
} break;
case 2: {
mX.assign(Y.c_str(), LENGTH);
} break;
case 3: {
mX.assign(Y.c_str());
} break;
case 4: {
mX.assign(LENGTH, Y[0]);
} break;
case 5: {
mX.assign(Y.begin(), Y.end());
} break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n",e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'operator+='.\n");
for (int operatorMethod = 0; operatorMethod <= 2; ++operatorMethod) {
if (veryVerbose) {
switch (operatorMethod) {
case 0: printf("\toperator+=(str).\n"); break;
case 1: printf("\toperator+=(C *s).\n"); break;
case 2: printf("\toperator+=(C c).\n"); break;
default: ASSERT(0);
};
}
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\t\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
switch (operatorMethod) {
case 0: {
mX += Y;
} break;
case 1: {
mX += Y.c_str();
} break;
case 2: {
for (size_t i = 0; i < Y.size(); ++i) {
mX += Y[i];
}
} break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'append'.\n");
for (int appendMethod = 0; appendMethod <= 5; ++appendMethod) {
if (verbose) {
switch (appendMethod) {
case 0: printf("\tWith append(str).\n"); break;
case 1: printf("\tWith append(str, pos, n).\n"); break;
case 2: printf("\tWith append(C *s, n).\n"); break;
case 3: printf("\tWith append(C *s).\n"); break;
case 4: printf("\tWith append(n, c).\n"); break;
case 5: printf("\tWith append<Iter>(f, l).\n"); break;
default: ASSERT(0);
};
}
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\t\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
switch (appendMethod) {
case 0: {
mX.append(Y);
} break;
case 1: {
mX.append(Y, 0, LENGTH);
} break;
case 2: {
mX.append(Y.c_str(), LENGTH);
} break;
case 3: {
mX.append(Y.c_str());
} break;
case 4: {
mX.append(LENGTH, DEFAULT_VALUE);
} break;
case 5: {
mX.append(Y.begin(), Y.end());
} break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'insert'.\n");
for (int insertMethod = 0; insertMethod <= 8; ++insertMethod) {
if (verbose) {
switch (insertMethod) {
case 0: printf("\tWith push_back(c).\n"); break;
case 1: printf("\tWith insert(pos, str).\n"); break;
case 2: printf("\tWith insert(pos, str, pos2, n).\n"); break;
case 3: printf("\tWith insert(pos, C *s, n).\n"); break;
case 4: printf("\tWith insert(pos, C *s).\n"); break;
case 5: printf("\tWith insert(pos, n, C c).\n"); break;
case 6: printf("\tWith insert(p, C c).\n"); break;
case 7: printf("\tWith insert(p, n, C c).\n"); break;
case 8: printf("\tWith insert<Iter>(p, f, l).\n"); break;
default: ASSERT(0);
};
}
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\t\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
switch (insertMethod) {
case 0: {
for (size_t i = 0; i < LENGTH; ++i) {
mX.push_back(Y[i]);
}
} break;
case 1: {
mX.insert(0, Y);
} break;
case 2: {
mX.insert(0, Y, 0, LENGTH);
} break;
case 3: {
mX.insert(0, Y.c_str(), LENGTH);
} break;
case 4: {
mX.insert(0, Y.c_str());
} break;
case 5: {
mX.insert((size_t)0, LENGTH, DEFAULT_VALUE);
} break;
case 6: {
for (size_t i = 0; i < LENGTH; ++i) {
mX.insert(mX.begin(), DEFAULT_VALUE);
}
} break;
case 7: {
mX.insert(mX.begin(), LENGTH, DEFAULT_VALUE);
} break;
case 8: {
mX.insert(mX.cbegin(), Y.begin(), Y.end());
} break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'replace'.\n");
for (int replaceMethod = 1; replaceMethod < 8; ++replaceMethod) {
if (verbose) {
switch (replaceMethod) {
case 1: printf("\tWith replace(pos1, n1, str).\n");
break;
case 2: printf("\tWith replace(pos1, n1, str, pos2, n2).\n");
break;
case 3: printf("\tWith replace(pos1, n1, C *s, n2).\n");
break;
case 4: printf("\tWith replace(pos1, n1, C *s).\n");
break;
case 5: printf("\tWith replace(pos1, n1, n2, C c).\n");
break;
case 6: printf("\tWith replace(f, l, const C *s, n2).\n");
break;
case 7: printf("\tWith replace(f, l, n, const C *s).\n");
break;
case 8: printf("\treplace(f, l, n2, C c).\n");
break;
default: ASSERT(0);
};
}
for (size_t limit = LENGTH - 2; limit <= LENGTH + 2; ++limit) {
bool exceptionCaught = false;
a.setMaxSize(limit);
if (veryVerbose)
printf("\t\tWith max_size() equal to limit = " ZU "\n", limit);
try {
LimitObj mX(a);
switch (replaceMethod) {
case 1: {
mX.replace(0, 1, Y);
} break;
case 2: {
mX.replace(0, 1, Y, 0, LENGTH);
} break;
case 3: {
mX.replace(0, 1, Y.c_str(), LENGTH);
} break;
case 4: {
mX.replace(0, 1, Y.c_str());
} break;
case 5: {
mX.replace(0, 1, LENGTH, DEFAULT_VALUE);
} break;
case 6: {
mX.replace(mX.begin(),
mX.end(),
Y.c_str(),
LENGTH);
} break;
case 7: {
mX.replace(mX.begin(), mX.end(), Y.c_str());
} break;
case 8: {
mX.replace(mX.begin(),
mX.end(),
LENGTH, DEFAULT_VALUE);
} break;
default: ASSERT(0);
};
} catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
} catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t \tCaught std::exception(%s).\n", e.what());
}
} catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
LOOP2_ASSERT(limit, exceptionCaught,
(limit <= LENGTH) == exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
const int PADDING = 16;
size_t expMaxSize = -1;
const size_t& EXP_MAX_SIZE = expMaxSize;
{
const Obj X;
expMaxSize = X.max_size();
}
LOOP_ASSERT(EXP_MAX_SIZE, (size_t)-1 > EXP_MAX_SIZE);
if (EXP_MAX_SIZE >= (size_t)-2) {
printf("\n\nERROR: Cannot continue this test case without attempting\n"
"to allocate huge amounts of memory. *** Aborting. ***\n\n");
return; // RETURN
}
const size_t DATA[] = {
EXP_MAX_SIZE + 1,
EXP_MAX_SIZE + 2,
(EXP_MAX_SIZE + 1) / 2 + (size_t)-1 / 2,
(size_t)-2,
(size_t)-1,
0 // must be the last value
};
if (verbose) printf("\nConstructor 'string(n, c, a = A())'"
" and 'max_size()' equal to " ZU ".\n", EXP_MAX_SIZE);
for (int i = 0; DATA[i]; ++i)
{
bool exceptionCaught = false;
if (veryVerbose) printf("\tWith 'n' = " ZU "\n", DATA[i]);
try {
Obj mX(DATA[i], DEFAULT_VALUE); // test here
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\tCaught std::length_error(\"%s\").\n", e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
ASSERT(exceptionCaught);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'reserve/resize' and"
" 'max_size()' equal to " ZU ".\n", EXP_MAX_SIZE);
for (int capacityMethod = 0; capacityMethod < 3; ++capacityMethod)
{
if (verbose) {
switch (capacityMethod) {
case 0: printf("\tWith reserve(n).\n"); break;
case 1: printf("\tWith resize(n).\n"); break;
case 2: printf("\tWith resize(n, C c).\n"); break;
default: ASSERT(0);
};
}
for (int i = 0; DATA[i]; ++i)
{
bool exceptionCaught = false;
if (veryVerbose) printf("\t\tWith 'n' = " ZU "\n", DATA[i]);
try {
Obj mX;
switch (capacityMethod) {
case 0: mX.reserve(DATA[i]); break;
case 1: mX.resize(DATA[i]); break;
case 2: mX.resize(DATA[i], DEFAULT_VALUE); break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
ASSERT(exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'append' and 'max_size()' equal to " ZU ".\n",
EXP_MAX_SIZE);
for (int appendMethod = 4; appendMethod <= 4; ++appendMethod) {
if (verbose) {
switch (appendMethod) {
case 4: printf("\tWith append(n, c).\n"); break;
default: ASSERT(0);
};
}
for (int i = 0; DATA[i]; ++i) {
bool exceptionCaught = false;
if (veryVerbose)
printf("\t\tCreating string of length " ZU ".\n", DATA[i]);
try {
Obj mX(PADDING, DEFAULT_VALUE, a);
mX.append(DATA[i] - PADDING, DEFAULT_VALUE);
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
ASSERT(exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'insert' and 'max_size()' equal to " ZU ".\n",
EXP_MAX_SIZE);
for (int insertMethod = 5; insertMethod <= 7; insertMethod += 2) {
if (verbose) {
switch (insertMethod) {
case 5: printf("\tWith insert(pos, n, C c).\n"); break;
case 7: printf("\tWith insert(p, n, C c).\n"); break;
default: ASSERT(0);
};
}
for (int i = 0; DATA[i]; ++i) {
bool exceptionCaught = false;
if (veryVerbose)
printf("\t\tCreating string of length " ZU ".\n", DATA[i]);
try {
Obj mX(PADDING, DEFAULT_VALUE, a);
const size_t LENGTH = DATA[i] - PADDING;
switch (insertMethod) {
case 5: {
mX.insert((size_t)0, LENGTH, DEFAULT_VALUE);
} break;
case 7: {
mX.insert(mX.begin(), LENGTH, DEFAULT_VALUE);
} break;
default: ASSERT(0);
};
}
catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
}
catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught std::exception(%s).\n", e.what());
}
}
catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t\tCaught unknown exception.\n");
}
}
ASSERT(exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
if (verbose) printf("\nWith 'replace' and 'max_size()' equal to " ZU ".\n",
EXP_MAX_SIZE);
for (int replaceMethod = 5; replaceMethod <= 8; replaceMethod += 3) {
if (verbose) {
switch (replaceMethod) {
case 5: printf("\tWith replace(pos1, n1, n2, C c).\n");
break;
case 8: printf("\tWith replace(f, l, n2, C c).\n");
break;
default: ASSERT(0);
};
}
for (int i = 0; DATA[i]; ++i) {
bool exceptionCaught = false;
if (veryVerbose)
printf("\t\tCreating string of length " ZU ".\n", DATA[i]);
try {
Obj mX(3 * PADDING, DEFAULT_VALUE);
const size_t LENGTH = DATA[i] - PADDING;
switch (replaceMethod) {
case 5: {
mX.replace(PADDING, PADDING,
LENGTH, DEFAULT_VALUE);
} break;
case 8: {
mX.replace(mX.begin() + PADDING,
mX.begin() + 2 * PADDING,
LENGTH, DEFAULT_VALUE);
} break;
default: ASSERT(0);
};
} catch (std::length_error& e) {
if (veryVerbose) {
printf("\t\t\tCaught std::length_error(\"%s\").\n",
e.what());
}
exceptionCaught = true;
} catch (std::exception& e) {
ASSERT(0);
if (veryVerbose) {
printf("\t\t \tCaught std::exception(%s).\n", e.what());
}
} catch (...) {
ASSERT(0);
if (veryVerbose) {
printf("\t\tCaught unknown exception.\n");
}
}
ASSERT(exceptionCaught);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBytesInUse());
#endif
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase24()
{
// --------------------------------------------------------------------
// TESTING COMPARISONS
//
// Concerns:
// 1) 'operator<' returns the lexicographic comparison on two arrays.
// 2) 'operator>', 'operator<=', and 'operator>=' are correctly tied to
// 'operator<'.
// 3) 'compare' returns the correct result.
// 4) That traits get selected properly.
//
// Plan:
// For a variety of strings of different sizes and different values, test
// that the comparison returns as expected. Note that capacity is not of
// concern here, the implementation specifically uses only 'begin()',
// 'end()', and 'size()'. For concern 4, use 'TRAITS::compare()'
// explicitly in the 'check_compare' helper function, and check that the
// return value has not only the correct sign, but the same value as
// well.
//
// Testing:
// int compare(const string& str) const;
// int compare(pos1, n1, const string& str) const;
// int compare(pos1, n1, const string& str, pos2, n2) const;
// int compare(const C* s) const;
// int compare(pos1, n1, const C* s) const;
// int compare(pos1, n1, const C* s, n2) const;
// bool operator<(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator<(const C *, const string<C,CT,A>&);
// bool operator<(const string<C,CT,A>&, const C *);
// bool operator>(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator>(const C *, const string<C,CT,A>&);
// bool operator>(const string<C,CT,A>&, const C *);
// bool operator<=(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator<=(const C *, const string<C,CT,A>&);
// bool operator<=(const string<C,CT,A>&, const C *);
// bool operator>=(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator>=(const C *, const string<C,CT,A>&);
// bool operator>=(const string<C,CT,A>&, const C *);
// ------------------------------------------------------------------------
static const char *SPECS[] = {
"",
"A",
"AA",
"AAA",
"AAAA",
"AAAAA",
"AAAAAA",
"AAAAAAA",
"AAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAAA",
"AAAAAAAAAAA",
"AAAAAAAAAAAA",
"AAAAAAAAAAAAA",
"AAAAAAAAAAAAAA",
"AAAAAAAAAAAAAAA",
"AAAAAB",
"AAAAABA",
"AAAAABAA",
"AAAAABAAA",
"AAAAABAAAA",
"AAAAABAAAAA",
"AAAAABAAAAAA",
"AAAAABAAAAAAA",
"AAAAABAAAAAAAA",
"AAAAABAAAAAAAAA",
"AAAAB",
"AAAABAAAAAA",
"AAAABAAAAAAA",
"AAAABAAAAAAAA",
"AAAABAAAAAAAAA",
"AAAABAAAAAAAAAA",
"AAAB",
"AAABA",
"AAABAA",
"AAABAAAAAA",
"AAB",
"AABA",
"AABAA",
"AABAAA",
"AABAAAAAA",
"AB",
"ABA",
"ABAA",
"ABAAA",
"ABAAAAAA",
"B",
"BA",
"BAA",
"BAAA",
"BAAAA",
"BAAAAA",
"BAAAAAA",
"BB",
0 // null string required as last element
};
if (verbose) printf("\tTesting free operators <, >, <=, >=.\n");
if (veryVerbose) printf("\tCompare each pair of similar and different"
" values (u, v) in S X S.\n");
{
// Create first object
for (int si = 0; SPECS[si]; ++si) {
const char *const U_SPEC = SPECS[si];
const Obj U(g(U_SPEC));
if (veryVerbose) {
T_; T_; P_(U_SPEC); P(U);
}
// Create second object
for (int sj = 0; SPECS[sj]; ++sj) {
const char *const V_SPEC = SPECS[sj];
const Obj V(g(V_SPEC));
if (veryVerbose) {
T_; T_; P_(V_SPEC); P(V);
}
// First comparisons with 'string' objects
const bool isLess = si < sj;
const bool isLessEq = !(sj < si);
LOOP2_ASSERT(si, sj, isLess == (U < V));
LOOP2_ASSERT(si, sj, !isLessEq == (U > V));
LOOP2_ASSERT(si, sj, isLessEq == (U <= V));
LOOP2_ASSERT(si, sj, !isLess == (U >= V));
// Then test comparisons with C-strings
LOOP2_ASSERT(si, sj, isLess == (U.c_str() < V));
LOOP2_ASSERT(si, sj, !isLessEq == (U.c_str() > V));
LOOP2_ASSERT(si, sj, isLessEq == (U.c_str() <= V));
LOOP2_ASSERT(si, sj, !isLess == (U.c_str() >= V));
LOOP2_ASSERT(si, sj, isLess == (U < V.c_str()));
LOOP2_ASSERT(si, sj, !isLessEq == (U > V.c_str()));
LOOP2_ASSERT(si, sj, isLessEq == (U <= V.c_str()));
LOOP2_ASSERT(si, sj, !isLess == (U >= V.c_str()));
}
}
}
if (verbose) printf("\tTesting 'compare'.\n");
if (veryVerbose) printf("\tCompare each substring previous.\n");
{
// Create first object
for (int si = 0; SPECS[si]; ++si) {
const char *const U_SPEC = SPECS[si];
const size_t U_LEN = strlen(U_SPEC);
const Obj U(g(U_SPEC));
if (veryVerbose) {
T_; T_; P_(U_SPEC); P(U);
}
// Create second object
for (int sj = 0; SPECS[sj]; ++sj) {
const char *const V_SPEC = SPECS[sj];
const size_t V_LEN = strlen(V_SPEC);
const Obj V(g(V_SPEC));
if (veryVerbose) {
T_; T_; P_(V_SPEC); P(V);
}
checkCompare(U, V, U.compare(V));
checkCompare(U, V, U.compare(V.c_str()));
for (size_t i = 0; i <= U_LEN; ++i) {
for (size_t j = 0; j <= V_LEN; ++j) {
const Obj U1(U, i, 1);
const Obj UN(U, i, U_LEN);
const Obj V1(V, j, 1);
const Obj VN(V, j, V_LEN);
checkCompare(U1, V, U.compare(i, 1, V));
checkCompare(U1, V1, U.compare(i, 1, V, j, 1));
checkCompare(U1, VN, U.compare(i, 1, V, j, V_LEN));
checkCompare(U1, V, U.compare(i, 1, V));
checkCompare(U1, V1, U.compare(i, 1, V, j, 1));
checkCompare(U1, VN, U.compare(i, 1, V, j, V_LEN));
checkCompare(UN, V, U.compare(i, U_LEN, V));
checkCompare(UN, V1, U.compare(i, U_LEN, V, j, 1));
checkCompare(UN, VN, U.compare(i, U_LEN, V, j, V_LEN));
checkCompare(UN, V, U.compare(i, U_LEN, V));
checkCompare(UN, V1, U.compare(i, U_LEN, V, j, 1));
checkCompare(UN, VN, U.compare(i, U_LEN, V, j, V_LEN));
}
}
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase24Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING COMPARISONS
//
// Concerns:
// 1 'compare' asserts on undefined behavior when it's passed a NULL
// C-string pointer.
// 2 comparison free operator overloads assert on undefined behavior when
// they are passed a NULL C-string pointer.
//
// Plan:
// For each 'compare' method overload, create a non-empty string and test
// 'compare' with a NULL C-string pointer parameter.
//
// For each comparison free-function overload, do the same as for
// 'compare' method.
//
// Testing:
// int compare(const C* s) const;
// int compare(pos1, n1, const C* s) const;
// int compare(pos1, n1, const C* s, n2) const;
// bool operator<(const C *s, const string<C,CT,A>& str);
// bool operator<(const string<C,CT,A>& str, const C *s);
// bool operator>(const C *s, const string<C,CT,A>& str);
// bool operator>(const string<C,CT,A>& str, const C *s);
// bool operator<=(const C *s, const string<C,CT,A>& str);
// bool operator<=(const string<C,CT,A>& str, const C *s);
// bool operator>=(const C *s, const string<C,CT,A>& str);
// bool operator>=(const string<C,CT,A>& str, const C *s);
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
Obj mX(g("ABCDE"));
const Obj& X = mX;
const TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
if (veryVerbose) printf("\tcompare(s)\n");
{
ASSERT_SAFE_FAIL(X.compare(nullStr));
ASSERT_SAFE_PASS(X.compare(X.c_str()));
}
if (veryVerbose) printf("\tcompare(pos1, n1, s)\n");
{
ASSERT_SAFE_FAIL(X.compare(0, X.size(), nullStr));
ASSERT_SAFE_PASS(X.compare(0, X.size(), X.c_str()));
}
if (veryVerbose) printf("\tcompare(pos1, n1, s, n2)\n");
{
ASSERT_SAFE_FAIL(X.compare(0, X.size(), nullStr, X.size()));
ASSERT_SAFE_PASS(X.compare(0, X.size(), X.c_str(), X.size()));
}
if (veryVerbose) printf("\toperator<\n");
{
ASSERT_SAFE_FAIL(X < nullStr);
ASSERT_SAFE_FAIL(nullStr < X);
ASSERT_SAFE_PASS(X < X.c_str());
ASSERT_SAFE_PASS(X.c_str() < X);
}
if (veryVerbose) printf("\toperator>\n");
{
ASSERT_SAFE_FAIL(X > nullStr);
ASSERT_SAFE_FAIL(nullStr > X);
ASSERT_SAFE_PASS(X > X.c_str());
ASSERT_SAFE_PASS(X.c_str() > X);
}
if (veryVerbose) printf("\toperator<=\n");
{
ASSERT_SAFE_FAIL(X <= nullStr);
ASSERT_SAFE_FAIL(nullStr >= X);
ASSERT_SAFE_PASS(X <= X.c_str());
ASSERT_SAFE_PASS(X.c_str() <= X);
}
if (veryVerbose) printf("\toperator>=\n");
{
ASSERT_SAFE_FAIL(X >= nullStr);
ASSERT_SAFE_FAIL(nullStr >= X);
ASSERT_SAFE_PASS(X >= X.c_str());
ASSERT_SAFE_PASS(X.c_str() >= X);
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase23()
{
// --------------------------------------------------------------------
// TESTING SUBSTRING
// We have the following concerns:
// 1) That the 'substr' and 'copy' operations have the correct behavior
// and return value, cases where 'n' is smaller than, equal to, or
// larger than 'length() - pos'.
// 2. That 'substr' and 'copy' throw 'std::out_of_range' when passed an
// out-of-bound position.
// 3) That 'copy' does not overwrite beyond the buffer boundaries.
//
// Plan:
// For a set of string values, create the substring using the already
// tested constructors, and compare the results to those constructed
// substrings, with 'n' being either 0, 1 (smaller than 'length() - pos'
// whenever there are remaining characters), 'length() - pos' exactly,
// and 'length() + 1' and 'npos'. Leave padding on both ends for the
// 'copy' buffer and verify that padding has not been written into.
//
// Testing:
// string substr(pos, n) const;
// size_type copy(char *s, n, pos = 0) const;
// ------------------------------------------------------------------------
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const int MAX_LEN = 128;
TYPE buffer[MAX_LEN];
const size_t npos = Obj::npos; // note: NPOS is a system macro
static const struct {
int d_lineNum; // source line number
const char *d_spec; // specifications
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDE" }, // 5
{ L_, "ABCDEA" }, // 6
{ L_, "ABCDEAB" }, // 7
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABCD" }, // 14
{ L_, "ABCDEABCDEABCDE" }, // 15
{ L_, "ABCDEABCDEABCDEA" }, // 16
{ L_, "ABCDEABCDEABCDEAB" }, // 17
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEA" }, // 31
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB" }, // 32
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEABC" }, // 33
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEA" }, // 63
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEAB" }, // 64
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEABC" } // 65
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tTesting substr(pos, n).\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const Obj X(g(SPEC));
if (veryVerbose) {
printf("\tOn a string of length " ZU ":\t", LENGTH); P(SPEC);
}
for (size_t i = 0; i <= LENGTH; ++i) {
const Obj EXP1 = Obj(X, i, 1);
const Obj EXPN = Obj(X, i, LENGTH);
const Obj Y0 = X.substr(i, 0);
LOOP2_ASSERT(LINE, i, Y0.empty());
const Obj Y1 = X.substr(i, 1);
LOOP2_ASSERT(LINE, i, EXP1 == Y1);
const Obj YM = X.substr(i, LENGTH - i);
LOOP2_ASSERT(LINE, i, EXPN == YM);
const Obj YL = X.substr(i, LENGTH + 1);
LOOP2_ASSERT(LINE, i, EXPN == YL);
const Obj YN = X.substr(i, npos);
LOOP2_ASSERT(LINE, i, EXPN == YN);
}
}
}
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\t\tWith exceptions.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const Obj X(g(SPEC));
bool outOfRangeCaught = false;
try {
const Obj Y = X.substr(LENGTH + 1, 0);
ASSERT(0);
}
catch (std::out_of_range) {
outOfRangeCaught = true;
}
LOOP_ASSERT(LINE, outOfRangeCaught);
}
}
#endif
if (verbose) printf("\tTesting copy(s, n, pos).\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const Obj X(g(SPEC));
ASSERT(LENGTH < MAX_LEN - 2);
if (veryVerbose) {
printf("\tOn a string of length " ZU ":\t", LENGTH); P(SPEC);
}
for (size_t i = 0; i <= LENGTH; ++i) {
for (size_t j = 0; j <= LENGTH + 1; ++j) {
for (int k = 0; k < MAX_LEN; ++k) {
buffer[k] = DEFAULT_VALUE;
}
size_t ret = X.copy(buffer + 1, j, i);
size_t m = j < LENGTH - i ? j : LENGTH - i;
LOOP3_ASSERT(LINE, i, j, m == ret);
LOOP3_ASSERT(LINE, i, j, DEFAULT_VALUE == buffer[0]);
for (m = 0; m < j && m < LENGTH - i; ++m) {
LOOP4_ASSERT(LINE, i, j, m, buffer[1 + m] == X[i + m]);
}
LOOP3_ASSERT(LINE, i, j, ret == m);
LOOP3_ASSERT(LINE, i, j, DEFAULT_VALUE == buffer[1 + m]);
}
}
}
}
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\t\tWith exceptions.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const Obj X(g(SPEC));
bool outOfRangeCaught = false;
try {
(void) X.copy(buffer + 1, MAX_LEN - 2, LENGTH + 1);
ASSERT(0);
}
catch (std::out_of_range) {
outOfRangeCaught = true;
}
LOOP_ASSERT(LINE, outOfRangeCaught);
}
}
#endif
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase23Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING COPY:
//
// Concerns:
// 1 'copy' asserts on undefined behavior when it's passed a NULL
// C-string pointer.
//
// Plan:
// Create a non-empty string and test 'copy' with a NULL C-string pointer
// parameter.
//
// Testing:
// size_type copy(char *s, n, pos = 0) const;
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\tcopy(s, n, pos)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
TYPE dest[10];
ASSERT(sizeof dest / sizeof *dest > X.size());
// characterString == NULL
ASSERT_SAFE_FAIL(X.copy(nullStr, X.size(), 0));
// pass
ASSERT_SAFE_PASS(X.copy(dest, X.size(), 0));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase22()
{
// --------------------------------------------------------------------
// TESTING FIND VARIANTS
// We have the following concerns:
// 1) That the return value is correct, even in the presence of no or
// multiple occurrences of the search pattern.
// 2) That passing a 'pos' argument that is out-of-bounds is not an
// error, and does not throw.
//
// Plan:
// For a set of carefully selected set of string and search pattern
// values, compare the value of 'find' and 'rfind' against expected
// return values. For each string, exercise the special case of an empty
// pattern (the find operations always return the current position,
// except for 'find' when out-of-bounds: npos is returned instead). Also
// exercise the special case of a single character (different signature),
// and verify that return value equals that of a brute-force
// computation.
//
// For 'find_first_...' and 'find_last_...', use the Cartesian product of
// a set of strings and a set of search patterns, and compare the results
// to those of a brute-force computation. Also exercise the special
// cases of a single-character pattern (different signature) and of an
// empty pattern (although redundant since the set of search patterns
// includes an empty string, this also enables us to test the correctness
// of our brute-force implementation in the boundary cases).
//
// Testing:
// size_type find(const string& str, pos = 0) const;
// size_type find(const C *s, pos, n) const;
// size_type find(const C *s, pos = 0) const;
// size_type find(C c, pos = 0) const;
// size_type rfind(const string& str, pos = 0) const;
// size_type rfind(const C *s, pos, n) const;
// size_type rfind(const C *s, pos = 0) const;
// size_type rfind(C c, pos = 0) const;
// size_type find_first_of(const string& str, pos = 0) const;
// size_type find_first_of(const C *s, pos, n) const;
// size_type find_first_of(const C *s, pos = 0) const;
// size_type find_first_of(C c, pos = 0) const;
// size_type find_last_of(const string& str, pos = 0) const;
// size_type find_last_of(const C *s, pos, n) const;
// size_type find_last_of(const C *s, pos = 0) const;
// size_type find_last_of(C c, pos = 0) const;
// size_type find_first_not_of(const string& str, pos = 0) const;
// size_type find_first_not_of(const C *s, pos, n) const;
// size_type find_first_not_of(const C *s, pos = 0) const;
// size_type find_first_not_of(C c, pos = 0) const;
// size_type find_last_not_of(const string& str, pos = 0) const;
// size_type find_last_not_of(const C *s, pos, n) const;
// size_type find_last_not_of(const C *s, pos = 0) const;
// size_type find_last_not_of(C c, pos = 0) const;
// --------------------------------------------------------------------
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const size_t npos = Obj::npos; // note: NPOS is a system macro
if (verbose) printf("\nTesting 'find' and 'rfind'.\n");
{
static const struct {
int d_lineNum;
const char *d_spec;
const char *d_pattern;
size_t d_exp;
size_t d_rexp;
} DATA[] = {
//line spec pattern exp rexp
//---- ---- ------- --- ----
{ L_, "", "A", (size_t)-1, (size_t)-1, },
{ L_, "A", "A", (size_t) 0, (size_t) 0, },
{ L_, "A", "B", (size_t)-1, (size_t)-1, },
{ L_, "AABAA", "B", (size_t) 2, (size_t) 2, },
{ L_, "ABABA", "B", (size_t) 1, (size_t) 3, },
{ L_, "BAAAB", "B", (size_t) 0, (size_t) 4, },
{ L_, "ABCDE", "BCD", (size_t) 1, (size_t) 1, },
{ L_, "ABABA", "ABA", (size_t) 0, (size_t) 2, },
{ L_, "ABACABA", "ABA", (size_t) 0, (size_t) 4, },
{ L_, "ABABABAB", "BABAB", (size_t) 1, (size_t) 3, },
{ L_, "ABABABAB", "C", (size_t)-1, (size_t)-1, },
{ L_, "ABABABAB", "ABABABAC", (size_t)-1, (size_t)-1, },
{ L_, "A", "ABABA", (size_t)-1, (size_t)-1, },
{ L_, "AABAA", "CDCDC", (size_t)-1, (size_t)-1, },
// Add further tests below, but note that test will fail if the
// spec has the pattern in more than two occurrences.
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_lineNum;
const char* const SPEC = DATA[i].d_spec;
const size_t LENGTH = strlen(SPEC);
const char* const PATTERN = DATA[i].d_pattern;
const size_t N = strlen(PATTERN);
const size_t EXP = DATA[i].d_exp;
const size_t REXP = DATA[i].d_rexp;
const Obj X(g(SPEC));
if (veryVerbose) {
printf("\tWith SPEC: \"%s\" of length " ZU
" and empty pattern.\n",
SPEC,
LENGTH);
printf("\t\tExpecting 'find' and 'rfind' at each position.\n");
}
const Obj Z;
LOOP2_ASSERT(LINE, SPEC, 0 == X.find(Z));
LOOP2_ASSERT(LINE, SPEC, 0 == X.find(Z.c_str()));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z.c_str()));
for (size_t j = 0; j <= LENGTH; ++j) {
LOOP3_ASSERT(LINE, SPEC, j, j == X.find(Z, j));
LOOP3_ASSERT(LINE, SPEC, j, j == X.find(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j, j == X.find(Z.c_str(), j, 0));
LOOP3_ASSERT(LINE, SPEC, j, j == X.rfind(Z, j));
LOOP3_ASSERT(LINE, SPEC, j, j == X.rfind(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j, j == X.rfind(Z.c_str(), j, 0));
}
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z, LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z, npos));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z.c_str(), LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z.c_str(), npos));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z.c_str(), LENGTH + 1, 0));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(Z.c_str(), npos, 0));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z, LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z, npos));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z.c_str(), LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z.c_str(), npos));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z.c_str(), LENGTH + 1,
0));
LOOP2_ASSERT(LINE, SPEC, LENGTH == X.rfind(Z.c_str(), npos, 0));
if (veryVerbose) {
printf("\tWith SPEC: \"%s\" of length " ZU
" and every 'char'.\n",
SPEC,
LENGTH);
printf("\t\tComparing with values computed ad hoc.\n");
}
for (int i = 0; i < NUM_VALUES; ++i) {
const TYPE C = VALUES[i];
size_t *exp = new size_t[LENGTH + 1];
const size_t *EXP = exp;
size_t *rExp = new size_t[LENGTH + 1];
const size_t *REXP = rExp;
for (size_t j = 0; j <= LENGTH; ++j) {
size_t lastJ = j < LENGTH ? j : LENGTH - 1;
exp[j] = rExp[j] = npos;
for (size_t k = j; k < LENGTH; ++k) {
if (TRAITS::eq(C, X[k])) {
exp[j] = k; break;
}
}
ASSERT(npos == EXP[j] || (EXP[j] < LENGTH &&
C == X[EXP[j]]));
for (int k = static_cast<int>(lastJ); k >= 0; --k) {
if (TRAITS::eq(C, X[k])) {
rExp[j] = k; break;
}
}
ASSERT(npos == REXP[j] || (REXP[j] <= lastJ &&
C == X[REXP[j]]));
}
LOOP2_ASSERT(LINE, SPEC, EXP[0] == X.find(C));
LOOP2_ASSERT(LINE, SPEC, REXP[LENGTH] == X.rfind(C));
for (size_t j = 0; j <= LENGTH; ++j) {
LOOP3_ASSERT(LINE, SPEC, j, EXP[j] == X.find(C, j));
LOOP3_ASSERT(LINE, SPEC, j, REXP[j] == X.rfind(C, j));
}
LOOP2_ASSERT(LINE, SPEC, npos == X.find(C, LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC, npos == X.find(C, npos));
LOOP2_ASSERT(LINE, SPEC, REXP[LENGTH] == X.rfind(C, LENGTH +
1));
LOOP2_ASSERT(LINE, SPEC, REXP[LENGTH] == X.rfind(C, npos));
delete[] exp;
delete[] rExp;
}
if (veryVerbose) {
printf("\tWith SPEC: \"%s\" of length " ZU
" and pattern \"%s\".\n",
SPEC,
LENGTH,
PATTERN);
printf("\t\tExpecting 'find' at " ZU
" and 'rfind' at " ZU ".\n",
EXP,
REXP);
}
const Obj Y(g(PATTERN));
LOOP4_ASSERT(LINE, SPEC, PATTERN, EXP, EXP == X.find(Y));
LOOP4_ASSERT(LINE, SPEC, PATTERN, EXP, EXP == X.find(Y.c_str()));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP, REXP == X.rfind(Y));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
REXP == X.rfind(Y.c_str()));
if (EXP == npos) {
ASSERT(EXP == REXP);
for (size_t j = 0; j <= LENGTH + 2; ++j) {
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.find(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.find(Y.c_str(), j, N));
}
continue;
}
for (size_t j = 0; j < EXP; ++j) {
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.find(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.find(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.find(Y.c_str(), j, N));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
npos == X.rfind(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
npos == X.rfind(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
npos == X.rfind(Y.c_str(), j, N));
}
LOOP4_ASSERT(LINE, SPEC, PATTERN, EXP,
EXP == X.find(Y, EXP));
for (size_t j = EXP + 1; j <= REXP; ++j) {
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.find(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.find(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.find(Y.c_str(), j, N));
}
for (size_t j = EXP; j < REXP; ++j) {
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.rfind(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.rfind(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
EXP == X.rfind(Y.c_str(), j, N));
}
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP, REXP == X.rfind(Y, REXP));
for (size_t j = REXP + 1; j < LENGTH + 2; ++j) {
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
npos == X.find(Y, j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
npos == X.find(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, EXP,
npos == X.find(Y.c_str(), j, N));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.rfind(Y));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.rfind(Y.c_str(), j));
LOOP5_ASSERT(LINE, SPEC, PATTERN, j, REXP,
REXP == X.rfind(Y.c_str(), j, N));
}
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
npos == X.find(Y, npos));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
npos == X.find(Y.c_str(), npos));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
npos == X.find(Y.c_str(), npos, N));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
REXP == X.rfind(Y, npos));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
REXP == X.rfind(Y.c_str(), npos));
LOOP4_ASSERT(LINE, SPEC, PATTERN, REXP,
REXP == X.rfind(Y.c_str(), npos, N));
}
}
if (verbose) printf("\nTesting 'find_first_...' and 'find_last_...'.\n");
{
static const struct {
int d_lineNum;
const char *d_spec;
} DATA[] = {
//line spec
//---- ----
{ L_, "" },
{ L_, "A" },
{ L_, "B" },
{ L_, "AB" },
{ L_, "ABABABABAB" },
{ L_, "AAAAAABBBB" },
{ L_, "ABCDABCD" },
{ L_, "ABCDEABCDE" },
{ L_, "AAAABBBBCCCCDDDDEEEE" }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
static const struct {
int d_lineNum;
const char *d_pattern;
} PATTERNS[] = {
//line pattern
//---- -------
{ L_, "", },
{ L_, "A", },
{ L_, "AAA", },
{ L_, "AB", },
{ L_, "ABC", },
{ L_, "ABCDE", },
{ L_, "B", },
{ L_, "E", },
{ L_, "F", },
{ L_, "FGHIJKL", }
};
const int NUM_PATTERNS = sizeof PATTERNS / sizeof *PATTERNS;
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_lineNum;
const char* const SPEC = DATA[i].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\tWith SPEC: \"%s\" of length " ZU ".\n",
SPEC,
LENGTH);
}
const Obj X(g(SPEC));
if (veryVerbose) {
printf("\t\tWith empty pattern.\n");
printf("\t\t\tExpecting 'find_.._not_of' at each position.\n");
}
const Obj Z;
LOOP2_ASSERT(LINE, SPEC, npos == X.find_first_of(Z));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_first_of(Z.c_str()));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_last_of(Z));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_last_of(Z.c_str()));
if (LENGTH) {
LOOP2_ASSERT(LINE, SPEC, 0 == X.find_first_not_of(Z));
LOOP2_ASSERT(LINE, SPEC, 0 == X.find_first_not_of(Z.c_str()));
LOOP2_ASSERT(LINE, SPEC, LENGTH - 1 == X.find_last_not_of(Z));
LOOP2_ASSERT(LINE, SPEC, LENGTH - 1 == X.find_last_not_of(
Z.c_str()));
} else {
LOOP2_ASSERT(LINE, SPEC, npos == X.find_first_not_of(Z));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_first_not_of(
Z.c_str()));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_last_not_of(Z));
LOOP2_ASSERT(LINE, SPEC, npos == X.find_last_not_of(
Z.c_str()));
}
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_first_of(Z, j));
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_first_of(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_first_of(Z.c_str(), j, 0));
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_last_of(Z, j));
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_last_of(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j,
npos == X.find_last_of(Z.c_str(), j, 0));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_first_not_of(Z, j));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_first_not_of(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_first_not_of(Z.c_str(), j, 0));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_last_not_of(Z, j));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_last_not_of(Z.c_str(), j));
LOOP3_ASSERT(LINE, SPEC, j,
j == X.find_last_not_of(Z.c_str(), j, 0));
}
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_first_of(Z, npos));
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_first_of(Z.c_str(), npos, 0));
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_last_of(Z, npos));
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_last_of(Z.c_str(), npos, 0));
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_first_not_of(Z, npos));
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_first_not_of(Z.c_str(), npos, 0));
LOOP2_ASSERT(LINE, SPEC,
LENGTH - 1 == X.find_last_not_of(Z, npos));
LOOP2_ASSERT(LINE, SPEC,
LENGTH - 1 == X.find_last_not_of(Z.c_str(), npos, 0));
if (veryVerbose) {
printf("\t\tWith 'char' pattern.\n");
printf("\t\t\tComparing with values computed ad hoc.\n");
}
for (int i = 0; i < NUM_VALUES; ++i) {
const TYPE C = VALUES[i];
size_t *exp = new size_t[LENGTH + 1];
const size_t *EXP = exp;
size_t *rExp = new size_t[LENGTH + 1];
const size_t *REXP = rExp;
for (size_t j = 0; j <= LENGTH; ++j) {
size_t lastJ = j < LENGTH ? j : j - 1;
exp[j] = rExp[j] = npos;
for (size_t k = j; k < LENGTH; ++k) {
if (!TRAITS::eq(C, X[k])) {
exp[j] = k; break;
}
}
ASSERT(npos == EXP[j] || (j <= EXP[j] &&
EXP[j] < LENGTH &&
C != X[EXP[j]]));
for (int k = static_cast<int>(lastJ); k >= 0; --k) {
if (!TRAITS::eq(C, X[k])) {
rExp[j] = k; break;
}
}
ASSERT(npos == REXP[j] || (REXP[j] <= lastJ &&
C != X[REXP[j]]));
}
LOOP2_ASSERT(LINE, SPEC, X.find(C) == X.find_first_of(C));
LOOP2_ASSERT(LINE, SPEC, X.rfind(C) == X.find_last_of(C));
LOOP2_ASSERT(LINE, SPEC, EXP[0] == X.find_first_not_of(C));
LOOP2_ASSERT(LINE, SPEC,
REXP[LENGTH] == X.find_last_not_of(C));
for (size_t j = 0; j <= LENGTH + 2; ++j) {
LOOP3_ASSERT(LINE, SPEC, j,
X.find(C, j) == X.find_first_of(C, j));
LOOP3_ASSERT(LINE, SPEC, j,
X.rfind(C, j) == X.find_last_of(C, j));
}
for (size_t j = 0; j <= LENGTH; ++j) {
LOOP3_ASSERT(LINE, SPEC, j,
EXP[j] == X.find_first_not_of(C, j));
LOOP3_ASSERT(LINE, SPEC, j,
REXP[j] == X.find_last_not_of(C, j));
}
LOOP2_ASSERT(LINE, SPEC,
npos == X.find_first_not_of(C, LENGTH + 1));
LOOP2_ASSERT(LINE, SPEC,
REXP[LENGTH] == X.find_last_not_of(C,
LENGTH + 1));
delete[] exp;
delete[] rExp;
}
for (int k = 0; k < NUM_PATTERNS; ++k) {
const int PLINE = PATTERNS[k].d_lineNum;
const char* const PATTERN = PATTERNS[k].d_pattern;
const size_t N = strlen(PATTERN);
const Obj Y(g(PATTERN));
if (veryVerbose) {
printf("\t\tWith pattern \"%s\".\n", PATTERN);
printf("\t\t\tComparing with values computed ad hoc.\n");
printf("\t\t\tFor 'find_{first,last}_of'.\n");
}
size_t *exp = new size_t[LENGTH + 1];
const size_t *EXP = exp;
size_t *rExp = new size_t[LENGTH + 1];
const size_t *REXP = rExp;
size_t *expN = new size_t[LENGTH + 1];
const size_t *EXP_N = expN;
size_t *rExpN = new size_t[LENGTH + 1];
const size_t *REXP_N = rExpN;
for (size_t j = 0; j <= LENGTH; ++j) {
size_t lastJ = j < LENGTH ? j : j - 1;
exp[j] = rExp[j] = npos;
for (size_t k = j; k < LENGTH && EXP[j] == npos; ++k) {
for (size_t m = 0; m < N; ++m) {
if (TRAITS::eq(Y[m], X[k])) {
exp[j] = k; expN[j] = m; break;
}
}
}
ASSERT(npos == EXP[j] || (j <= EXP[j] && EXP[j] < LENGTH &&
Y[EXP_N[j]] == X[EXP[j]]));
for (int k = static_cast<int>(lastJ);
k >= 0 && REXP[j] == npos;
--k) {
for (size_t m = 0; m < N; ++m) {
if (TRAITS::eq(Y[m], X[k])) {
rExp[j] = k; rExpN[j] = m; break;
}
}
}
ASSERT(npos == REXP[j] || (REXP[j] <= lastJ &&
Y[REXP_N[j]] == X[REXP[j]]));
}
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, EXP[0],
EXP[0] == X.find_first_of(Y));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, EXP[0],
EXP[0] == X.find_first_of(Y.c_str()));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[0],
REXP[LENGTH] == X.find_last_of(Y));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[0],
REXP[LENGTH] == X.find_last_of(Y.c_str()));
for (size_t j = 0; j <= LENGTH; ++j) {
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP[j] == X.find_first_of(Y, j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP [j]== X.find_first_of(Y.c_str(), j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP [j]== X.find_first_of(Y.c_str(), j, N));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_of(Y, j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_of(Y.c_str(), j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_of(Y.c_str(), j, N));
}
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_of(Y, npos));
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_of(Y.c_str(), npos));
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_of(Y.c_str(), npos, N));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_of(Y, npos));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_of(Y.c_str(), npos));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_of(Y.c_str(),
npos,
N));
if (veryVerbose)
printf("\t\t\tFor 'find_{first,last}_not_of'.\n");
for (size_t j = 0; j <= LENGTH; ++j) {
size_t lastJ = j < LENGTH ? j : j - 1;
exp[j] = rExp[j] = npos;
for (size_t k = j; k < LENGTH; ++k) {
size_t m;
for (m = 0; m < N; ++m) {
if (TRAITS::eq(Y[m], X[k])) {
break;
}
}
if (m == N) {
exp[j] = k; expN[j] = m; break;
}
}
ASSERT(npos == EXP[j] || (j <= EXP[j] && EXP[j] < LENGTH));
for (int k = static_cast<int>(lastJ); k >= 0; --k) {
size_t m;
for (m = 0; m < N; ++m) {
if (TRAITS::eq(Y[m], X[k])) {
break;
}
}
if (m == N) {
rExp[j] = k; rExpN[j] = m; break;
}
}
ASSERT(npos == REXP[j] || REXP[j] <= lastJ);
}
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, EXP[0],
EXP[0] == X.find_first_not_of(Y));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, EXP[0],
EXP[0] == X.find_first_not_of(Y.c_str()));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[0],
REXP[LENGTH] == X.find_last_not_of(Y));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[0],
REXP[LENGTH] == X.find_last_not_of(Y.c_str()));
for (size_t j = 0; j <= LENGTH; ++j) {
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP[j] == X.find_first_not_of(Y, j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP [j]== X.find_first_not_of(Y.c_str(), j));
LOOP6_ASSERT(
LINE, PLINE, SPEC, PATTERN, j, EXP[j],
EXP [j]== X.find_first_not_of(Y.c_str(), j, N));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_not_of(Y, j));
LOOP6_ASSERT(LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_not_of(Y.c_str(), j));
LOOP6_ASSERT(
LINE, PLINE, SPEC, PATTERN, j, REXP[j],
REXP[j] == X.find_last_not_of(Y.c_str(), j, N));
}
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_not_of(Y, npos));
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_not_of(Y.c_str(), npos));
LOOP4_ASSERT(LINE, PLINE, SPEC, PATTERN,
npos == X.find_first_not_of(Y.c_str(), npos, N));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_not_of(Y, npos));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_not_of(Y.c_str(),
npos));
LOOP5_ASSERT(LINE, PLINE, SPEC, PATTERN, REXP[LENGTH],
REXP[LENGTH] == X.find_last_not_of(Y.c_str(),
npos,
N));
delete[] exp;
delete[] expN;
delete[] rExp;
delete[] rExpN;
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase22Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING COPY:
//
// Concerns:
// 'find' asserts on undefined behavior when it's passed a NULL C-string
// pointer.
//
// Plan:
// For each variant of the 'find...' method, create a non-empty string
// and test the 'find' method with a NULL C-string pointer parameter.
//
// Testing:
// size_type find(const C *s, pos, n) const;
// size_type find(const C *s, pos = 0) const;
// size_type rfind(const C *s, pos, n) const;
// size_type rfind(const C *s, pos = 0) const;
// size_type find_first_of(const C *s, pos, n) const;
// size_type find_first_of(const C *s, pos = 0) const;
// size_type find_last_of(const C *s, pos, n) const;
// size_type find_last_of(const C *s, pos = 0) const;
// size_type find_first_not_of(const C *s, pos, n) const;
// size_type find_first_not_of(const C *s, pos = 0) const;
// size_type find_last_not_of(const C *s, pos, n) const;
// size_type find_last_not_of(const C *s, pos = 0) const;
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
Obj mX(g("ABCDE"));
const Obj& X = mX;
const TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
if (veryVerbose) printf("\tfind(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.find(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.find(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\tfind(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.find(nullStr, 0));
ASSERT_SAFE_PASS(X.find(X.c_str(), 0));
}
if (veryVerbose) printf("\trfind(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.rfind(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.rfind(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\trfind(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.rfind(nullStr, 0));
ASSERT_SAFE_PASS(X.rfind(X.c_str(), 0));
}
if (veryVerbose) printf("\tfind_first_of(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.find_first_of(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.find_first_of(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\tfind_first_of(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.find_first_of(nullStr, 0));
ASSERT_SAFE_PASS(X.find_first_of(X.c_str(), 0));
}
if (veryVerbose) printf("\tfind_last_of(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.find_last_of(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.find_last_of(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\tfind_last_of(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.find_last_of(nullStr, 0));
ASSERT_SAFE_PASS(X.find_last_of(X.c_str(), 0));
}
if (veryVerbose) printf("\tfind_first_not_of(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.find_first_not_of(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.find_first_not_of(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\tfind_first_not_of(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.find_first_not_of(nullStr, 0));
ASSERT_SAFE_PASS(X.find_first_not_of(X.c_str(), 0));
}
if (veryVerbose) printf("\tfind_last_not_of(s, pos, n)\n");
{
ASSERT_SAFE_FAIL(X.find_last_not_of(nullStr, 0, X.size()));
ASSERT_SAFE_PASS(X.find_last_not_of(X.c_str(), 0, X.size()));
}
if (veryVerbose) printf("\tfind_last_not_of(s, pos)\n");
{
ASSERT_SAFE_FAIL(X.find_last_not_of(nullStr, 0));
ASSERT_SAFE_PASS(X.find_last_not_of(X.c_str(), 0));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase21()
{
// --------------------------------------------------------------------
// TESTING SWAP
//
// Concerns:
// 1) Swapping containers does not swap allocators.
// 2) Swapping containers with same allocator results in no allocation
// or deallocation operations.
// 3) Swapping containers with different allocators does result in
// allocation and deallocation operations.
// 4) Swap free function works the same way as the 'swap' method.
// 5) Swap works correctly for the short string optimization (swapping
// short and long strings).
//
// Plan:
// Construct 'str1' and 'str2' with different test allocators.
// Add data to 'str1'. Remember allocation statistics.
// Swap 'str1' and 'str2'.
// Verify that contents were swapped.
// Verify that allocators for each are unchanged.
// Verify that allocation statistics changed for each test allocator.
// Create a 'str3' with same allocator as 'str2'.
// Swap 'str2' and 'str3'
// Verify that contents were swapped.
// Verify that allocation statistics did not change.
// Let 'str3' got out of scope.
// Verify that memory was returned to allocator.
// Construct two strings, apply a free function swap to them and verify
// the result.
// Construct short and long strings, swap them with each other and verify
// the result.
//
// Testing:
// swap(string<C,CT,A>& rhs); // method
// swap(string<C,CT,A>& lhs, string<C,CT,A>& rhs); // free function
// ------------------------------------------------------------------------
const size_t LENGTH = DEFAULT_CAPACITY * 2;
{
bslma::TestAllocator testAlloc2(veryVeryVerbose);
ASSERT(0 == testAlloc2.numBytesInUse());
Obj str1(g(LENGTH, TYPE('0')));
Obj str1cpy(str1);
Obj str2(&testAlloc2);
if (verbose) printf("Swap strings with unequal allocators.\n");
str1.swap(str2);
ASSERT(0 == str1.size());
ASSERT(LENGTH == str2.size());
ASSERT(str1cpy == str2);
ASSERT(bslma::Default::defaultAllocator() == str1.get_allocator());
ASSERT(&testAlloc2 == str2.get_allocator());
const Int64 numAlloc2 = testAlloc2.numAllocations();
const Int64 numDealloc2 = testAlloc2.numDeallocations();
const Int64 inUse2 = testAlloc2.numBytesInUse();
if (verbose) printf("Swap strings with equal allocators.\n");
{
Obj str3(&testAlloc2);
ASSERT(testAlloc2.numBytesInUse() == inUse2);
str3.swap(str2);
ASSERT(str2.empty());
ASSERT(LENGTH == str3.size());
ASSERT(str1cpy == str3);
ASSERT(numAlloc2 == testAlloc2.numAllocations());
ASSERT(numDealloc2 == testAlloc2.numDeallocations());
ASSERT(inUse2 == testAlloc2.numBytesInUse());
}
// Destructor for str3 should have freed memory
ASSERT(0 == testAlloc2.numBytesInUse());
}
if (verbose) printf("Swap free function.\n");
{
Obj str1(g(LENGTH, TYPE('0')));
Obj str1cpy(str1);
Obj str2(g(LENGTH, TYPE('9')));
Obj str2cpy(str2);
using bsl::swap;
swap(str1, str2);
ASSERT(str1 == str2cpy);
ASSERT(str2 == str1cpy);
}
if (verbose) printf("Swap and short string optimization.\n");
{
if (veryVerbose) printf(" short <-> short\n");
{
Obj shortStr1(g(DEFAULT_CAPACITY, TYPE('0')));
Obj shortStr1Cpy(shortStr1);
Obj shortStr2(g(DEFAULT_CAPACITY, TYPE('9')));
Obj shortStr2Cpy(shortStr2);
shortStr1.swap(shortStr2);
ASSERT(shortStr1 == shortStr2Cpy);
ASSERT(shortStr2 == shortStr1Cpy);
}
if (veryVerbose) printf(" short <-> long\n");
{
Obj shortStr(g(DEFAULT_CAPACITY, TYPE('0')));
Obj shortStrCpy(shortStr);
Obj longStr(g(DEFAULT_CAPACITY * 2, TYPE('9')));
Obj longStrCpy(longStr);
shortStr.swap(longStr);
ASSERT(shortStr == longStrCpy);
ASSERT(longStr == shortStrCpy);
}
if (veryVerbose) printf(" long <-> short\n");
{
Obj longStr(g(DEFAULT_CAPACITY * 2, TYPE('0')));
Obj longStrCpy(longStr);
Obj shortStr(g(DEFAULT_CAPACITY, TYPE('9')));
Obj shortStrCpy(shortStr);
longStr.swap(shortStr);
ASSERT(longStr == shortStrCpy);
ASSERT(shortStr == longStrCpy);
}
if (veryVerbose) printf(" long <-> long\n");
{
Obj longStr1(g(DEFAULT_CAPACITY * 2, TYPE('0')));
Obj longStr1Cpy(longStr1);
Obj longStr2(g(DEFAULT_CAPACITY * 2, TYPE('9')));
Obj longStr2Cpy(longStr2);
longStr1.swap(longStr2);
ASSERT(longStr1 == longStr2Cpy);
ASSERT(longStr2 == longStr1Cpy);
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase20()
{
// --------------------------------------------------------------------
// TESTING REPLACE:
// We have the following concerns:
// 1) That the resulting string value is correct.
// 2) That the 'replace' return value is a reference to self.
// 3) That the resulting capacity is correctly set up.
// 4) That existing elements are moved via Traits::move.
// 5) That insertion is exception neutral w.r.t. memory allocation.
// 6) The internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
//
// Plan:
// The plan is similar to 'insert' (case 17) with two nested loops
// for the beginning and end of the replace range (instead of only one
// for the insert position). Since both 'erase' and 'insert' have been
// tested, and conceptually replace is equivalent to 'erase' followed by
// 'insert', is suffices to perform 'replace' using this alternate method
// and compare the resulting strings.
//
// Testing:
// string& replace(pos1, n1, size_type n2, C c);
// replace(const_iterator first, const_iterator last, size_type n2, C c);
// -----------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
enum {
REPLACE_CHAR_MODE_FIRST = 0,
REPLACE_CHAR_N_AT_INDEX = 0,
REPLACE_CHAR_N_AT_ITERATOR = 1,
REPLACE_CHAR_MODE_LAST = 1
};
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 18 }
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 32 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\nTesting 'replace'.\n");
for (int replaceMode = REPLACE_CHAR_MODE_FIRST;
replaceMode <= REPLACE_CHAR_MODE_LAST;
++replaceMode)
{
if (verbose)
printf("\tUsing 'n' copies of 'value', replaceMode = %d.\n",
replaceMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const int NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = std::min(b + s, INIT_LENGTH);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS -
(END - BEGIN);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
ALLOC(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mExp(X); const Obj& EXP = mExp;
mExp.erase(mExp.begin() + BEGIN, mExp.begin() + END);
mExp.insert(BEGIN, NUM_ELEMENTS, VALUE);
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tReplace "); P_(SIZE);
printf("elements between "); P_(BEGIN); P_(END);
printf("using "); P_(NUM_ELEMENTS); P(VALUE);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch (replaceMode) {
case REPLACE_CHAR_N_AT_ITERATOR: {
// void replace(iterator p, iterator q,
// size_type n, C c);
Obj& result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
NUM_ELEMENTS,
VALUE);
LOOP3_ASSERT(INIT_LINE, i, ti, &X == &result);
} break;
case REPLACE_CHAR_N_AT_INDEX: {
// string& replace(pos1, n1, n2, C c);
Obj &result = mX.replace(BEGIN,
SIZE,
NUM_ELEMENTS,
VALUE);
LOOP3_ASSERT(INIT_LINE, i, ti, &X == &result);
} break;
default:
printf("***UNKNOWN REPLACE MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
LENGTH == X.size());
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
CAP == X.capacity());
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
EXP == X);
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
BB + REALLOC == AA);
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
B + A_ALLOC == A);
}
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
for (int replaceMode = REPLACE_CHAR_MODE_FIRST;
replaceMode <= REPLACE_CHAR_MODE_LAST;
++replaceMode)
{
if (verbose)
printf("\t\tUsing string with replaceMode = %d.\n", replaceMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const size_t NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(
testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
ALLOC(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
Obj mExp(X); const Obj& EXP = mExp;
mExp.erase(mExp.begin() + BEGIN,
mExp.begin() + END);
mExp.insert(BEGIN, NUM_ELEMENTS, VALUE);
testAllocator.setAllocationLimit(AL);
bool checkResultFlag = false;
switch (replaceMode) {
case REPLACE_CHAR_N_AT_INDEX: {
// string& replace(pos1, n1, n2, C c);
Obj &result = mX.replace(BEGIN, SIZE,
NUM_ELEMENTS,
VALUE);
LOOP4_ASSERT(INIT_LINE, LINE, BEGIN, SIZE,
&X == &result);
checkResultFlag = true;
} break;
case REPLACE_CHAR_N_AT_ITERATOR: {
// void replace(iterator p, iterator q,
// size_type n2, C c);
Obj &result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
NUM_ELEMENTS,
VALUE);
LOOP4_ASSERT(INIT_LINE, LINE, BEGIN, END,
&X == &result);
checkResultFlag = true;
} break;
default:
printf("***UNKNOWN REPLACE MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
if (checkResultFlag) {
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, END, SIZE,
EXP == X);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
template <class CONTAINER>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase20Range(const CONTAINER&)
{
// --------------------------------------------------------------------
// TESTING REPLACE:
// We have the following concerns:
// 1) That the resulting string value is correct.
// 2) That the return value is a reference to self.
// 3) That the resulting capacity is correctly set up if the initial
// 'FWD_ITER' is a random-access iterator.
// 5) That insertion is exception neutral w.r.t. memory allocation.
// 6) The internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
//
// Plan:
// See 'testCase20'.
//
// Testing:
// string& replace(pos1, n1, const string& str);
// string& replace(pos1, n1, const string& str, pos2, n2);
// string& replace(pos1, n1, const C *s, n2);
// string& replace(pos1, n1, const C *s);
// replace(const_iterator first, const_iterator last, const C *s, n2);
// replace(const_iterator first, const_iterator last, const C *s);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const int INPUT_ITERATOR_TAG =
bsl::is_same<std::input_iterator_tag,
typename bsl::iterator_traits<
typename CONTAINER::const_iterator>::iterator_category
>::value;
enum {
REPLACE_STRING_MODE_FIRST = 0,
REPLACE_SUBSTRING_AT_INDEX = 0,
REPLACE_STRING_AT_INDEX = 1,
REPLACE_CSTRING_N_AT_INDEX = 2,
REPLACE_CSTRING_AT_INDEX = 3,
REPLACE_STRING_AT_ITERATOR = 4,
REPLACE_CONST_STRING_AT_ITERATOR = 5,
REPLACE_CSTRING_N_AT_ITERATOR = 6,
REPLACE_CSTRING_AT_ITERATOR = 7,
REPLACE_STRING_MODE_LAST = 7
};
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 }
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
static const struct {
int d_lineNum; // source line number
const char *d_spec; // container spec
} U_DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_U_DATA = sizeof U_DATA / sizeof *U_DATA;
for (int replaceMode = REPLACE_STRING_AT_INDEX;
replaceMode <= REPLACE_STRING_MODE_LAST;
++replaceMode)
{
if (verbose)
printf("\tUsing string with replaceMode = %d.\n", replaceMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS -
(END - BEGIN);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tReplace "); P_(NUM_ELEMENTS);
printf("between "); P_(BEGIN); P_(END);
printf("using "); P(SPEC);
}
Obj mExp(X); const Obj& EXP = mExp;
mExp.erase(mExp.begin() + BEGIN, mExp.begin() + END);
mExp.insert(BEGIN, Y);
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch(replaceMode) {
case REPLACE_STRING_AT_INDEX: {
// string& replace(pos1, n1, const string& str);
Obj &result = mX.replace(BEGIN, SIZE, Y);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_N_AT_INDEX: {
// string& replace(pos1, n1, const C *s, n2);
Obj &result = mX.replace(BEGIN,
SIZE,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_AT_INDEX: {
// string& replace(pos1, n1, const C *s);
Obj &result = mX.replace(BEGIN, SIZE, Y.c_str());
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_N_AT_ITERATOR: {
// string& replace(iterator p, q, const C *s);
Obj &result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_AT_ITERATOR: {
// string& replace(iterator p, q, const C *s);
Obj &result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
Y.c_str());
ASSERT(&result == &mX);
} break;
case REPLACE_STRING_AT_ITERATOR: {
// template <class InputIter>
// void replace(iterator p, iterator q,
// InputIter first, last);
mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
mU.begin(),
mU.end());
} break;
case REPLACE_CONST_STRING_AT_ITERATOR: {
// template <class InputIter>
// void replace(iterator p, iterator q,
// InputIter first, last);
mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
U.begin(),
U.end());
} break;
default:
printf("***UNKNOWN REPLACE MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
CAP == X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
EXP == X);
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, BEGIN, END, SIZE,
BB + REALLOC <= AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, ti,
B + A_ALLOC <= A);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tUsing string with replaceMode = %d.\n",
REPLACE_SUBSTRING_AT_INDEX);
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
for (size_t k = 0; k <= NUM_ELEMENTS; ++k) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
const size_t POS2 = k;
const size_t NUM_ELEMENTS_INS = NUM_ELEMENTS - POS2;
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS_INS -
(END - BEGIN);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t n;
for (n = 0; n < INIT_LENGTH; ++n) {
mX[n] = VALUES[n % NUM_VALUES];
}
Obj mExp(X); const Obj& EXP = mExp;
mExp.erase(mExp.begin() + BEGIN, mExp.begin() + END);
mExp.insert(BEGIN, Y, POS2, NUM_ELEMENTS);
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tReplace"); P_(NUM_ELEMENTS_INS);
printf("between "); P_(BEGIN); P_(END);
printf("using "); P_(SPEC);
printf("starting at "); P(POS2);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
// string& replace(pos1, n1, const string& str,
// pos2, n2);
Obj &result = mX.replace(BEGIN, SIZE,
Y, POS2, NUM_ELEMENTS);
ASSERT(&result == &mX);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, POS2,
LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, POS2,
CAP == X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
EXP == X);
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
BEGIN, END, BB + REALLOC <= AA);
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
BEGIN, END, B + A_ALLOC <= A);
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
for (int replaceMode = REPLACE_STRING_MODE_FIRST;
replaceMode <= REPLACE_STRING_MODE_LAST;
++replaceMode)
{
if (verbose)
printf("\t\tUsing string with replaceMode = %d.\n", replaceMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS -
(END - BEGIN);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(
testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
Obj mExp(X); const Obj& EXP = mExp;
mExp.erase(mExp.begin() + BEGIN,
mExp.begin() + END);
mExp.insert(BEGIN, Y);
testAllocator.setAllocationLimit(AL);
switch(replaceMode) {
case REPLACE_STRING_AT_INDEX: {
// string& replace(pos1, n1,
// const string& str);
Obj &result = mX.replace(BEGIN, SIZE, Y);
ASSERT(&result == &mX);
} break;
case REPLACE_SUBSTRING_AT_INDEX: {
// string& replace(pos1, n1, const string& str,
// pos2, n2);
Obj &result = mX.replace(BEGIN,
SIZE,
Y,
0,
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_N_AT_INDEX: {
// string& replace(pos1, n1, const C *s, n2);
Obj &result = mX.replace(BEGIN,
SIZE,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_AT_INDEX: {
// string& replace(pos1, n1, const C *s);
Obj &result = mX.replace(BEGIN,
SIZE,
Y.c_str());
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_N_AT_ITERATOR: {
// replace(const_iterator p, q, const C *s);
Obj &result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case REPLACE_CSTRING_AT_ITERATOR: {
// replace(const_iterator p, q, const C *s);
Obj &result = mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
Y.c_str());
ASSERT(&result == &mX);
} break;
case REPLACE_STRING_AT_ITERATOR: {
// template <class InputIter>
// replace(const_iterator p, const_iterator q,
// InputIter first, last);
mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
mU.begin(),
mU.end());
} break;
case REPLACE_CONST_STRING_AT_ITERATOR: {
// template <class InputIter>
// replace(const_iterator p, const_iterator q,
// InputIter first, last);
mX.replace(mX.begin() + BEGIN,
mX.begin() + END,
U.begin(),
U.end());
} break;
default:
printf("***UNKNOWN REPLACE MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
LENGTH == X.size());
LOOP5_ASSERT(INIT_LINE, LINE, BEGIN, SIZE, END,
EXP == X);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tTesting aliasing concerns.\n");
for (int replaceMode = REPLACE_STRING_MODE_FIRST;
replaceMode <= REPLACE_STRING_MODE_LAST;
++replaceMode)
{
if (verbose)
printf("\t\tUsing string with replaceMode = %d.\n", replaceMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) {
printf("\t\t\tReplace with "); P_(Y);
printf(" between "); P_(BEGIN); P_(END);
}
switch(replaceMode) {
case REPLACE_STRING_AT_INDEX: {
// string& replace(pos1, n1, const string& str);
mX.replace(BEGIN, SIZE, Y);
mY.replace(BEGIN, SIZE, Y);
} break;
case REPLACE_CSTRING_N_AT_INDEX: {
// string& replace(pos1, n1, const C *s, n);
mX.replace(BEGIN, SIZE, Y.data(), INIT_LENGTH);
mY.replace(BEGIN, SIZE, Y.data(), INIT_LENGTH);
} break;
case REPLACE_CSTRING_AT_INDEX: {
// string& replace(pos1, n1, const C *s);
mX.replace(BEGIN, SIZE, Y.c_str());
mY.replace(BEGIN, SIZE, Y.c_str());
} break;
case REPLACE_SUBSTRING_AT_INDEX: {
// string& replace(pos1, n1, const string& str,
// pos2, n);
mX.replace(BEGIN, SIZE, Y, 0, INIT_LENGTH);
mY.replace(BEGIN, SIZE, Y, 0, INIT_LENGTH);
} break;
case REPLACE_STRING_AT_ITERATOR: {
// template <class InputIter>
// replace(const_iterator p, q, InputIter first, last);
mX.replace(mX.begin() + BEGIN, mX.begin() + END,
mY.begin(), mY.end());
mY.replace(mY.begin() + BEGIN, mY.begin() + END,
mY.begin(), mY.end());
} break;
case REPLACE_CONST_STRING_AT_ITERATOR: {
// template <class InputIter>
// replace(const_iterator p, q, InputIter first, last);
mX.replace(mX.begin() + BEGIN, mX.begin() + END,
Y.begin(), Y.end());
mY.replace(mY.begin() + BEGIN, mY.begin() + END,
Y.begin(), Y.end());
} break;
case REPLACE_CSTRING_N_AT_ITERATOR: {
// replace(const_iterator p, q, const C *s, n);
mX.replace(mX.begin() + BEGIN, mX.begin() + END,
Y.data(), INIT_LENGTH);
mY.replace(mY.begin() + BEGIN, mY.begin() + END,
Y.data(), INIT_LENGTH);
} break;
case REPLACE_CSTRING_AT_ITERATOR: {
// string& replace(pos, const C *s);
mX.replace(mX.begin() + BEGIN, mX.begin() + END,
Y.c_str());
mY.replace(mY.begin() + BEGIN, mY.begin() + END,
Y.c_str());
} break;
default:
printf("***UNKNOWN REPLACE MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP4_ASSERT(INIT_LINE, INIT_CAP, BEGIN, SIZE, X == Y);
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
{
if (verbose)
printf("\t\tUsing string with replaceMode = %d (complete).\n",
REPLACE_SUBSTRING_AT_INDEX);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
for (size_t b = 0; b <= INIT_LENGTH; ++b) {
for (size_t s = 0; s <= INIT_LENGTH; ++s) {
const size_t BEGIN = b;
const size_t SIZE = s;
const size_t END = min(b + s, INIT_LENGTH);
for (size_t h = 0; h < INIT_LENGTH; ++h) {
for (size_t m = 0; m < INIT_LENGTH; ++m) {
const size_t INDEX = h;
const size_t NUM_ELEMENTS = m;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) {
printf("\t\t\tInsert substring of itself");
printf(" with "); P_(INDEX); P(NUM_ELEMENTS);
printf("between "); P_(BEGIN); P(END);
}
mX.replace(BEGIN, SIZE, Y, INDEX, NUM_ELEMENTS);
mY.replace(BEGIN, SIZE, Y, INDEX, NUM_ELEMENTS);
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP6_ASSERT(INIT_LINE, INIT_CAP, BEGIN, SIZE,
INDEX, NUM_ELEMENTS, X == Y);
}
}
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase20Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING REPLACE:
//
// Concerns:
// 1 'replace' asserts on undefined behavior when it's passed either a
// NULL C-string pointer, invalid iterators, or invalid iterator ranges.
//
// Plan:
// For each 'replace' overload create a non-empty string and test
// 'replace' with different combinations of invalid parameters.
//
// Testing:
// replace(const_iterator first, const_iterator last, size_type n2, C c);
// replace(const_iterator first, const_iterator last, const string& str);
// replace(const_iterator first, const_iterator last, InputIter f, l);
// replace(pos1, n1, const C *s);
// replace(pos1, n1, const C *s, n2);
// replace(const_iterator first, const_iterator last, const C *s);
// replace(const_iterator first, const_iterator last, const C *s, n2);
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\treplase(first, last, n, c)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
// first < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin() - 1, X.end(), 1, X[0]));
// first > end()
ASSERT_SAFE_FAIL(mX.replace(X.end() + 1, X.end(), 1, X[0]));
// last < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.begin() - 1, 1, X[0]));
// last > end()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end() + 1, 1, X[0]));
// first > last
ASSERT_SAFE_FAIL(mX.replace(X.begin() + 1, X.begin(), 1, X[0]));
// pass
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(), 1, X[0]));
}
if (veryVerbose) printf("\treplace(first, last, str)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
Obj mY(g("AB")); // replacement
// first < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin() - 1, X.end(), mY));
// first > end()
ASSERT_SAFE_FAIL(mX.replace(X.end() + 1, X.end(), mY));
// last < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.begin() - 1, mY));
// last > end()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end() + 1, mY));
// first > last
ASSERT_SAFE_FAIL(mX.replace(X.begin() + 1, X.begin(), mY));
// pass
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(), mY));
}
if (veryVerbose) printf("\treplace(first, last, f, l)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
Obj mY(g("AB")); // replacement
const Obj& Y = mY;
// first < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin() - 1, X.end(),
mY.begin(), mY.end()));
// first > end()
ASSERT_SAFE_FAIL(mX.replace(X.end() + 1, X.end(),
mY.begin(), mY.end()));
// last < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.begin() - 1,
mY.begin(), mY.end()));
// last > end()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end() + 1,
mY.begin(), mY.end()));
// first > last
ASSERT_SAFE_FAIL(mX.replace(X.begin() + 1, X.begin(),
mY.begin(), mY.end()));
// stringFirst > stringLast (non-const iterators)
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end(),
mY.end(), mY.begin()));
// stringFirst > stringLast (const iterators)
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end(),
Y.end(), Y.begin()));
// pass (non-const iterators)
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(),
mY.begin(), mY.end()));
// pass (const iterators)
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(),
Y.begin(), Y.end()));
}
if (veryVerbose) printf("\treplace(pos1, n1, s)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
// characterString == NULL
ASSERT_SAFE_FAIL(mX.replace(0, X.size(), NULL));
// pass
ASSERT_SAFE_PASS(mX.replace(0, X.size(), X.c_str()));
}
if (veryVerbose) printf("\treplace(pos1, n1, s, n2)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
const TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
// characterString == NULL
ASSERT_SAFE_FAIL(mX.replace(0, X.size(), nullStr, 10));
// pass
ASSERT_SAFE_PASS(mX.replace(0, X.size(), X.c_str(), X.size()));
}
if (veryVerbose) printf("\treplace(first, last, s)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
const TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
// first < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin() - 1, X.end(), X.c_str()));
// first > end()
ASSERT_SAFE_FAIL(mX.replace(X.end() + 1, X.end(), X.c_str()));
// last < begin()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.begin() - 1, X.c_str()));
// last > end()
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end() + 1, X.c_str()));
// first > last
ASSERT_SAFE_FAIL(mX.replace(X.begin() + 1, X.begin(), X.c_str()));
// characterString == NULL
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end(), nullStr));
// pass
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(), X.c_str()));
}
if (veryVerbose) printf("\treplace(first, last, s, n2)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
const TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
// first < begin()
ASSERT_SAFE_FAIL(
mX.replace(X.begin() - 1, X.end(), X.c_str(), X.size()));
// first > end()
ASSERT_SAFE_FAIL(
mX.replace(X.end() + 1, X.end(), X.c_str(), X.size()));
// last < begin()
ASSERT_SAFE_FAIL(
mX.replace(X.begin(), X.begin() - 1, X.c_str(), X.size()));
// last > end()
ASSERT_SAFE_FAIL(
mX.replace(X.begin(), X.end() + 1, X.c_str(), X.size()));
// first > last
ASSERT_SAFE_FAIL(
mX.replace(X.begin() + 1, X.begin(), X.c_str(), X.size()));
// characterString == NULL
ASSERT_SAFE_FAIL(mX.replace(X.begin(), X.end(), nullStr, X.size()));
// pass
ASSERT_SAFE_PASS(mX.replace(X.begin(), X.end(), X.c_str(), X.size()));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase19()
{
// --------------------------------------------------------------------
// TESTING ERASE
// We have the following concerns:
// 1) That the resulting value is correct.
// 2) That erasing a suffix of the array never allocates, and thus never
// throws. In particular, 'pop_back()' and 'erase(..., X.end())' do
// not throw.
// 3) That erasing is exception neutral w.r.t. memory allocation.
// 4) That erasing does not modify the capacity (i.e., shrink).
// 5) That no memory is leaked.
//
// Plan:
// For the 'erase' methods, the concerns are simply to cover the full
// range of possible indices and numbers of elements. We build a string
// with a variable size and capacity, and remove a variable element or
// number of elements from it, and verify that size, capacity, and value
// are as expected:
// - Without exceptions, and computing the number of allocations.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*,
// but not computing the number of allocations or checking on the
// value in case an exception is thrown (it is enough to verify that
// all the elements have been destroyed indirectly by making sure
// that there are no memory leaks).
// For concern 2, we verify that the number of allocations is as
// expected:
// - length of the tail (last element erased to last element) if the
// type uses a 'bslma' allocator, and is not moveable.
// - 0 otherwise.
//
// Testing:
// void pop_back();
// string& erase(size_type pos, size_type n);
// iterator erase(const_iterator p);
// iterator erase(const_iterator first, iterator last);
// -----------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 8 },
{ L_, 9 },
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 },
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\nTesting 'pop_back' on non-empty strings.\n");
{
for (int i = 1; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
const size_t LENGTH = INIT_LENGTH - 1;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
Obj mX(INIT_LENGTH, DEFAULT_VALUE, AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k = 0;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\tBefore: "); P_(BB); P(B);
}
mX.pop_back();
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\tAfter : "); P_(AA); P(A);
T_; T_; P_(X); P(X.capacity());
}
LOOP3_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
LENGTH == X.size());
LOOP3_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
INIT_CAP == X.capacity());
for (k = 0; k < LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, k,
VALUES[k % NUM_VALUES] == X[k]);
}
LOOP3_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, BB == AA);
LOOP3_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, B == A);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 1; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_lineNum;
const size_t LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t CAP = DATA[l].d_length;
ASSERT(LENGTH <= CAP);
Obj mX(LENGTH, DEFAULT_VALUE, AllocType(&testAllocator));
mX.reserve(CAP);
if (veryVerbose) {
printf("\t\tWith initial "); P_(LENGTH); P(CAP);
}
bool exceptionCaught = false;
try {
mX.pop_back();
}
catch (...) {
exceptionCaught = true;
}
LOOP_ASSERT(LINE, !exceptionCaught);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
#endif
if (verbose) printf("\nTesting 'erase(pos, n)'.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
for (size_t k = j; k <= INIT_LENGTH + 2; ++k) {
const size_t BEGIN_POS = j;
const size_t END_POS = k >= INIT_LENGTH
? INIT_LENGTH : k;
const size_t NUM_ELEMENTS = k - BEGIN_POS;
const size_t LENGTH = INIT_LENGTH -
(END_POS - BEGIN_POS);
Obj mX(INIT_LENGTH, DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
if (veryVerbose) {
printf("\t\tErase elements between ");
P_(BEGIN_POS); P(END_POS);
}
const size_t CAPACITY = X.capacity();
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tBefore:"); P_(BB); P(B);
}
Obj *result = &mX.erase(BEGIN_POS, NUM_ELEMENTS);
// test erase here
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, BEGIN_POS,
NUM_ELEMENTS, result == &mX);
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, BEGIN_POS,
NUM_ELEMENTS, LENGTH == X.size());
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, BEGIN_POS,
NUM_ELEMENTS, CAPACITY == X.capacity());
for (m = 0; m < BEGIN_POS; ++m) {
LOOP5_ASSERT(INIT_LINE, LENGTH, BEGIN_POS, END_POS, m,
VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(
INIT_LINE, LENGTH, BEGIN_POS, END_POS, m,
VALUES[(m + NUM_ELEMENTS) % NUM_VALUES] == X[m]);
}
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, END_POS,
BB + 0 == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, END_POS,
B + 0 == A);
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
for (size_t k = j; k <= INIT_LENGTH; ++k) {
const size_t BEGIN_POS = j;
const size_t END_POS = k >= INIT_LENGTH
? INIT_LENGTH : k;
const size_t NUM_ELEMENTS = k - BEGIN_POS;
const size_t LENGTH = INIT_LENGTH -
(END_POS - BEGIN_POS);
if (veryVerbose) {
printf("\t\t\tErase elements between ");
P_(BEGIN_POS); P(END_POS);
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
testAllocator.setAllocationLimit(AL);
Obj *result = &mX.erase(BEGIN_POS, NUM_ELEMENTS);
// test erase here
(void) result;
for (m = 0; m < BEGIN_POS; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
END_POS, m,
VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
END_POS, m,
VALUES[(m + NUM_ELEMENTS) % NUM_VALUES] == X[m]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\nTesting 'erase(pos)' on non-empty strings.\n");
{
for (int i = 1; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
const size_t LENGTH = INIT_LENGTH - 1;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j < INIT_LENGTH; ++j) {
const size_t POS = j;
Obj mX(INIT_LENGTH, DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
if (veryVerbose) {
printf("\t\tErase one element at "); P(POS);
}
const size_t CAPACITY = X.capacity();
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tBefore: "); P_(BB); P(B);
}
typename Obj::iterator result = mX.erase(mX.begin() + POS);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tAfter : "); P_(AA); P(A);
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS,
result == mX.begin() + POS);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS,
LENGTH == X.size());
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS,
CAPACITY == X.capacity());
for (m = 0; m < POS; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS, m,
VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS, m,
VALUES[(m + 1) % NUM_VALUES] == X[m]);
}
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS,
BB + 0 == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, POS,
B + 0 == A);
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 1; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
const size_t LENGTH = INIT_LENGTH - 1;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j < INIT_LENGTH; ++j) {
const size_t POS = j;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
testAllocator.setAllocationLimit(AL);
mX.erase(mX.begin() + POS); // test erase here
for (m = 0; m < POS; ++m) {
LOOP5_ASSERT(
INIT_LINE, INIT_LENGTH, INIT_CAP,
POS, m, VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(
INIT_LINE, INIT_LENGTH, INIT_CAP,
POS, m, VALUES[(m + 1) % NUM_VALUES] == X[m]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\nTesting 'erase(first, last)'.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
for (size_t k = j; k <= INIT_LENGTH; ++k) {
const size_t BEGIN_POS = j;
const size_t END_POS = k;
const size_t NUM_ELEMENTS = END_POS - BEGIN_POS;
const size_t LENGTH = INIT_LENGTH - NUM_ELEMENTS;
Obj mX(INIT_LENGTH, DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
if (veryVerbose) {
printf("\t\tErase elements between ");
P_(BEGIN_POS); P(END_POS);
}
const size_t CAPACITY = X.capacity();
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tBefore:"); P_(BB); P(B);
}
typename Obj::iterator result = mX.erase(
mX.begin() + BEGIN_POS,
mX.begin() + END_POS);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(
INIT_LINE, INIT_LENGTH, INIT_CAP,
NUM_ELEMENTS, result == mX.begin() + BEGIN_POS);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
NUM_ELEMENTS, LENGTH == X.size());
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
NUM_ELEMENTS, CAPACITY == X.capacity());
for (m = 0; m < BEGIN_POS; ++m) {
LOOP5_ASSERT(INIT_LINE, LENGTH, BEGIN_POS, END_POS, m,
VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(
INIT_LINE, LENGTH, BEGIN_POS, END_POS, m,
VALUES[(m + NUM_ELEMENTS) % NUM_VALUES] == X[m]);
}
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, END_POS,
BB + 0 == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, END_POS,
B + 0 == A);
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial "); P_(INIT_LENGTH); P(INIT_RES);
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
for (size_t k = j; k <= INIT_LENGTH; ++k) {
const size_t BEGIN_POS = j;
const size_t END_POS = k;
const size_t NUM_ELEMENTS = END_POS - BEGIN_POS;
const size_t LENGTH = INIT_LENGTH - NUM_ELEMENTS;
if (veryVerbose) {
printf("\t\t\tErase elements between ");
P_(BEGIN_POS); P(END_POS);
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t m = 0;
for (m = 0; m < INIT_LENGTH; ++m) {
mX[m] = VALUES[m % NUM_VALUES];
}
testAllocator.setAllocationLimit(AL);
mX.erase(mX.begin() + BEGIN_POS, mX.begin() + END_POS);
// test erase here
for (m = 0; m < BEGIN_POS; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
END_POS, m,
VALUES[m % NUM_VALUES] == X[m]);
}
for (; m < LENGTH; ++m) {
LOOP5_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP,
END_POS, m,
VALUES[(m + NUM_ELEMENTS) % NUM_VALUES] == X[m]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase19Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING ERASE
//
// Concerns:
// 1 'pop_back' asserts on undefined behavior when the string is empty,
// 2 'erase' asserts on undefined behavior when iterators are not valid
// on the string being tested or they don't make a valid range.
//
// Plan:
// For concern (1), create an empty string and call 'pop_back' which
// should assert. For concern (2), create a non-empty string and test
// 'erase' with different combinations of invalid iterators and iterator
// ranges.
//
// Testing:
// void pop_back();
// iterator erase(const_iterator p);
// iterator erase(const_iterator first, iterator last);
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\tnegative testing pop_back\n");
{
Obj mX;
// pop_back on empty string
ASSERT_SAFE_FAIL(mX.pop_back());
}
if (veryVerbose) printf("\tnegative testing erase(iterator)\n");
{
Obj mX(g("ABCDE"));
// position < begin()
ASSERT_SAFE_FAIL(mX.erase(mX.begin() - 1));
// position >= end()
ASSERT_SAFE_FAIL(mX.erase(mX.end()));
ASSERT_SAFE_FAIL(mX.erase(mX.end() + 1));
}
if (veryVerbose) printf("\tnegative testing erase(iterator, iterator)\n");
{
Obj mX(g("ABCDE"));
// first < begin()
ASSERT_SAFE_FAIL(mX.erase(mX.begin() - 1, mX.end()));
// last > end()
ASSERT_SAFE_FAIL(mX.erase(mX.begin(), mX.end() + 1));
// first > last
ASSERT_SAFE_FAIL(mX.erase(mX.end(), mX.begin()));
ASSERT_SAFE_FAIL(mX.erase(mX.begin() + 1, mX.begin()));
ASSERT_SAFE_FAIL(mX.erase(mX.end(), mX.end() - 1));
// first > end()
ASSERT_SAFE_FAIL(mX.erase(mX.end() + 1, mX.end()));
// last < begin()
ASSERT_SAFE_FAIL(mX.erase(mX.begin(), mX.begin() - 1));
}
if (veryVerbose) {
printf("\tnow try some valid parameters for pop_back/erase\n");
}
{
Obj mX(g("ABCDE"));
ASSERT_SAFE_PASS(mX.pop_back());
ASSERT_SAFE_PASS(mX.erase(mX.begin()));
ASSERT_SAFE_PASS(mX.erase(mX.begin(), mX.end()));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase18()
{
// --------------------------------------------------------------------
// TESTING INSERTION:
// We have the following concerns:
// 1) That the resulting string value is correct.
// 2) That the 'insert' return (if any) value is a reference to self,
// or a valid iterator, even when the string underwent a reallocation.
// 3) That the resulting capacity is correctly set up.
// 4) That existing elements are moved via Traits::move.
// 5) That insertion is exception neutral w.r.t. memory allocation.
// 6) The internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
//
// Plan:
// For insertion we will create objects of varying sizes and capacities
// containing default values, and insert a distinct 'value' at various
// positions, or a variable number of copies of this value. Perform the
// above tests:
// - Without exceptions, and compute the number of allocations.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*,
// but do not compute the number of allocations.
// and use basic accessors to verify the resulting
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
//
// Testing:
// string& insert(size_type pos, size_type n, C c);
// iterator insert(const_iterator p, size_type n, C c);
// iterator insert(const_iterator p, C c);
// // string& insert(size_type pos, const C *s, n2);
// // string& insert(size_type pos, const C *s);
// -----------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
enum {
INSERT_CHAR_MODE_FIRST = 0,
INSERT_CHAR_N_AT_INDEX = 0,
INSERT_CHAR_N_AT_ITERATOR = 1,
INSERT_CHAR_AT_ITERATOR = 2,
INSERT_CHAR_MODE_LAST = 2
};
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 }
#else
// This portion of the test would be appropriate if we performed
// short-string optimization, for which the boundary sizes would differ
// in 32 and 64-bit modes, but we do not in this version.
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\nTesting 'insert'.\n");
if (verbose) printf("\tUsing a single 'value'.\n");
for (int insertMode = INSERT_CHAR_AT_ITERATOR;
insertMode <= INSERT_CHAR_MODE_LAST;
++insertMode)
{
if (verbose)
printf("\t\tUsing string with insertMode = %d.\n", insertMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
const TYPE VALUE = VALUES[i % NUM_VALUES];
const size_t LENGTH = INIT_LENGTH + 1;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
Obj mX(INIT_LENGTH, DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tInsert with "); P_(LENGTH);
printf(" at "); P_(POS);
printf(" using "); P(VALUE);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch (insertMode) {
case INSERT_CHAR_AT_ITERATOR: {
// iterator insert(iterator p, C c);
iterator result = mX.insert(mX.begin() + POS, VALUE);
LOOP3_ASSERT(INIT_LINE, i, j,
X.begin() + POS == result);
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP3_ASSERT(INIT_LINE, i, j, LENGTH == X.size());
LOOP3_ASSERT(INIT_LINE, i, j, CAP == X.capacity());
for (k = 0; k < POS; ++k) {
LOOP4_ASSERT(INIT_LINE, LENGTH, POS, k,
VALUES[k % NUM_VALUES] == X[k]);
}
LOOP3_ASSERT(INIT_LINE, LENGTH, POS, VALUE == X[POS]);
for (++k; k < LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LENGTH, POS, k,
VALUES[(k - 1) % NUM_VALUES] == X[k]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
BB + REALLOC == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
B + A_ALLOC == A);
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
for (int insertMode = INSERT_CHAR_MODE_FIRST;
insertMode < INSERT_CHAR_AT_ITERATOR;
++insertMode)
{
if (verbose)
printf("\tUsing 'n' copies of 'value', insertMode = %d.\n",
insertMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const int NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tInsert "); P_(NUM_ELEMENTS);
printf("at "); P_(POS);
printf("using "); P(VALUE);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch (insertMode) {
case INSERT_CHAR_N_AT_ITERATOR: {
// void insert(iterator p, size_type n, C c);
mX.insert(mX.begin() + POS, NUM_ELEMENTS, VALUE);
} break;
case INSERT_CHAR_N_AT_INDEX: {
// string& insert(pos, n, C c);
Obj &result = mX.insert(POS, NUM_ELEMENTS, VALUE);
LOOP3_ASSERT(INIT_LINE, i, j, &X == &result);
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
LENGTH == X.size());
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
CAP == X.capacity());
size_t m = 0;
for (k = 0; k < POS; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, j, k,
VALUES[k % NUM_VALUES] == X[k]);
}
for (; k < POS + NUM_ELEMENTS; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, j, k,
VALUE == X[k]);
}
for (m = POS; k < LENGTH; ++k, ++m) {
LOOP5_ASSERT(INIT_LINE, LINE, j, k, m,
VALUES[m % NUM_VALUES] == X[k]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
BB + REALLOC == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
B + A_ALLOC == A);
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
for (int insertMode = INSERT_CHAR_MODE_FIRST;
insertMode <= INSERT_CHAR_MODE_LAST;
++insertMode)
{
if (verbose)
printf("\t\tUsing string with insertMode = %d.\n", insertMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const size_t NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(
testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
const size_t CAP = computeNewCapacity(
LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
testAllocator.setAllocationLimit(AL);
bool checkResultFlag = false;
switch (insertMode) {
case INSERT_CHAR_N_AT_INDEX: {
// string& insert(pos, n, C c);
Obj &result = mX.insert(POS,
NUM_ELEMENTS,
VALUE);
LOOP3_ASSERT(INIT_LINE, i, j, &X == &result);
checkResultFlag = true;
} break;
case INSERT_CHAR_N_AT_ITERATOR: {
// iterator insert(const_iterator p,
// size_type n, C c);
mX.insert(mX.begin() + POS,
NUM_ELEMENTS,
VALUE);
checkResultFlag = true;
} break;
case INSERT_CHAR_AT_ITERATOR: {
if (NUM_ELEMENTS != 1) {
break;
}
// iterator insert(iterator p, C c);
iterator result =
mX.insert(mX.begin() + POS, VALUE);
LOOP3_ASSERT(INIT_LINE, i, j,
X.begin() + POS == result);
checkResultFlag = true;
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
if (checkResultFlag) {
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
LENGTH == X.size());
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
CAP == X.capacity());
size_t k;
for (k = 0; k < POS; ++k) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
DEFAULT_VALUE == X[k]);
}
for (; k < POS + NUM_ELEMENTS; ++k) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
VALUE == X[k]);
}
for (; k < LENGTH; ++k) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
DEFAULT_VALUE == X[k]);
}
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
template <class CONTAINER>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase18Range(const CONTAINER&)
{
// --------------------------------------------------------------------
// TESTING INSERTION:
// We have the following concerns:
// 1) That the resulting string value is correct.
// 2) That the initial range is correctly imported and then moved if the
// initial 'FWD_ITER' is an input iterator.
// 3) That the resulting capacity is correctly set up if the initial
// 'FWD_ITER' is a random-access iterator.
// 4) That existing elements are moved without copy-construction if the
// bitwise-moveable trait is present.
// 5) That insertion is exception neutral w.r.t. memory allocation.
// 6) The internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
//
// Plan:
// For insertion we will create objects of varying sizes with different
// 'value' as argument. Perform the above tests:
// - From the parameterized 'CONTAINER::const_iterator'.
// - Without exceptions, and compute the number of allocations.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*,
// but do not compute the number of allocations.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
// In addition, the number of allocations should reflect proper internal
// memory management: the number of allocations should equal the sum of
// - NUM_ELEMENTS + (INIT_LENGTH - POS) if the type uses an allocator
// and is not bitwise-moveable, 0 otherwise
// - 1 if there is a change in capacity, 0 otherwise
// - 1 if the type uses an allocator and the value is an alias.
// -
// For concern 4, we test with a bitwise-moveable type that the only
// reallocations are for the new elements plus one if the string
// undergoes a reallocation (capacity changes).
//
// template <class InputIter>
// iterator insert(const_iterator p, InputIter first, InputIter last);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const int INPUT_ITERATOR_TAG =
bsl::is_same<std::input_iterator_tag,
typename bsl::iterator_traits<
typename CONTAINER::const_iterator>::iterator_category
>::value;
enum {
INSERT_STRING_MODE_FIRST = 0,
INSERT_SUBSTRING_AT_INDEX = 0,
INSERT_STRING_AT_INDEX = 1,
INSERT_CSTRING_N_AT_INDEX = 2,
INSERT_CSTRING_AT_INDEX = 3,
INSERT_STRING_AT_ITERATOR = 4,
INSERT_STRING_AT_CONST_ITERATOR = 5,
INSERT_STRING_MODE_LAST = 5
};
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 },
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
static const struct {
int d_lineNum; // source line number
const char *d_spec; // container spec
} U_DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_U_DATA = sizeof U_DATA / sizeof *U_DATA;
for (int insertMode = INSERT_STRING_AT_INDEX;
insertMode <= INSERT_STRING_MODE_LAST;
++insertMode)
{
if (verbose)
printf("\tUsing string with insertMode = %d.\n", insertMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tInsert "); P_(NUM_ELEMENTS);
printf("at "); P_(POS);
printf("using "); P(SPEC);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch(insertMode) {
case INSERT_STRING_AT_INDEX: {
// string& insert(pos1, const string<C,CT,A>& str);
Obj &result = mX.insert(POS, Y);
ASSERT(&result == &mX);
} break;
case INSERT_CSTRING_N_AT_INDEX: {
// string& insert(pos, const C *s, n);
Obj &result = mX.insert(POS,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case INSERT_CSTRING_AT_INDEX: {
// string& insert(pos, const C *s);
Obj &result = mX.insert(POS, Y.c_str());
ASSERT(&result == &mX);
} break;
case INSERT_STRING_AT_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS, mU.begin(), mU.end());
} break;
case INSERT_STRING_AT_CONST_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS, U.begin(), U.end());
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
CAP == X.capacity());
}
size_t m = 0;
for (k = 0; k < POS; ++k, ++m) {
LOOP4_ASSERT(INIT_LINE, LINE, j, k,
VALUES[m % NUM_VALUES] == X[k]);
}
for (m = 0; k < POS + NUM_ELEMENTS; ++k, ++m) {
LOOP5_ASSERT(INIT_LINE, LINE, j, k, m,
Y[m] == X[k]);
}
for (m = POS; k < LENGTH; ++k, ++m) {
LOOP5_ASSERT(INIT_LINE, LINE, j, k, m,
VALUES[m % NUM_VALUES] == X[k]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
BB + REALLOC <= AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
B + A_ALLOC <= A);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tUsing string with insertMode = %d.\n",
INSERT_SUBSTRING_AT_INDEX);
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
for (size_t k = 0; k <= NUM_ELEMENTS; ++k) {
const size_t POS = j;
const size_t POS2 = k;
const size_t NUM_ELEMENTS_INS = NUM_ELEMENTS - POS2;
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS_INS;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t n;
for (n = 0; n < INIT_LENGTH; ++n) {
mX[n] = VALUES[n % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tInsert "); P_(NUM_ELEMENTS_INS);
printf("at "); P_(POS);
printf("using "); P_(SPEC);
printf("starting at "); P(POS2);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
// string& insert(pos1, const string<C,CT,A>& str,
// pos2, n);
Obj &result = mX.insert(POS, Y, POS2, NUM_ELEMENTS);
ASSERT(&result == &mX);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
CAP == X.capacity());
}
size_t m;
for (n = 0; n < POS; ++n) {
LOOP4_ASSERT(INIT_LINE, LINE, j, n,
VALUES[n % NUM_VALUES] == X[n]);
}
for (m = 0; m < NUM_ELEMENTS_INS; ++m, ++n) {
LOOP5_ASSERT(INIT_LINE, LINE, j, m, n,
Y[POS2 + m] == X[n]);
}
for (m = POS; n < LENGTH; ++m, ++n) {
LOOP5_ASSERT(INIT_LINE, LINE, j, m, n,
VALUES[m % NUM_VALUES] == X[n]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
BB + REALLOC <= AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, j,
B + A_ALLOC <= A);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
for (int insertMode = INSERT_STRING_MODE_FIRST;
insertMode <= INSERT_STRING_MODE_LAST;
++insertMode)
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(
testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
const size_t CAP = computeNewCapacity(
LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
testAllocator.setAllocationLimit(AL);
switch(insertMode) {
case INSERT_STRING_AT_INDEX: {
// string& insert(pos1, const string<C,CT,A>& str);
Obj &result = mX.insert(POS, Y);
ASSERT(&result == &mX);
} break;
case INSERT_CSTRING_N_AT_INDEX: {
// string& insert(pos, const C *s, n);
Obj &result = mX.insert(POS,
Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case INSERT_CSTRING_AT_INDEX: {
// string& insert(pos, const C *s);
Obj &result = mX.insert(POS, Y.c_str());
ASSERT(&result == &mX);
} break;
case INSERT_STRING_AT_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS,
mU.begin(),
mU.end());
} break;
case INSERT_STRING_AT_CONST_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS,
U.begin(),
U.end());
} break;
case INSERT_SUBSTRING_AT_INDEX: {
// string& insert(pos1, const string<C,CT,A>& str,
// pos2, n);
mX.insert(POS, Y, 0, NUM_ELEMENTS);
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP4_ASSERT(INIT_LINE, LINE, i, j,
CAP == X.capacity());
}
size_t k, m;
for (k = 0; k < POS; ++k) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
DEFAULT_VALUE == X[k]);
}
for (m = 0; m < NUM_ELEMENTS; ++k, ++m) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
Y[m] == X[k]);
}
for (m = POS; k < LENGTH; ++k) {
LOOP5_ASSERT(INIT_LINE, LINE, i, j, k,
DEFAULT_VALUE == X[k]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tTesting aliasing concerns.\n");
for (int insertMode = INSERT_STRING_MODE_FIRST;
insertMode <= INSERT_STRING_MODE_LAST;
++insertMode)
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) {
printf("\t\t\tInsert itself");
printf(" at "); P(POS);
}
switch(insertMode) {
case INSERT_STRING_AT_INDEX: {
// string& insert(pos1, const string<C,CT,A>& str);
mX.insert(POS, Y);
mY.insert(POS, Y);
} break;
case INSERT_CSTRING_N_AT_INDEX: {
// string& insert(pos, const C *s, n);
mX.insert(POS, Y.data(), INIT_LENGTH);
mY.insert(POS, Y.data(), INIT_LENGTH);
} break;
case INSERT_CSTRING_AT_INDEX: {
// string& insert(pos, const C *s);
mX.insert(POS, Y.c_str());
mY.insert(POS, Y.c_str());
} break;
case INSERT_SUBSTRING_AT_INDEX: {
// string& insert(pos1, const string<C,CT,A>& str,
// pos2, n);
mX.insert(POS, Y, 0, INIT_LENGTH);
mY.insert(POS, Y, 0, INIT_LENGTH);
} break;
case INSERT_STRING_AT_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS, Y.begin(), Y.end());
mY.insert(mY.cbegin() + POS, Y.begin(), Y.end());
} break;
case INSERT_STRING_AT_CONST_ITERATOR: {
// template <class InputIter>
// insert(const_iterator p, InputIter first, last);
mX.insert(mX.cbegin() + POS, mY.begin(), mY.end());
mY.insert(mY.cbegin() + POS, mY.begin(), mY.end());
} break;
default:
printf("***UNKNOWN INSERT MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP4_ASSERT(INIT_LINE, i, INIT_CAP, POS, X == Y);
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
for (size_t j = 0; j <= INIT_LENGTH; ++j) {
const size_t POS = j;
for (size_t h = 0; h < INIT_LENGTH; ++h) {
for (size_t m = 0; m < INIT_LENGTH; ++m) {
const size_t INDEX = h;
const size_t NUM_ELEMENTS = m;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator));
const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) {
printf("\t\t\tInsert substring of itself");
printf(" with "); P_(INDEX); P(NUM_ELEMENTS);
printf(" at "); P_(POS);
}
mX.insert(POS, Y, INDEX, NUM_ELEMENTS);
mY.insert(POS, Y, INDEX, NUM_ELEMENTS);
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP5_ASSERT(INIT_LINE, i, INIT_CAP, POS, INDEX,
X == Y);
}
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase18Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING INSERTION:
//
// Concerns:
// 1 'insert' methods assert on undefined behavior when either a NULL
// C-string pointer is passed or invalid iterators are passed. Other
// valid parameters do not change the ability of 'insert' to assert on
// invalid parameters.
//
// Plan:
// Construct a string object with some string data, call 'insert' with a
// NULL C-string pointer and verify that it asserts. Then call 'insert'
// with invalid iterators and verify that it asserts.
//
// Testing:
// string& insert(size_type pos, const C *s);
// string& insert(size_type pos, const C *s, n2);
// iterator insert(const_iterator p, C c);
// iterator insert(const_iterator p, size_type n, C c);
// template <class InputIter>
// iterator insert(const_iterator p, InputIter first, InputIter last);
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\tnegative testing insert(pos, s)\n");
{
Obj mX(g("ABCDE"));
const TYPE *nullStr = 0;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
ASSERT_SAFE_FAIL(mX.insert(1, nullStr));
ASSERT_SAFE_FAIL(mX.insert(mX.length() + 1, nullStr));
ASSERT_SAFE_PASS(mX.insert(1, mX.c_str()));
}
if (veryVerbose) printf("\tnegative testing insert(pos, s, n)\n");
{
Obj mX(g("ABCDE"));
const TYPE *nullStr = 0;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
ASSERT_SAFE_PASS(mX.insert(1, nullStr, 0));
ASSERT_SAFE_FAIL(mX.insert(mX.length() + 1, nullStr, 10));
ASSERT_SAFE_PASS(mX.insert(1, mX.c_str(), mX.length()));
}
if (veryVerbose) printf("\tnegative testing insert(p, c)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
// position < begin()
ASSERT_SAFE_FAIL(mX.insert(X.begin() - 1, X[0]));
// position > end()
ASSERT_SAFE_FAIL(mX.insert(X.end() + 1, X[0]));
// begin() <= position < end()
ASSERT_SAFE_PASS(mX.insert(X.begin() + 1, X[0]));
}
if (veryVerbose) printf("\tnegative testing insert(p, n, c)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
// position < begin()
ASSERT_SAFE_FAIL(mX.insert(X.begin() - 1, X[0], 0));
ASSERT_SAFE_FAIL(mX.insert(X.begin() - 1, X[0], 2));
// position > end()
ASSERT_SAFE_FAIL(mX.insert(X.end() + 1, X[0], 0));
ASSERT_SAFE_FAIL(mX.insert(X.end() + 1, X[0], 2));
// begin() <= position <= end()
ASSERT_SAFE_PASS(mX.insert(X.begin() + 1, X[0], 0));
ASSERT_SAFE_PASS(mX.insert(X.begin() + 1, X[0], 2));
}
if (veryVerbose) printf("\tnegative testing insert(p, first, last)\n");
{
Obj mX(g("ABCDE"));
const Obj& X = mX;
Obj mY(g("ABE"));
const Obj& Y = mY;
// position < begin()
ASSERT_SAFE_FAIL(mX.insert(X.begin() - 1, Y.begin(), Y.end()));
// position > end()
ASSERT_SAFE_FAIL(mX.insert(X.end() + 1, Y.begin(), Y.end()));
// first > last
ASSERT_SAFE_FAIL(mX.insert(X.begin(), Y.end(), Y.begin()));
// begin() <= position <= end() && first <= last
ASSERT_SAFE_PASS(mX.insert(X.begin(), Y.begin(), Y.end()));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase17()
{
// --------------------------------------------------------------------
// TESTING 'append'
//
// Plan:
// For appending, we will create objects of varying sizes containing
// default values for type T, and then append different 'value'. Perform
// the above tests:
// - With various initial values before the 'append'.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
//
// Testing:
// string& append(size_type n, C c);
// // operator+=(c);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 },
{ L_, 17 },
{ L_, 19 },
{ L_, 21 },
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 },
{ L_, 35 },
{ L_, 40 },
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\nTesting 'append'.\n");
if (verbose) printf("\tUsing multiple copies of 'value'.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const int NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tAppend "); P_(NUM_ELEMENTS);
printf("using "); P(VALUE);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
// string& append(n, C c);
Obj &result = mX.append(NUM_ELEMENTS, VALUE);
LOOP2_ASSERT(INIT_LINE, i, &X == &result);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(INIT_LINE, LINE, LENGTH == X.size());
LOOP2_ASSERT(INIT_LINE, LINE, CAP == X.capacity());
for (k = 0; k < INIT_LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
VALUES[k % NUM_VALUES] == X[k]);
}
for (; k < LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
VALUE == X[k]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
BB + REALLOC == AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
B + A_ALLOC == A);
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const size_t NUM_ELEMENTS = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t CAP = computeNewCapacity(LENGTH,
X.length(),
X.capacity(),
X.max_size());
testAllocator.setAllocationLimit(AL);
// void append(size_type n, C c);
mX.append(NUM_ELEMENTS, VALUE);
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(INIT_LINE, LINE, LENGTH == X.size());
LOOP2_ASSERT(INIT_LINE, LINE, CAP == X.capacity());
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
DEFAULT_VALUE == X[k]);
}
for (; k < LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
VALUE == X[k]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
template <class CONTAINER>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase17Range(const CONTAINER&)
{
// --------------------------------------------------------------------
// TESTING 'append'
//
// Plan:
// For appending we will create objects of varying sizes containing
// default values for type T, and then append different 'value' as
// argument. Perform the above tests:
// - From the parameterized 'CONTAINER::const_iterator'.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
//
// Testing:
// string& append(const string<C,CT,A>& str);
// string& append(const string<C,CT,A>& str, pos, n);
// string& append(const C *s, size_type n);
// string& append(const C *s);
// template <class InputIter>
// append(InputIter first, InputIter last);
// // operator+=(const string& rhs);
// // operator+=(const C *s);
// operator+=(const StringRefData& strRefData);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const int INPUT_ITERATOR_TAG =
bsl::is_same<std::input_iterator_tag,
typename bsl::iterator_traits<
typename CONTAINER::const_iterator>::iterator_category
>::value;
enum {
APPEND_STRING_MODE_FIRST = 0,
APPEND_SUBSTRING = 0,
APPEND_STRING = 1,
APPEND_CSTRING_N = 2,
APPEND_CSTRING_NULL_0 = 3,
APPEND_CSTRING = 4,
APPEND_RANGE = 5,
APPEND_CONST_RANGE = 6,
APPEND_STRINGREFDATA = 7,
APPEND_STRING_MODE_LAST = 7
};
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 }
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
static const struct {
int d_lineNum; // source line number
const char *d_spec; // container spec
} U_DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_U_DATA = sizeof U_DATA / sizeof *U_DATA;
for (int appendMode = APPEND_STRING;
appendMode <= APPEND_STRING_MODE_LAST;
++appendMode)
{
if (verbose)
printf("\tUsing string with appendMode = %d.\n", appendMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS =
(APPEND_CSTRING_NULL_0 == appendMode) ? 0 : strlen(SPEC);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
bslstl::StringRefData<TYPE> mV(&*Y.begin(),
&*Y.end());
const bslstl::StringRefData<TYPE> V = mV;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t k;
for (k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tInsert "); P_(NUM_ELEMENTS);
printf("using "); P(SPEC);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
switch(appendMode) {
case APPEND_STRING: {
// string& append(const string<C,CT,A>& str);
Obj &result = mX.append(Y);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING_N: {
// string& append(pos, const C *s, n);
Obj &result = mX.append(Y.data(),
NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING_NULL_0: {
// string& append(pos, const C *s, n);
Obj &result = mX.append(0, NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING: {
// string& append(const C *s);
Obj &result = mX.append(Y.c_str());
ASSERT(&result == &mX);
} break;
case APPEND_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(mU.begin(), mU.end());
} break;
case APPEND_CONST_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(U.begin(), U.end());
} break;
case APPEND_STRINGREFDATA: {
//operator+=(const StringRefData& strRefData);
mX += V;
} break;
default:
printf("***UNKNOWN APPEND MODE***\n");
ASSERT(0);
};
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(INIT_LINE, LINE, LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP2_ASSERT(INIT_LINE, LINE, CAP == X.capacity());
}
size_t m = 0;
for (k = 0; k < INIT_LENGTH; ++k, ++m) {
LOOP3_ASSERT(INIT_LINE, LINE, k,
VALUES[m % NUM_VALUES] == X[k]);
}
for (m = 0; k < LENGTH; ++k, ++m) {
LOOP4_ASSERT(INIT_LINE, LINE, k, m,
Y[m] == X[k]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
BB + REALLOC <= AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
B + A_ALLOC <= A);
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tUsing string with appendMode = %d.\n",
APPEND_SUBSTRING);
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS = strlen(SPEC);
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t k = 0; k <= NUM_ELEMENTS; ++k) {
const size_t POS2 = k;
const size_t NUM_ELEMENTS_INS = NUM_ELEMENTS - POS2;
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS_INS;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
size_t n;
for (n = 0; n < INIT_LENGTH; ++n) {
mX[n] = VALUES[n % NUM_VALUES];
}
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
if (veryVerbose) {
printf("\t\t\tAppend"); P_(NUM_ELEMENTS_INS);
printf("using "); P_(SPEC);
printf("starting at "); P(POS2);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore:"); P_(BB); P(B);
}
// string& append(const string<C,CT,A>& str,
// pos2, n);
Obj &result = mX.append(Y, POS2, NUM_ELEMENTS);
ASSERT(&result == &mX);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter :"); P_(AA); P(A);
T_; T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(INIT_LINE, LINE, LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP2_ASSERT(INIT_LINE, LINE, CAP == X.capacity());
}
size_t m;
for (n = 0; n < INIT_LENGTH; ++n) {
LOOP3_ASSERT(INIT_LINE, LINE, n,
VALUES[n % NUM_VALUES] == X[n]);
}
for (m = 0; m < NUM_ELEMENTS_INS; ++m, ++n) {
LOOP4_ASSERT(INIT_LINE, LINE, m, n,
Y[POS2 + m] == X[n]);
}
const int REALLOC = X.capacity() > INIT_CAP;
const int A_ALLOC =
DEFAULT_CAPACITY >= INIT_CAP &&
X.capacity() > DEFAULT_CAPACITY;
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
BB + REALLOC <= AA);
LOOP4_ASSERT(INIT_LINE, INIT_LENGTH, INIT_CAP, CAP,
B + A_ALLOC <= A);
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tWith exceptions.\n");
for (int appendMode = APPEND_STRING_MODE_FIRST;
appendMode <= APPEND_STRING_MODE_LAST;
++appendMode)
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t NUM_ELEMENTS =
(APPEND_CSTRING_NULL_0 == appendMode) ? 0 : strlen(SPEC);
const size_t LENGTH = INIT_LENGTH + NUM_ELEMENTS;
Obj mY(g(SPEC)); const Obj& Y = mY;
CONTAINER mU(Y); const CONTAINER& U = mU;
bslstl::StringRefData<TYPE> mV(&*Y.begin(),
&*Y.end());
const bslstl::StringRefData<TYPE> V = mV;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
const size_t INIT_CAP = X.capacity();
const size_t CAP = computeNewCapacity(LENGTH,
INIT_LENGTH,
INIT_CAP,
X.max_size());
testAllocator.setAllocationLimit(AL);
switch(appendMode) {
case APPEND_STRING: {
// string& append(const string<C,CT,A>& str);
Obj &result = mX.append(Y);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING_N: {
// string& append(const C *s, n);
Obj &result = mX.append(Y.data(), NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING_NULL_0: {
// string& append(const C *s, n); 's = 0';
Obj &result = mX.append(0, NUM_ELEMENTS);
ASSERT(&result == &mX);
} break;
case APPEND_CSTRING: {
// string& append(const C *s);
Obj &result = mX.append(Y.c_str());
ASSERT(&result == &mX);
} break;
case APPEND_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(mU.begin(), mU.end());
} break;
case APPEND_CONST_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(U.begin(), U.end());
} break;
case APPEND_SUBSTRING: {
// string& append(const string<C,CT,A>& str, pos2, n);
mX.append(Y, 0, NUM_ELEMENTS);
} break;
case APPEND_STRINGREFDATA: {
//operator+=(const StringRefData& strRefData);
mX += V;
} break;
default:
printf("***UNKNOWN APPEND MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(INIT_LINE, LINE, LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP2_ASSERT(INIT_LINE, LINE, CAP == X.capacity());
}
size_t k, m;
for (k = 0; k < INIT_LENGTH; ++k) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
DEFAULT_VALUE == X[k]);
}
for (m = 0; m < NUM_ELEMENTS; ++k, ++m) {
LOOP4_ASSERT(INIT_LINE, LINE, i, k,
Y[m] == X[k]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
if (verbose) printf("\tTesting aliasing concerns.\n");
for (int appendMode = APPEND_STRING_MODE_FIRST;
appendMode <= APPEND_STRING_MODE_LAST;
++appendMode)
{
if (verbose)
printf("\tUsing string with appendMode = %d.\n", appendMode);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
bslstl::StringRefData<TYPE> mV(&*Y.begin(),
&*Y.end());
const bslstl::StringRefData<TYPE> V = mV;
if (veryVerbose) {
printf("\t\t\tAppend itself.\n");
}
switch(appendMode) {
case APPEND_STRING: {
// string& append(const string<C,CT,A>& str);
mX.append(Y);
mY.append(Y);
} break;
case APPEND_CSTRING_N: {
// string& append(pos, const C *s, n);
mX.append(Y.data(), INIT_LENGTH);
mY.append(Y.data(), INIT_LENGTH);
} break;
case APPEND_CSTRING_NULL_0: {
// string& append(pos, const C *s, n);
mX.append(0, 0);
mY.append(0, 0);
} break;
case APPEND_CSTRING: {
// string& append(const C *s);
mX.append(Y.c_str());
mY.append(Y.c_str());
} break;
case APPEND_SUBSTRING: {
// string& append(const string<C,CT,A>& str, pos2, n);
mX.append(Y, 0, INIT_LENGTH);
mY.append(Y, 0, INIT_LENGTH);
} break;
case APPEND_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(mY.begin(), mY.end());
mY.append(mY.begin(), mY.end());
} break;
case APPEND_CONST_RANGE: {
// template <class InputIter>
// void append(InputIter first, last);
mX.append(Y.begin(), Y.end());
mY.append(Y.begin(), Y.end());
} break;
case APPEND_STRINGREFDATA: {
//operator+=(const StringRefData& strRefData);
mX += V;
mY += V;
} break;
default:
printf("***UNKNOWN APPEND MODE***\n");
ASSERT(0);
};
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP5_ASSERT(INIT_LINE, appendMode, INIT_RES, X, Y, X == Y);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
{
if (verbose) printf("\tUsing string with appendMode = %d (complete)."
"\n",
APPEND_SUBSTRING);
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
for (int l = i; l < NUM_DATA; ++l) {
const size_t INIT_RES = DATA[l].d_length;
ASSERT(INIT_LENGTH <= INIT_RES);
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH); P_(INIT_RES);
printf("using distinct (cyclic) values.\n");
}
for (size_t h = 0; h < INIT_LENGTH; ++h) {
for (size_t m = 0; m < INIT_LENGTH; ++m) {
const size_t INDEX = h;
const size_t NUM_ELEMENTS = m;
Obj mX(INIT_LENGTH,
DEFAULT_VALUE,
AllocType(&testAllocator)); const Obj& X = mX;
mX.reserve(INIT_RES);
for (size_t k = 0; k < INIT_LENGTH; ++k) {
mX[k] = VALUES[k % NUM_VALUES];
}
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) {
printf("\t\t\tAppend substring of itself");
printf(" with "); P_(INDEX); P(NUM_ELEMENTS);
}
// string& append(const string<C,CT,A>& str, pos2, n);
mX.append(Y, INDEX, NUM_ELEMENTS);
mY.append(Y, INDEX, NUM_ELEMENTS);
if (veryVerbose) {
T_; T_; T_; T_; P(X);
T_; T_; T_; T_; P(Y);
}
LOOP5_ASSERT(INIT_LINE, INIT_RES, INDEX, X, Y, X == Y);
}
}
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase17Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING 'append'
//
// Concerns:
// 'append', 'operator+=', and 'operator+' assert on undefined behavior:
// 1 when a character string pointer parameter is NULL,
// 2 when the 'first'/'last' parameters do not specify a valid iterator
// range
//
// Plan:
// 1 Create a string object and then test the following things that
// should produce an assert for undefined behavior:
// o call 'append' with a NULL pointer,
// o call 'operator+=' with a NULL pointer,
// o call 'operator+' with a NULL pointer,
// o call 'append' with various invalid iterator ranges.
// 2 After that, call those methods with valid parameters and verify that
// they don't assert.
//
// Testing:
// string& append(const C *s, size_type n);
// string& append(const C *s);
// template <class InputIter> append(InputIter first, InputIter last);
// operator+=(const string& rhs);
// operator+(const string& lhs, const CHAR_TYPE *rhs);
// operator+(const CHAR_TYPE *lhs, const string& rhs);
// --------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\tappend/operator+/+= with NULL\n");
{
Obj mX;
const TYPE *nullStr = 0;
ASSERT_SAFE_FAIL(mX.append(nullStr));
ASSERT_SAFE_PASS(mX.append(nullStr, 0));
ASSERT_SAFE_FAIL(mX.append(nullStr, 10));
ASSERT_SAFE_FAIL(mX += nullStr);
ASSERT_SAFE_FAIL(mX + nullStr);
ASSERT_SAFE_FAIL(nullStr + mX);
if (veryVerbose) printf("\tappend/operator+/+= with valid C-string\n");
Obj nonNull(g("ABCDE"));
ASSERT_SAFE_PASS(mX.append(nonNull.c_str()));
ASSERT_SAFE_PASS(mX.append(nonNull.c_str(), 0));
ASSERT_SAFE_PASS(mX.append(nonNull.c_str(), nonNull.length()));
ASSERT_SAFE_PASS(mX += nonNull.c_str());
ASSERT_SAFE_PASS(mX + nonNull.c_str());
ASSERT_SAFE_PASS(nonNull.c_str() + mX);
}
if (veryVerbose) printf("\t'append' with invalid range\n");
{
Obj mX;
Obj mY(g("ABCDE"));
const Obj& Y = mY;
(void) Y; // to disable "unused variable" warning
ASSERT_SAFE_FAIL(mX.append(mY.end(), mY.begin()));
ASSERT_SAFE_FAIL(mX.append(Y.end(), Y.begin()));
}
if (veryVerbose) printf("\t'append' with valid range\n");
{
Obj mX;
Obj mY(g("ABCDE"));
const Obj& Y = mY;
ASSERT_SAFE_PASS(mX.append(mY.begin(), mY.end()));
ASSERT_SAFE_PASS(mX.append(Y.begin(), Y.end()));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase16()
{
// --------------------------------------------------------------------
// TESTING ITERATORS
// Concerns:
// 1) That 'begin' and 'end' return mutable iterators for a
// reference to a modifiable string, and non-mutable iterators
// otherwise.
// 2) That the range '[begin(), end())' equals the value of the string.
// 3) Same concerns with 'rbegin' and 'rend'.
// In addition:
// 4) That 'iterator' is a pointer to 'TYPE'.
// 5) That 'const_iterator' is a pointer to 'const TYPE'.
// 6) That 'reverse_iterator' and 'const_reverse_iterator' are
// implemented by the (fully-tested) 'bslstl::ReverseIterator' over a
// pointer to 'TYPE' or 'const TYPE'.
// 6. That 'reverse_iterator' and 'const_reverse_iterator' are
// implemented by the (fully-tested) 'bsl::reverse_iterator' over a
// pointer to 'TYPE' or 'const TYPE'.
//
// Plan:
// For 1--3, for each value given by variety of specifications of
// different lengths, create a test string with this value, and access
// each element in sequence and in reverse sequence, both as a modifiable
// reference (setting it to a default value, then back to its original
// value, and as a non-modifiable reference.
//
// For 4--6, use 'bsl::is_same' to assert the identity of iterator types.
// Note that these concerns let us get away with other concerns such as
// testing that 'iter[i]' and 'iter + i' advance 'iter' by the correct
// number 'i' of positions, and other concern about traits, because
// 'bsl::iterator_traits' and 'bsl::reverse_iterator' have already been
// fully tested in the 'bslstl_iterator' component.
//
// Testing:
// iterator begin();
// iterator end();
// reverse_iterator rbegin();
// reverse_iterator rend();
// const_iterator begin();
// const_iterator end();
// const_reverse_iterator rbegin();
// const_reverse_iterator rend();
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE();
static const struct {
int d_lineNum; // source line number
const char *d_spec; // initial
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("Testing 'iterator', 'begin', and 'end',"
" and 'const' variants.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
Obj mX(g(SPEC), AllocType(&testAllocator)); const Obj& X = mX;
Obj mY(X); const Obj& Y = mY; // control
if (verbose) { P_(LINE); P(SPEC); }
size_t i = 0;
for (iterator iter = mX.begin(); iter != mX.end(); ++iter, ++i) {
LOOP_ASSERT(LINE, Y[i] == *iter);
*iter = DEFAULT_VALUE;
LOOP_ASSERT(LINE, DEFAULT_VALUE == *iter);
mX[i] = Y[i];
}
LOOP_ASSERT(LINE, LENGTH == i);
LOOP_ASSERT(LINE, Y == X);
i = 0;
for (const_iterator iter = X.begin(); iter != X.end();
++iter, ++i) {
LOOP2_ASSERT(LINE, i, Y[i] == *iter);
}
LOOP_ASSERT(LINE, LENGTH == i);
}
}
if (verbose) printf("Testing 'reverse_iterator', 'rbegin', and 'rend',"
" and 'const' variants.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const int LENGTH = static_cast<int>(strlen(SPEC));
Obj mX(g(SPEC), AllocType(&testAllocator)); const Obj& X = mX;
Obj mY(X); const Obj& Y = mY; // control
if (verbose) { P_(LINE); P(SPEC); }
int i = LENGTH - 1;
for (reverse_iterator riter = mX.rbegin(); riter != mX.rend();
++riter, --i) {
LOOP_ASSERT(LINE, Y[i] == *riter);
*riter = DEFAULT_VALUE;
LOOP_ASSERT(LINE, DEFAULT_VALUE == *riter);
mX[i] = Y[i];
}
LOOP_ASSERT(LINE, -1 == i);
LOOP_ASSERT(LINE, Y == X);
i = LENGTH - 1;
for (const_reverse_iterator riter = X.rbegin(); riter != X.rend();
++riter, --i) {
LOOP_ASSERT(LINE, Y[i] == *riter);
}
LOOP_ASSERT(LINE, -1 == i);
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase15()
{
// --------------------------------------------------------------------
// TESTING ELEMENT ACCESS
// Concerns:
// 1) That 'v[x]', as well as 'v.front()' and 'v.back()', allow to modify
// its indexed element when 'v' is an lvalue, but must not modify its
// indexed element when it is an rvalue.
// 2) That 'v.at(pos)' returns 'v[x]' or throws if 'pos == v.size())'.
// 3) That 'v.front()' is identical to 'v[0]' and 'v.back()' the same as
// 'v[v.size() - 1]'.
//
// Plan:
// For each value given by variety of specifications of different
// lengths, create a test string with this value, and access each element
// (front, back, at each position) both as a modifiable reference
// (setting it to a default value, then back to its original value, and
// as a non-modifiable reference. Verify that 'at' throws
// 'std::out_of_range' when accessing the past-the-end element.
//
// Testing:
// T& operator[](size_type position);
// T& at(size_type n);
// T& front();
// T& back();
// const T& front() const;
// const T& back() const;
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE DEFAULT_VALUE = TYPE();
static const struct {
int d_lineNum; // source line number
const char *d_spec; // initial
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tWithout exception.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
Obj mX(g(SPEC), AllocType(&testAllocator)); const Obj& X = mX;
Obj mY(X); const Obj& Y = mY; // control
if (veryVerbose) { T_; P_(LINE); P(SPEC); }
LOOP_ASSERT(LINE, Y == X);
// Test front/back.
if (!mX.empty()) {
LOOP_ASSERT(LINE, mX.front() == mX[0]);
LOOP_ASSERT(LINE, mX.back() == mX[mX.size() - 1]);
}
// Test operator[].
for (size_t j = 0; j < LENGTH; ++j) {
LOOP_ASSERT(LINE, TYPE(SPEC[j]) == X[j]);
mX[j] = DEFAULT_VALUE;
LOOP_ASSERT(LINE, DEFAULT_VALUE == X[j]);
mX.at(j) = Y[j];
LOOP_ASSERT(LINE, TYPE(SPEC[j]) == X.at(j));
}
}
}
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\tWith exceptions.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
Obj mX(g(SPEC), AllocType(&testAllocator)); const Obj& X = mX;
Obj mY(X); const Obj& Y = mY; // control
bool outOfRangeCaught = false;
try {
mX.at(LENGTH) = DEFAULT_VALUE;
}
catch (std::out_of_range) {
outOfRangeCaught = true;
}
LOOP_ASSERT(LINE, Y == X);
LOOP_ASSERT(LINE, outOfRangeCaught);
}
}
#endif
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase15Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING ELEMENT ACCESS
// Concerns:
// For a string 's', the following const and non-const operations assert
// on undefined behavior:
// 1 s[x] - when the index 'x' is out of range
// 2 s.front() - when 's' is empty
// 3 s.back() - when 's' is empty
//
// Plan:
// To test concerns (2) and (3), create an empty string and verify that
// 'front'/'back' methods assert correctly. Then insert a single
// character into the string and verify that the methods don't assert any
// more. Then remove the character to make the string empty again, and
// verify that the methods start asserting again.
//
// To test concern (1), create a string using a variety of specifications
// of different lengths, then scan the range of negative and positive
// indices for 'operator[]' and verify that 'operator[]' asserts when the
// index is out of range.
//
// Testing:
// T& operator[](size_type position);
// const T& operator[](size_type position) const;
// T& front();
// T& back();
// const T& front() const;
// const T& back() const;
// --------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
static const struct {
int d_lineNum; // source line number
const char *d_spec; // initial
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
{ L_, "ABCDEABCDEABCDEABCDE" }, // 20
#ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" }, // 15
{ L_, "ABCDEABCDEABCDEABCDE" }, // 20
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" }, // 30
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" }, // 40
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (veryVerbose) printf("\toperator[]\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
(void) LINE;
(void) LENGTH;
Obj mX(g(SPEC));
const Obj& X = mX;
const int numChars = static_cast<int>(X.size());
for (int i = -numChars - 1; i < numChars * 2 + 2; ++i) {
if (i >= 0 && i <= numChars) {
ASSERT_SAFE_PASS(X[i]);
ASSERT_SAFE_PASS(mX[i]);
}
else {
ASSERT_SAFE_FAIL(X[i]);
ASSERT_SAFE_FAIL(mX[i]);
}
}
}
}
if (veryVerbose) printf("\tfront/back\n");
{
Obj mX;
const Obj& X = mX;
ASSERT_SAFE_FAIL(X.front());
ASSERT_SAFE_FAIL(mX.front());
ASSERT_SAFE_FAIL(X.back());
ASSERT_SAFE_FAIL(mX.back());
mX.push_back(TYPE('A'));
ASSERT_SAFE_PASS(X.front());
ASSERT_SAFE_PASS(mX.front());
ASSERT_SAFE_PASS(X.back());
ASSERT_SAFE_PASS(mX.back());
mX.pop_back();
ASSERT_SAFE_FAIL(X.front());
ASSERT_SAFE_FAIL(mX.front());
ASSERT_SAFE_FAIL(X.back());
ASSERT_SAFE_FAIL(mX.back());
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase14()
{
// --------------------------------------------------------------------
// TESTING CAPACITY
// Concerns:
// 1) That 'v.reserve(n)' reserves sufficient capacity in 'v' to hold
// 'n' elements without reallocation, but does not change value.
// In addition, if 'v.reserve(n)' allocates, it must allocate for a
// capacity of exactly 'n' bytes.
// 2) That 'v.resize(n, val)' brings the new size to 'n', adding elements
// equal to 'val' if 'n' is larger than the current size.
// 3) That existing elements are moved without copy-construction if the
// bitwise-moveable trait is present.
// 4) That 'reserve' and 'resize' are exception-neutral with full
// guarantee of rollback.
// 5) That the accessors such as 'capacity', 'empty', return the correct
// value.
//
// Plan:
// For string 'v' having various initial capacities, call 'v.reserve(n)'
// for various values of 'n'. Verify that sufficient capacity is
// allocated by filling 'v' with 'n' elements. Perform each test in the
// standard 'bslma' exception-testing macro block.
//
// Testing:
// void string<C,CT,CA>::reserve(size_type n);
// void resize(size_type n);
// void resize(size_type n, C c);
// size_type max_size() const;
// size_type capacity() const;
// bool empty() const;
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
bslma::Allocator *Z = &testAllocator;
ASSERT(0 == testAllocator.numBytesInUse());
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
static const size_t EXTEND[] = {
0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15, 23, 24, 25, 30, 63, 64, 65
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
static const size_t DATA[] = {
0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15, 23, 24, 25, 30, 63, 64, 65
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tTesting 'max_size'.\n");
{
// This is the maximum value. Any larger value would be cause for
// potential bugs. Any reasonable value must be 2^31 -1 at least.
Obj X;
ASSERT(~(size_t)0 / sizeof(TYPE) - 1 >= X.max_size());
ASSERT(~(unsigned)0 / sizeof(TYPE) / 2 - 1 <= X.max_size());
}
if (verbose) printf("\tTesting 'reserve', 'capacity' and 'empty'.\n");
for (int ti = 0; ti < NUM_DATA; ++ti) {
const size_t NE = DATA[ti];
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
const size_t CAP = EXTEND[ei];
const size_t DELTA = NE > CAP ? NE - CAP : 0;
if (veryVerbose)
printf("LINE = %d, ti = %d, ei = %d\n", L_, ti, ei);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(Z); const Obj& X = mX;
LOOP_ASSERT(ti, X.empty());
stretch(&mX, CAP);
LOOP_ASSERT(ti, CAP == X.size());
LOOP_ASSERT(ti, CAP <= X.capacity());
LOOP_ASSERT(ti, !(bool)X.size() == X.empty());
testAllocator.setAllocationLimit(AL);
const Int64 NUM_ALLOC_BEFORE = testAllocator.numAllocations();
const size_t CAPACITY = X.capacity();
{
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.reserve(NE);
LOOP_ASSERT(ti, CAP == X.size());
LOOP_ASSERT(ti, CAPACITY >= NE || NE <= X.capacity());
}
// Note: assert mX unchanged via the exception guard destructor.
const Int64 NUM_ALLOC_AFTER = testAllocator.numAllocations();
LOOP_ASSERT(ti, NE > CAPACITY ||
NUM_ALLOC_BEFORE == NUM_ALLOC_AFTER);
const Int64 AL2 = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
stretch(&mX, DELTA);
LOOP_ASSERT(ti, CAP + DELTA == X.size());
LOOP_ASSERT(ti,
NUM_ALLOC_AFTER == testAllocator.numAllocations());
testAllocator.setAllocationLimit(AL2);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const size_t NE = DATA[ti];
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
const size_t CAP = EXTEND[ei];
if (veryVeryVerbose)
printf("LINE = %d, ti = %d, ei = %d\n", L_, ti, ei);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(Z); const Obj& X = mX;
stretchRemoveAll(&mX, CAP);
LOOP_ASSERT(ti, X.empty());
LOOP_ASSERT(ti, 0 == X.size());
LOOP_ASSERT(ti, CAP <= X.capacity());
testAllocator.setAllocationLimit(AL);
const Int64 NUM_ALLOC_BEFORE = testAllocator.numAllocations();
const size_t CAPACITY = X.capacity();
{
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.reserve(NE);
LOOP_ASSERT(ti, 0 == X.size());
LOOP_ASSERT(ti, NE <= X.capacity());
}
// Note: assert mX unchanged via the exception guard destructor.
const Int64 NUM_ALLOC_AFTER = testAllocator.numAllocations();
LOOP_ASSERT(ti, NE > CAPACITY ||
NUM_ALLOC_BEFORE == NUM_ALLOC_AFTER);
const Int64 AL2 = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
stretch(&mX, NE);
LOOP_ASSERT(ti, NE == X.size());
LOOP_ASSERT(ti,
NUM_ALLOC_AFTER == testAllocator.numAllocations());
testAllocator.setAllocationLimit(AL2);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
if (verbose) printf("\tTesting 'resize'.\n");
for (int ti = 0; ti < NUM_DATA; ++ti) {
const size_t NE = DATA[ti];
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
const size_t CAP = EXTEND[ei];
const size_t DELTA = NE > CAP ? NE - CAP : 0;
if (veryVerbose)
printf("LINE = %d, ti = %d, ei = %d\n", L_, ti, ei);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(Z); const Obj& X = mX;
LOOP_ASSERT(ti, X.empty());
stretch(&mX, CAP);
LOOP_ASSERT(ti, CAP == X.size());
LOOP_ASSERT(ti, CAP <= X.capacity());
LOOP_ASSERT(ti, !(bool)X.size() == X.empty());
testAllocator.setAllocationLimit(AL);
const Int64 NUM_ALLOC_BEFORE = testAllocator.numAllocations();
const size_t CAPACITY = X.capacity();
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.resize(NE, VALUES[ti % NUM_VALUES]); // test here
LOOP_ASSERT(ti, NE == X.size());
LOOP_ASSERT(ti, NE <= X.capacity());
const Int64 NUM_ALLOC_AFTER = testAllocator.numAllocations();
LOOP_ASSERT(ti, NE > CAPACITY ||
NUM_ALLOC_BEFORE == NUM_ALLOC_AFTER);
for (size_t j = CAP; j < NE; ++j) {
LOOP2_ASSERT(ti, j, VALUES[ti % NUM_VALUES] == X[j]);
}
guard.release();
const Int64 AL2 = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
stretch(&mX, DELTA);
LOOP_ASSERT(ti, NE + DELTA == X.size());
testAllocator.setAllocationLimit(AL2);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const size_t NE = DATA[ti];
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
const size_t CAP = EXTEND[ei];
const size_t DELTA = NE > CAP ? NE - CAP : 0;
if (veryVeryVerbose)
printf("LINE = %d, ti = %d, ei = %d\n", L_, ti, ei);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(Z); const Obj& X = mX;
stretchRemoveAll(&mX, CAP);
LOOP_ASSERT(ti, X.empty());
LOOP_ASSERT(ti, 0 == X.size());
LOOP_ASSERT(ti, CAP <= X.capacity());
const Int64 NUM_ALLOC_BEFORE = testAllocator.numAllocations();
const size_t CAPACITY = X.capacity();
ExceptionGuard<Obj> guard(&mX, X, L_);
testAllocator.setAllocationLimit(AL);
mX.resize(NE, VALUES[ti % NUM_VALUES]); // test here
LOOP_ASSERT(ti, NE == X.size());
LOOP_ASSERT(ti, NE <= X.capacity());
const Int64 NUM_ALLOC_AFTER = testAllocator.numAllocations();
LOOP_ASSERT(ti, NE > CAPACITY ||
NUM_ALLOC_BEFORE == NUM_ALLOC_AFTER);
for (size_t j = 0; j < NE; ++j) {
LOOP2_ASSERT(ti, j, VALUES[ti % NUM_VALUES] == X[j]);
}
guard.release();
const Int64 AL2 = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
stretch(&mX, DELTA);
LOOP_ASSERT(ti, NE + DELTA == X.size());
testAllocator.setAllocationLimit(AL2);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase13()
{
// --------------------------------------------------------------------
// TESTING 'assign'
// The concerns are the same as for the constructor with the same
// signature (case 12), except that the implementation is different,
// and in addition the previous value must be freed properly. Also, there
// is a concern about aliasing (although assigning a portion of oneself is
// not subject to aliasing in most implementations).
//
// Plan:
// For the assignment we will create objects of varying sizes containing
// default values for type T, and then assign different 'value'. Perform
// the above tests:
// - With various initial values before the assignment.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
// Note that we relax the concerns about memory consumption, since this
// is implemented as 'copy' followed by 'erase + append', and append will
// be tested more completely in test case 25.
//
// Testing:
// void assign(const string<C,CT,A>& str);
// void assign(const string<C,CT,A>& str, pos, n);
// void assign(const C *s, size_type n);
// void assign(const C *s);
// void assign(size_type n, C c);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
bslma::Allocator *Z = &testAllocator;
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
enum {
ASSIGN_STRING_MODE_FIRST = 0,
ASSIGN_SUBSTRING_AT_INDEX = 0,
ASSIGN_STRING_AT_INDEX = 1,
ASSIGN_CSTRING_N_AT_INDEX = 2,
ASSIGN_CSTRING_AT_INDEX = 3,
ASSIGN_STRING_AT_ITERATOR = 4,
ASSIGN_STRING_MODE_LAST = 5
};
if (verbose) printf("\nTesting initial-length assignment.\n");
{
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 }
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tUsing 'n' copies of 'value'.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
Obj mX(INIT_LENGTH, DEFAULT_VALUE, AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const size_t LENGTH = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
if (veryVerbose) {
printf("\t\tAssign "); P_(LENGTH);
printf(" using "); P(VALUE);
}
mX.assign(LENGTH, VALUE);
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, ti, LENGTH == X.size());
LOOP4_ASSERT(INIT_LINE, LINE, i, ti,
X.capacity() >= X.size());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP5_ASSERT(INIT_LINE, LINE, i, ti, j, VALUE == X[j]);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
if (veryVerbose) {
printf("\t\tWith initial value of ");
P_(INIT_LENGTH);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const size_t LENGTH = DATA[ti].d_length;
const TYPE VALUE = VALUES[ti % NUM_VALUES];
if (veryVerbose) {
printf("\t\tAssign "); P_(LENGTH);
printf(" using "); P(VALUE);
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH, DEFAULT_VALUE, Z);
const Obj& X = mX;
// ExceptionGuard<Obj> guard(&mX, Obj(), L_);
testAllocator.setAllocationLimit(AL);
mX.assign(LENGTH, VALUE); // test here
// guard.release();
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, ti,
LENGTH == X.size());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP4_ASSERT(INIT_LINE, ti, i, j, VALUE == X[j]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
}
}
}
#ifndef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nSkip testing assign() exception-safety.\n");
#else
if (verbose) printf("\nTesting assign() exception-safety.\n");
{
size_t defaultCapacity = Obj().capacity();
Obj src(defaultCapacity + 1, '1', &testAllocator);
Obj dst(defaultCapacity, '2', &testAllocator);
Obj dstCopy(dst, &testAllocator);
bsls::Types::Int64 oldLimit = testAllocator.allocationLimit();
{
// make the allocator throw on the next allocation
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
// the assignment will require to allocate more memory
dst.assign(src);
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
{
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
dst.assign(src, 0, Obj::npos);
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
{
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
dst.assign(src.c_str());
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
{
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
dst.assign(src.c_str(), src.size());
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
{
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
dst.assign(src.size(), 'c');
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
{
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
dst.assign(src.begin(), src.end());
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
// restore the allocator state
testAllocator.setAllocationLimit(oldLimit);
}
#endif
}
template <class TYPE, class TRAITS, class ALLOC>
template <class CONTAINER>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase13Range(const CONTAINER&)
{
// --------------------------------------------------------------------
// TESTING 'assign'
// The concerns are the same as for the constructor with the same
// signature (case 12), except that the implementation is different,
// and in addition the previous value must be freed properly.
//
// Plan:
// For the assignment we will create objects of varying sizes containing
// default values for type T, and then assign different 'value' as
// argument. Perform the above tests:
// - From the parameterized 'CONTAINER::const_iterator'.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
// Note that we relax the concerns about memory consumption, since this
// is implemented as 'erase + insert', and insert will be tested more
// completely in test case 17.
//
// Testing:
// template <class InputIter>
// assign(InputIter first, InputIter last, const A& a = A());
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
bslma::Allocator *Z = &testAllocator;
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const int INPUT_ITERATOR_TAG =
bsl::is_same<std::input_iterator_tag,
typename bsl::iterator_traits<
typename CONTAINER::const_iterator>::iterator_category
>::value;
static const struct {
int d_lineNum; // source line number
int d_length; // expected length
} DATA[] = {
//line length
//---- ------
{ L_, 0 },
{ L_, 1 },
{ L_, 2 },
{ L_, 3 },
{ L_, 4 },
{ L_, 5 },
{ L_, 9 },
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, 11 },
{ L_, 12 },
{ L_, 13 },
{ L_, 15 }
#else
{ L_, 23 },
{ L_, 24 },
{ L_, 25 },
{ L_, 30 }
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
static const struct {
int d_lineNum; // source line number
const char *d_spec; // container spec
} U_DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_U_DATA = sizeof U_DATA / sizeof *U_DATA;
if (verbose) printf("\tUsing 'CONTAINER::const_iterator'.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
if (veryVerbose) {
printf("\t\tWith initial value of "); P_(INIT_LENGTH);
printf("using default char value.\n");
}
Obj mX(INIT_LENGTH, VALUES[i % NUM_VALUES],
AllocType(&testAllocator));
const Obj& X = mX;
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
CONTAINER mU(g(SPEC)); const CONTAINER& U = mU;
if (veryVerbose) {
printf("\t\tAssign "); P_(LENGTH);
printf(" using "); P(SPEC);
}
mX.assign(U.begin(), U.end());
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, ti, LENGTH == X.size());
if (!INPUT_ITERATOR_TAG) {
LOOP4_ASSERT(INIT_LINE, LINE, i, ti,
X.capacity() >= X.size());
}
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t j = 0; j < LENGTH; ++j) {
LOOP5_ASSERT(INIT_LINE, LINE, i, ti, j, Y[j] == X[j]);
}
}
}
ASSERT(0 == testAllocator.numMismatches());
ASSERT(0 == testAllocator.numBlocksInUse());
}
if (verbose) printf("\tWith exceptions.\n");
{
for (int i = 0; i < NUM_DATA; ++i) {
const int INIT_LINE = DATA[i].d_lineNum;
const size_t INIT_LENGTH = DATA[i].d_length;
if (veryVerbose) {
printf("\t\tWith initial value of "); P_(INIT_LENGTH);
printf("using default char value.\n");
}
for (int ti = 0; ti < NUM_U_DATA; ++ti) {
const int LINE = U_DATA[ti].d_lineNum;
const char *SPEC = U_DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
CONTAINER mU(g(SPEC)); const CONTAINER& U = mU;
if (veryVerbose) {
printf("\t\tAssign "); P_(LENGTH);
printf(" using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY; // control
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mX(INIT_LENGTH, DEFAULT_VALUE, Z); const Obj& X = mX;
// ExceptionGuard<Obj> guard(&mX, Obj(), L_);
testAllocator.setAllocationLimit(AL);
mX.assign(U.begin(), U.end()); // test here
// guard.release();
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP4_ASSERT(INIT_LINE, LINE, i, ti, LENGTH == X.size());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP5_ASSERT(INIT_LINE, LINE, i, ti, j, Y[j] == X[j]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP_ASSERT(testAllocator.numMismatches(),
0 == testAllocator.numMismatches());
LOOP_ASSERT(testAllocator.numBlocksInUse(),
0 == testAllocator.numBlocksInUse());
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase13Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING 'assign'
//
// Concerns:
// 'assign' methods asserts on undefined behavior when:
// 1 C-string pointer parameter is NULL
// 2 'first' and 'last' iterators do not make a valid range
// (i.e., first > last).
//
// Plan:
// For concern (1), create a string and call 'assign' methods with NULL
// pointer.
// For concern (2), create a string and call 'assign' with two iterators
// which do not make a valid range.
//
// Testing:
// void assign(const C *s, size_type n);
// void assign(const C *s);
// template <class InputIter>
// assign(InputIter first, InputIter last, const A& a = A());
// --------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\tnegative test assign with NULL C-string\n");
{
Obj mX;
ASSERT_SAFE_FAIL(mX.assign(0));
ASSERT_SAFE_PASS(mX.assign(0, size_t(0)));
ASSERT_SAFE_FAIL(mX.assign(0, size_t(10)));
Obj mY(g("ABCD"));
ASSERT_SAFE_PASS(mX.assign(mY.c_str()));
ASSERT_SAFE_PASS(mX.assign(mY.c_str(), mY.length()));
}
if (veryVerbose) {
printf("\tnegative test assign with invalid iterator range\n");
}
{
Obj mX;
Obj mY(g("ABCD"));
// first > last
ASSERT_SAFE_FAIL(mX.assign(mY.end(), mY.begin()));
ASSERT_SAFE_FAIL(mX.assign(mY.begin() + 1, mY.begin()));
// first <= last
ASSERT_SAFE_PASS(mX.assign(mY.begin(), mY.end()));
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase12()
{
// --------------------------------------------------------------------
// TESTING CONSTRUCTORS:
// We have the following concerns:
// 1) The initial value is correct.
// 2) The initial capacity is correctly set up.
// 3) The constructor is exception neutral w.r.t. memory allocation.
// 4) The internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
// 5) The move constructor moves value, capacity, and allocator
// correctly, and without performing any allocation.
//
// Plan:
// For the constructor we will create objects of varying sizes with
// different 'value' as argument. Test first with the default value
// for type T, and then test with different values. Perform the above
// tests:
// - With and without passing in an allocator.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// - Where the object is constructed with an object allocator, and
// neither of global and default allocator is used to supply memory.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
// As for concern 5, we simply move-construct each value into a new
// string and check that the value, capacity, and allocator are as
// expected, and that no allocation was performed.
//
// Testing:
// string<C,CT,A>(const string<C,CT,A>& str, pos, n = npos, a = A());
// string<C,CT,A>(const C *s, n, a = A());
// string<C,CT,A>(const C *s, a = A());
// string<C,CT,A>(n, C c, a = A());
// string<C,CT,A>(const string<C,CT,A>& original, a = A());
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
static const struct {
int d_lineNum; // source line number
const char *d_spec; // specifications
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDE" }, // 5
{ L_, "ABCDEA" }, // 6
{ L_, "ABCDEAB" }, // 7
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" }, // 15
{ L_, "ABCDEABCDEABCDEA" }, // 16
{ L_, "ABCDEABCDEABCDEAB" }, // 17
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEA" }, // 31
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB" }, // 32
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEABC" }, // 33
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEA" }, // 63
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEAB" }, // 64
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDEAB"
"ABCDEABCDEABCDEABCDEABCDEABCDEABC" } // 65
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tTesting string(n, c, a = A()).\n");
{
if (verbose) printf("\t\tWithout passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const TYPE VALUE = VALUES[ti % NUM_VALUES];
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(VALUE);
}
Obj mX(LENGTH, VALUE); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
// LOOP2_ASSERT(LINE, ti,
// LENGTH | MAX_ALIGN_MASK == X.capacity());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, VALUE == X[j]);
}
}
}
if (verbose) printf("\t\tWith passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const TYPE VALUE = VALUES[ti % NUM_VALUES];
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(VALUE);
}
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
Obj mX(LENGTH, VALUE, AllocType(&testAllocator));
const Obj& X = mX;
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, VALUE == X[j]);
}
if (LENGTH <= DEFAULT_CAPACITY)
{
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else {
LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
}
}
}
}
if (verbose) printf("\tTesting string(const C *s, n, a = A())\n"
"\t and string(const C *s, a = A()).\n");
{
if (verbose) printf("\t\tWithout passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY; // get a valid const C*
{
Obj mX(&Y[0], LENGTH); const Obj& X = mX;
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
}
{
Obj mX(&Y[0]); const Obj& X = mX;
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
}
}
}
if (verbose) printf("\t\tWith passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY; // get a valid const C*
{
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
Obj mX(&Y[0], LENGTH, AllocType(&testAllocator));
const Obj& X = mX;
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
if (LENGTH <= DEFAULT_CAPACITY)
{
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else {
LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
}
}
{
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
Obj mX(&Y[0], AllocType(&testAllocator));
const Obj& X = mX;
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
T_; T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
if (LENGTH <= DEFAULT_CAPACITY)
{
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else {
LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
}
}
}
}
}
if (verbose) printf("\tTesting string(str, pos, n = npos, a = A()).\n");
{
if (verbose) printf("\t\tWithout passing in an allocator, nor n.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t i = 0; i < LENGTH; ++i) {
const size_t POS = i;
Obj mU(g(SPEC + POS)); const Obj& U = mU;
if (veryVerbose) {
printf("\t\t\t\tFrom "); P_(Y); P(POS);
}
Obj mX(Y, POS); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH - POS == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH - POS <= X.capacity());
LOOP2_ASSERT(LINE, ti, U == X);
}
}
}
if (verbose) printf("\t\tWithout passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t i = 0; i <= LENGTH; ++i) {
const size_t POS = i;
Obj mU(g(SPEC + POS)); const Obj& U = mU;
if (veryVerbose) {
printf("\t\t\t\tFrom "); P_(Y); P_(POS);
printf("with " ZU " chars.\n", LENGTH - POS);
}
{
Obj mX(Y, POS, Obj::npos); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH - POS == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH - POS <= X.capacity());
LOOP2_ASSERT(LINE, ti, U == X);
}
{
Obj mX(Y, POS, LENGTH); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH - POS == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH - POS <= X.capacity());
LOOP2_ASSERT(LINE, ti, U == X);
}
{
Obj mX(Y, POS, LENGTH - POS); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH - POS == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH - POS <= X.capacity());
LOOP2_ASSERT(LINE, ti, U == X);
}
if (veryVerbose) {
printf("\t\t\t\tFrom "); P_(Y); P_(POS);
printf("but at most one char.");
}
{
Obj mX(Y, POS, 1); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
if (POS < LENGTH) {
LOOP2_ASSERT(LINE, ti, 1 == X.size());
LOOP2_ASSERT(LINE, ti, 1 <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y[POS] == X[0]);
} else {
LOOP2_ASSERT(LINE, ti, 0 == X.size());
LOOP2_ASSERT(LINE, ti, TYPE() == X[0]);
}
}
}
}
}
if (verbose) printf("\t\tWith passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY;
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
Obj mX(Y, 0, LENGTH, AllocType(&testAllocator));
const Obj& X = mX;
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
if (LENGTH <= DEFAULT_CAPACITY)
{
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else {
LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
}
}
}
}
if (verbose) printf("\tWith passing an allocator and checking for "
"allocation exceptions.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const TYPE VALUE = VALUES[ti % NUM_VALUES];
if (veryVerbose) {
printf("\t\tCreating object of "); P_(LENGTH);
printf("using "); P(VALUE);
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(LENGTH, VALUE, AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, VALUE == X[j]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
if (veryVerbose) {
printf("\t\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
Obj mY(g(SPEC)); const Obj& Y = mY;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(&Y[0], AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(&Y[0], LENGTH, AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(Y, 0, LENGTH, AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
LOOP2_ASSERT(LINE, ti, Y == X);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP2_ASSERT(LINE, ti, 0 == testAllocator.numBlocksInUse());
}
}
if (verbose) printf("\tAllocators hooked up properly.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
const TYPE VALUE = VALUES[ti % NUM_VALUES];
(void) LINE;
if (veryVerbose) {
printf("\t\tCreating object of "); P(LENGTH);
}
Obj mY(g(SPEC)); const Obj& Y = mY;
for (int i = 0; i < 4; ++i) {
const Int64 TB = defaultAllocator_p->numBytesInUse();
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(TB == defaultAllocator_p->numBytesInUse());
ASSERT(0 == objectAllocator_p->numBytesInUse());
switch (i) {
case 0: {
Obj x(LENGTH, VALUE, objectAllocator_p);
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(TB == defaultAllocator_p->numBytesInUse());
} break;
case 1: {
Obj x(&Y[0], objectAllocator_p);
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(TB == defaultAllocator_p->numBytesInUse());
} break;
case 2: {
Obj x(&Y[0], LENGTH, objectAllocator_p);
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(TB == defaultAllocator_p->numBytesInUse());
} break;
case 3: {
Obj x(Y, 0, LENGTH, objectAllocator_p);
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(TB == defaultAllocator_p->numBytesInUse());
} break;
};
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(0 == objectAllocator_p->numBytesInUse());
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
template <class CONTAINER>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase12Range(const CONTAINER&)
{
// --------------------------------------------------------------------
// TESTING RANGE (TEMPLATE) CONSTRUCTORS:
// We have the following concerns:
// 1) That the initial value is correct.
// 2) That the initial range is correctly imported and then moved if the
// initial 'FWD_ITER' is an input iterator.
// 3) That the initial capacity is correctly set up if the initial
// 'FWD_ITER' is a random-access iterator.
// 4) That the constructor is exception neutral w.r.t. memory
// allocation.
// 5) That the internal memory management system is hooked up properly
// so that *all* internally allocated memory draws from a
// user-supplied allocator whenever one is specified.
//
// Plan:
// We will create objects of varying sizes and capacities containing
// default values, and insert a range containing distinct values as
// argument. Perform the above tests:
// - From the parameterized 'CONTAINER::const_iterator'.
// - With and without passing in an allocator.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// and use basic accessors to verify
// - size
// - capacity
// - element value at each index position { 0 .. length - 1 }.
//
// Testing:
// template<class InputIter>
// string(InputIter first, InputIter last, a = A());
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
const int INPUT_ITERATOR_TAG =
bsl::is_same<std::input_iterator_tag,
typename bsl::iterator_traits<
typename CONTAINER::const_iterator>::iterator_category
>::value;
static const struct {
int d_lineNum; // source line number
const char *d_spec; // initial
} DATA[] = {
//line spec length
//---- ---- ------
{ L_, "" }, // 0
{ L_, "A" }, // 1
{ L_, "AB" }, // 2
{ L_, "ABC" }, // 3
{ L_, "ABCD" }, // 4
{ L_, "ABCDEABC" }, // 8
{ L_, "ABCDEABCD" }, // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
{ L_, "ABCDEABCDEA" }, // 11
{ L_, "ABCDEABCDEAB" }, // 12
{ L_, "ABCDEABCDEABC" }, // 13
{ L_, "ABCDEABCDEABCDE" } // 15
#else
{ L_, "ABCDEABCDEABCDEABCDEABC" }, // 23
{ L_, "ABCDEABCDEABCDEABCDEABCD" }, // 24
{ L_, "ABCDEABCDEABCDEABCDEABCDE" }, // 25
{ L_, "ABCDEABCDEABCDEABCDEABCDEABCDE" } // 30
#endif
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\tWithout passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
CONTAINER mU(g(SPEC)); const CONTAINER& U = mU;
Obj mX(U.begin(), U.end()); const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
Obj mY(g(SPEC)); const Obj& Y = mY;
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, Y[j] == X[j]);
}
}
}
if (verbose) printf("\tWith passing in an allocator.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) { printf("\t\tCreating object "); P(SPEC); }
CONTAINER mU(g(SPEC)); const CONTAINER& U = mU;
Obj mY(g(SPEC)); const Obj& Y = mY;
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
Obj mX(U.begin(), U.end(), AllocType(&testAllocator));
const Obj& X = mX;
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
T_; T_; P_(AA - BB); P(A - B);
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, Y[j] == X[j]);
}
if (LENGTH <= DEFAULT_CAPACITY) {
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else if (INPUT_ITERATOR_TAG) {
// LOOP2_ASSERT(LINE, ti, BB + 1 + NUM_ALLOCS[LENGTH] == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
} else {
// LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 1 == A);
}
}
}
if (verbose) printf("\tWith passing an allocator and checking for "
"allocation exceptions.\n");
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *SPEC = DATA[ti].d_spec;
const size_t LENGTH = strlen(SPEC);
if (veryVerbose) {
printf("\t\tCreating object of "); P_(LENGTH);
printf("using "); P(SPEC);
}
CONTAINER mU(g(SPEC)); const CONTAINER& U = mU;
Obj mY(g(SPEC)); const Obj& Y = mY;
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) { printf("\t\tBefore: "); P_(BB); P(B);}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(U.begin(), U.end(), AllocType(&testAllocator));
const Obj& X = mX;
if (veryVerbose) {
T_; T_; P_(X); P(X.capacity());
}
LOOP2_ASSERT(LINE, ti, LENGTH == X.size());
LOOP2_ASSERT(LINE, ti, LENGTH <= X.capacity());
for (size_t j = 0; j < LENGTH; ++j) {
LOOP3_ASSERT(LINE, ti, j, Y[j] == X[j]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) { printf("\t\tAfter : "); P_(AA); P(A);}
if (LENGTH <= DEFAULT_CAPACITY) {
LOOP2_ASSERT(LINE, ti, BB + 0 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
else {
if (INPUT_ITERATOR_TAG) {
LOOP2_ASSERT(LINE, ti, BB + 1 <= AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
} else {
LOOP2_ASSERT(LINE, ti, BB + 1 == AA);
LOOP2_ASSERT(LINE, ti, B + 0 == A);
}
}
LOOP2_ASSERT(LINE, ti, 0 == testAllocator.numBlocksInUse());
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase12Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING FOR CONSTRUCTORS:
//
// Concerns:
// 1 Constructing a string with a NULL pointer, or integral NULL value
// including 'false' is undefined behavior and it asserts.
// 2 Constructing a string with an invalid iterator range asserts on
// undefined behavior.
//
// Plan:
// For (1), call the proper constructor with a NULL value and verify that
// it asserts. Then call the same constructor with a valid C-string
// pointer and verify that it doesn't assert.
// For (2), construct a string with the constructor taking an invalid
// iterator range ('first > last') and verify that it asserts.
//
// Testing:
// string<C,CT,A>(const C *s, n, a = A());
// string<C,CT,A>(const C *s, a = A());
// template<class InputIter>
// string(InputIter first, InputIter last, a = A());
// --------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
ASSERT_SAFE_FAIL_RAW(Obj(0));
ASSERT_SAFE_PASS_RAW(Obj(0, size_t(0)));
ASSERT_SAFE_FAIL_RAW(Obj(0, size_t(10)));
Obj mY(g("ABCDE"));
ASSERT_SAFE_FAIL_RAW(Obj(mY.end(), mY.begin()));
Obj mX(g("ABCDE"));
ASSERT_SAFE_PASS_RAW(Obj(mX.c_str()));
ASSERT_SAFE_PASS_RAW(Obj(mX.c_str(), 0));
ASSERT_SAFE_PASS_RAW(Obj(mX.c_str(), mX.length()));
ASSERT_SAFE_PASS_RAW(Obj(mY.begin(), mY.end()));
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase11()
{
// --------------------------------------------------------------------
// TEST AllocType-RELATED CONCERNS
//
// Concerns:
// 1) That creating an empty string does not allocate
// 2) That the allocator is passed through to elements
// 3) That the string class has the 'bslma::UsesBslmaAllocator'
//
// Plan:
// We verify that the 'string' class has the traits, and
// that allocator is not used for creating empty strings.
//
// Testing:
// TRAITS
//
// TBD When a new string object Y is created from an old string object
// X, then the standard states that Y should get its allocator by
// copying X's allocator (23.1, Point 8). The STLport string
// implementation does not follow this rule for bslma::Allocator
// based allocators. To verify this behavior for non
// bslma::Allocator, should test, copy constructor using one
// and verify standard is followed.
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
(void) NUM_VALUES;
(void) VALUES;
if (verbose)
printf("\nTesting 'bslma::UsesBslmaAllocator'.\n");
ASSERT(( bslma::UsesBslmaAllocator<Obj>::value));
if (verbose)
printf("\nTesting that empty string does not allocate.\n");
{
Obj mX(Z);
ASSERT(0 == testAllocator.numBytesInUse());
}
ASSERT(0 == testAllocator.numBytesInUse());
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase9()
{
// --------------------------------------------------------------------
// TESTING ASSIGNMENT OPERATOR:
// We have the following concerns:
// 1) The value represented by any instance can be assigned to any
// other instance regardless of how either value is represented
// internally.
// 2) The 'rhs' value must not be affected by the operation.
// 3) 'rhs' going out of scope has no effect on the value of 'lhs'
// after the assignment.
// 4) Aliasing (x = x): The assignment operator must always work --
// even when the lhs and rhs are identically the same object.
// 5) The assignment operator must be neutral with respect to memory
// allocation exceptions.
// 6) The copy constructor's internal functionality varies
// according to which bitwise copy/move trait is applied.
//
// Plan:
// Specify a set S of unique object values with substantial and
// varied differences, ordered by increasing length. For each value
// in S, construct an object x along with a sequence of similarly
// constructed duplicates x1, x2, ..., xN. Attempt to affect every
// aspect of white-box state by altering each xi in a unique way.
// Let the union of all such objects be the set T.
//
// To address concerns 1, 2, and 5, construct tests u = v for all
// (u, v) in T X T. Using canonical controls UU and VV, assert
// before the assignment that UU == u, VV == v, and v == u if and only if
// VV == UU. After the assignment, assert that VV == u, VV == v,
// and, for grins, that v == u. Let v go out of scope and confirm
// that VV == u. All of these tests are performed within the 'bslma'
// exception testing apparatus. Since the execution time is lengthy
// with exceptions, every permutation is not performed when
// exceptions are tested. Every permutation is also tested
// separately without exceptions.
//
// As a separate exercise, we address 4 and 5 by constructing tests
// y = y for all y in T. Using a canonical control X, we will verify
// that X == y before and after the assignment, again within
// the bslma exception testing apparatus.
//
// To address concern 6, all these tests are performed on user
// defined types:
// With allocator, copyable
// With allocator, moveable
// With allocator, not moveable
//
// Testing:
// string<C,CT,A>& operator=(const string<C,CT,A>& rhs);
// string<C,CT,A>& operator=(const C *s);
// string<C,CT,A>& operator=(c);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
(void) NUM_VALUES;
// --------------------------------------------------------------------
if (verbose) printf("\nAssign cross product of values "
"with varied representations.\n"
"Without Exceptions\n");
{
static const char *SPECS[] = { // length
"", // 0
"A", // 1
"BC", // 2
"CDE", // 3
"DEAB", // 4
"DEABC", // 5
"CBAEDCBA", // 8
"EDCBAEDCB", // 9
"EDCBAEDCBAE", // 11
"EDCBAEDCBAED", // 12
"EDCBAEDCBAEDC", // 13
"EDCBAEDCBAEDCBAEDCBAEDC", // 23
"EDCBAEDCBAEDCBAEDCBAEDCB", // 24
"EDCBAEDCBAEDCBAEDCBAEDCBA", // 25
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBA", // 30
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAE", // 31
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAED", // 32
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAEDC", // 33
0 // null string required as last element
};
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15, 23, 24, 25, 30, 63, 64, 65
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
{
int uOldLen = -1;
for (int ui = 0; SPECS[ui]; ++ui) {
const char *const U_SPEC = SPECS[ui];
const size_t uLen = strlen(U_SPEC);
if (veryVerbose) {
printf("\tFor lhs objects of length " ZU ":\t", uLen);
P(U_SPEC);
}
LOOP_ASSERT(U_SPEC, uOldLen < (int)uLen);
uOldLen = static_cast<int>(uLen);
const Obj UU = g(U_SPEC); // control
LOOP_ASSERT(ui, uLen == UU.size()); // same lengths
for (int vi = 0; SPECS[vi]; ++vi) {
const char *const V_SPEC = SPECS[vi];
const size_t vLen = strlen(V_SPEC);
if (veryVerbose) {
printf("\t\tFor rhs objects of length " ZU ":\t",
vLen);
P(V_SPEC);
}
const Obj VV = g(V_SPEC); // control
const bool EQUAL = ui == vi; // flag indicating same values
for (int uj = 0; uj < NUM_EXTEND; ++uj) {
const int U_N = EXTEND[uj];
for (int vj = 0; vj < NUM_EXTEND; ++vj) {
const int V_N = EXTEND[vj];
Obj mU(Z); const Obj& U = mU;
stretchRemoveAll(&mU, U_N, VALUES[0]);
gg(&mU, U_SPEC);
{
Obj mV(Z); const Obj& V = mV;
stretchRemoveAll(&mV, V_N, VALUES[0]);
gg(&mV, V_SPEC);
// v--------
static int firstFew = 2 * NUM_EXTEND * NUM_EXTEND;
if (veryVeryVerbose || (veryVerbose && firstFew > 0)) {
printf("\t| "); P_(U_N); P_(V_N); P_(U); P(V);
--firstFew;
}
if (!veryVeryVerbose && veryVerbose && 0 == firstFew) {
printf("\t| ... (ommitted from now on\n");
--firstFew;
}
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, UU == U);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == V);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, EQUAL == (V == U));
const int NUM_CTOR = numCopyCtorCalls;
const int NUM_DTOR = numDestructorCalls;
const size_t OLD_LENGTH = U.size();
mU = V; // test assignment here
ASSERT((numCopyCtorCalls - NUM_CTOR) <= (int)V.size());
ASSERT((numDestructorCalls - NUM_DTOR) <=
(int)(V.size() + OLD_LENGTH));
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == U);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == V);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, V == U);
// ---------v
}
// 'mV' (and therefore 'V') now out of scope
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == U);
}
}
}
}
}
}
if (verbose) printf("\nAssign cross product of values "
"with varied representations.\n"
"With Exceptions\n");
{
static const char *SPECS[] = {
// spec length
// ---- ------
"", // 0
"A", // 1
"AB", // 2
"ABC", // 3
"ABCD", // 4
"ABCDEABC", // 8
"ABCDEABCD", // 9
#if 1 // #ifndef BSLS_PLATFORM_CPU_64_BIT
"ABCDEABCDEA", // 11
"ABCDEABCDEAB", // 12
"ABCDEABCDEABC", // 13
"ABCDEABCDEABCDE", // 15
#else
"ABCDEABCDEABCDEABCDEABC", // 23
"ABCDEABCDEABCDEABCDEABCD", // 24
"ABCDEABCDEABCDEABCDEABCDE", // 25
"ABCDEABCDEABCDEABCDEABCDEABCDE", // 30
#endif
0
}; // Null string required as last element.
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 9, 11, 12, 13
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
int iterationModulus = 1;
int iteration = 0;
{
int uOldLen = -1;
for (int ui = 0; SPECS[ui]; ++ui) {
const char *const U_SPEC = SPECS[ui];
const size_t uLen = strlen(U_SPEC);
if (veryVerbose) {
printf("\tFor lhs objects of length " ZU ":\t", uLen);
P(U_SPEC);
}
LOOP_ASSERT(U_SPEC, uOldLen < (int)uLen);
uOldLen = static_cast<int>(uLen);
const Obj UU = g(U_SPEC); // control
LOOP_ASSERT(ui, uLen == UU.size()); // same lengths
// int vOldLen = -1;
for (int vi = 0; SPECS[vi]; ++vi) {
const char *const V_SPEC = SPECS[vi];
const size_t vLen = strlen(V_SPEC);
if (veryVerbose) {
printf("\t\tFor rhs objects of length " ZU ":\t",
vLen);
P(V_SPEC);
}
// control
const Obj VV = g(V_SPEC);
for (int uj = 0; uj < NUM_EXTEND; ++uj) {
const int U_N = EXTEND[uj];
for (int vj = 0; vj < NUM_EXTEND; ++vj) {
const int V_N = EXTEND[vj];
if (iteration % iterationModulus == 0) {
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(
testAllocator) {
//--------------^
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
Obj mU(Z); const Obj& U = mU;
stretchRemoveAll(&mU, U_N, VALUES[0]);
gg(&mU, U_SPEC);
{
Obj mV(Z); const Obj& V = mV;
stretchRemoveAll(&mV, V_N, VALUES[0]);
gg(&mV, V_SPEC);
static int firstFew = 2 * NUM_EXTEND * NUM_EXTEND;
if (veryVeryVerbose || (veryVerbose && firstFew > 0)) {
printf("\t| "); P_(U_N); P_(V_N); P_(U); P(V);
--firstFew;
}
if (!veryVeryVerbose && veryVerbose && 0 == firstFew) {
printf("\t| ... (ommitted from now on\n");
--firstFew;
}
testAllocator.setAllocationLimit(AL);
{
mU = V; // test assignment here
}
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == U);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == V);
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, V == U);
}
// 'mV' (and therefore 'V') now out of scope
LOOP4_ASSERT(U_SPEC, U_N, V_SPEC, V_N, VV == U);
//--------------v
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
++iteration;
}
}
}
}
}
}
if (verbose) printf("\nTesting self assignment (Aliasing).\n");
{
static const char *SPECS[] = {
"", "A", "BC", "CDE", "DEAB", "EABCD",
"ABCDEAB", "ABCDEABC", "ABCDEABCD",
"ABCDEABCDEABCDE", "ABCDEABCDEABCDEA", "ABCDEABCDEABCDEAB",
0 // null string required as last element
};
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
int oldLen = -1;
for (int ti = 0; SPECS[ti]; ++ti) {
const char *const SPEC = SPECS[ti];
const int curLen = (int) strlen(SPEC);
if (veryVerbose) {
printf("\tFor an object of length %d:\t", curLen);
P(SPEC);
}
LOOP_ASSERT(SPEC, oldLen < curLen); // strictly increasing
oldLen = curLen;
// control
const Obj X = g(SPEC);
LOOP_ASSERT(ti, curLen == (int)X.size()); // same lengths
for (int tj = 0; tj < NUM_EXTEND; ++tj) {
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Int64 AL = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(-1);
const int N = EXTEND[tj];
Obj mY(Z); const Obj& Y = mY;
stretchRemoveAll(&mY, N, VALUES[0]);
gg(&mY, SPEC);
if (veryVerbose) { T_; T_; P_(N); P(Y); }
LOOP2_ASSERT(SPEC, N, Y == Y);
LOOP2_ASSERT(SPEC, N, X == Y);
testAllocator.setAllocationLimit(AL);
{
ExceptionGuard<Obj> guard(&mY, Y, L_);
mY = Y; // test assignment here
}
LOOP2_ASSERT(SPEC, N, Y == Y);
LOOP2_ASSERT(SPEC, N, X == Y);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
}
}
#ifndef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nSkip testing assignment exception-safety.\n");
#else
if (verbose) printf("\nTesting assignment exception-safety.\n");
{
size_t defaultCapacity = Obj().capacity();
Obj src(defaultCapacity + 1, '1', &testAllocator);
Obj dst(defaultCapacity, '2', &testAllocator);
Obj dstCopy(dst, &testAllocator);
// make the allocator throw on the next allocation
bsls::Types::Int64 oldLimit = testAllocator.allocationLimit();
testAllocator.setAllocationLimit(0);
bool exceptionCaught = false;
try
{
// the assignment will require to allocate more memory
dst = src;
}
catch (bslma::TestAllocatorException &)
{
exceptionCaught = true;
}
catch (...)
{
exceptionCaught = true;
ASSERT(0 && "Wrong exception caught");
}
// restore the allocator state
testAllocator.setAllocationLimit(oldLimit);
ASSERT(exceptionCaught);
ASSERT(dst == dstCopy);
}
#endif
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase9Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING ASSIGNMENT OPERATOR:
// Concerns:
// 1 Assigning a NULL C-string asserts to a string object asserts.
//
// Plan:
// Construct a string object, then assign a NULL C-string to it and
// verify that it asserts. After that assign a valid C-string and verify
// that it succeeds.
//
// Testing:
// string& operator=(const CHAR_TYPE *);
// --------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
Obj X;
if (verbose) printf("\tassigning a NULL C-string\n");
{
const TYPE *s = 0;
(void) s; // to disable "unused variable" warning
ASSERT_SAFE_FAIL(X = s);
}
if (verbose) printf("\tassigning a valid C-string\n");
{
Obj Y(g("ABC"));
ASSERT_SAFE_PASS(X = Y.c_str());
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase8()
{
// --------------------------------------------------------------------
// TESTING GENERATOR FUNCTION, g:
// Since 'g' is implemented almost entirely using 'gg', we need to verify
// only that the arguments are properly forwarded, that 'g' does not
// affect the test allocator, and that 'g' returns an object by value.
//
// Plan:
// For each SPEC in a short list of specifications, compare the object
// returned (by value) from the generator function, 'g(SPEC)' with the
// value of a newly constructed OBJECT configured using 'gg(&OBJECT,
// SPEC)'. Compare the results of calling the allocator's
// 'numBlocksTotal' and 'numBytesInUse' methods before and after calling
// 'g' in order to demonstrate that 'g' has no effect on the test
// allocator. Finally, use 'sizeof' to confirm that the (temporary)
// returned by 'g' differs in size from that returned by 'gg'.
//
// Testing:
// string g(const char *spec);
// string g(size_t len, TYPE seed);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
static const char *SPECS[] = {
"", "~", "A", "B", "C", "D", "E", "A~B~C~D~E", "ABCDE", "ABC~DE",
0 // null string required as last element
};
if (verbose)
printf("\nCompare values produced by 'g' and 'gg' "
"for various inputs.\n");
for (int ti = 0; SPECS[ti]; ++ti) {
const char *SPEC = SPECS[ti];
if (veryVerbose) { P_(ti); P(SPEC); }
Obj mX(Z);
gg(&mX, SPEC); const Obj& X = mX;
if (veryVerbose) {
printf("\t g = "); dbg_print(g(SPEC)); printf("\n");
printf("\tgg = "); dbg_print(X); printf("\n");
}
const Int64 TOTAL_BLOCKS_BEFORE = testAllocator.numBlocksTotal();
const Int64 IN_USE_BYTES_BEFORE = testAllocator.numBytesInUse();
LOOP_ASSERT(ti, X == g(SPEC));
const Int64 TOTAL_BLOCKS_AFTER = testAllocator.numBlocksTotal();
const Int64 IN_USE_BYTES_AFTER = testAllocator.numBytesInUse();
LOOP_ASSERT(ti, TOTAL_BLOCKS_BEFORE == TOTAL_BLOCKS_AFTER);
LOOP_ASSERT(ti, IN_USE_BYTES_BEFORE == IN_USE_BYTES_AFTER);
}
if (verbose) printf("\nConfirm return-by-value.\n");
{
const char *SPEC = "ABCDE";
// compile-time fact
ASSERT(sizeof(Obj) == sizeof g(SPEC));
Obj x(Z);
Obj& r1 = gg(&x, SPEC);
Obj& r2 = gg(&x, SPEC);
const Obj& r3 = g(SPEC);
const Obj& r4 = g(SPEC);
ASSERT(&r2 == &r1);
ASSERT(&x == &r1);
ASSERT(&r4 != &r3);
ASSERT(&x != &r3);
}
if (verbose) printf("\nVerify generator g(size_t len, TYPE seed)\n");
{
if (veryVerbose) printf(" Returned string length is correct.\n");
for (size_t i = 0; i < 200; ++i) {
ASSERT(g(i, TYPE()).size() == i);
}
if (veryVerbose) printf(" Seed produces unique strings.\n");
// scan the char range, wchar_t can be too wide (32bit)
Obj values[CHAR_MAX];
Obj *values_end = values + CHAR_MAX;
for (char s = 0; s != CHAR_MAX; ++s) {
values[s] = g(10, TYPE(s));
}
// all values are unique
std::sort(values, values_end);
ASSERT(std::adjacent_find(values, values_end) == values_end);
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase7()
{
// --------------------------------------------------------------------
// TESTING COPY CONSTRUCTOR:
// We have the following concerns:
// 1) The new object's value is the same as that of the original
// object (relying on the equality operator) and created with
// the correct capacity.
// 2) All internal representations of a given value can be used to
// create a new object of equivalent value.
// 3) The value of the original object is left unaffected.
// 4) Subsequent changes in or destruction of the source object have
// no effect on the copy-constructed object.
// 5) Subsequent changes ('push_back's) on the created object have no
// effect on the original and change the capacity of the new
// object correctly.
// 6) The object has its internal memory management system hooked up
// properly so that *all* internally allocated memory draws
// from a user-supplied allocator whenever one is specified.
// 7) The function is exception neutral w.r.t. memory allocation.
//
// Plan:
// Specify a set S of object values with substantial and varied
// differences, ordered by increasing length, to be used in the
// following tests.
//
// For concerns 1 - 4, for each value in S, initialize objects w and
// x, copy construct y from x and use 'operator==' to verify that
// both x and y subsequently have the same value as w. Let x go out
// of scope and again verify that w == y.
//
// For concern 5, for each value in S initialize objects w and x,
// and copy construct y from x. Change the state of y, by using the
// *primary* *manipulator* 'push_back'. Using the 'operator!=' verify
// that y differs from x and w, and verify that the capacity of y
// changes correctly.
//
// To address concern 6, we will perform tests performed for concern 1:
// - While passing a testAllocator as a parameter to the new object
// and ascertaining that the new object gets its memory from the
// provided testAllocator. Also perform test for concerns 2 and 5.
// - Where the object is constructed with an object allocator, and
// neither of global and default allocator is used to supply memory.
//
// To address concern 7, perform tests for concern 1 performed
// in the presence of exceptions during memory allocations using a
// 'bslma::TestAllocator' and varying its *allocation* *limit*.
//
// Testing:
// string(const string<C,CT,A>& original, a = A());
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
{
static const char *SPECS[] = {
"", // 0
"A", // 1
"BC", // 2
"CDE", // 3
"DEAB", // 4
"CBAEDCBA", // 8
"EDCBAEDCB", // 9
"EDCBAEDCBAE", // 11
"EDCBAEDCBAED", // 12
"EDCBAEDCBAEDC", // 13
"EDCBAEDCBAEDCBAEDCBAEDC", // 23
"EDCBAEDCBAEDCBAEDCBAEDCB", // 24
"EDCBAEDCBAEDCBAEDCBAEDCBA", // 25
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBA", // 30
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAE", // 31
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAED", // 32
"EDCBAEDCBAEDCBAEDCBAEDCBAEDCBAEDC", // 33
0 // null string required as last element
};
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 7, 8, 9
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
int oldLen = -1;
for (int ti = 0; SPECS[ti]; ++ti) {
const char *const SPEC = SPECS[ti];
const size_t LENGTH = strlen(SPEC);
if (verbose) {
printf("\tFor an object of length " ZU ":\t", LENGTH);
P(SPEC);
}
LOOP_ASSERT(SPEC, oldLen < (int)LENGTH); // strictly increasing
oldLen = static_cast<int>(LENGTH);
// Create control object w.
Obj mW; gg(&mW, SPEC);
const Obj& W = mW;
LOOP_ASSERT(ti, LENGTH == W.size()); // same lengths
if (veryVerbose) { printf("\tControl Obj: "); P(W); }
// Stretch capacity of x object by different amounts.
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
const int N = EXTEND[ei];
if (veryVerbose) { printf("\t\tExtend By : "); P(N); }
Obj *pX = new Obj(Z);
Obj& mX = *pX;
stretchRemoveAll(&mX, N, VALUES[0]);
const Obj& X = mX; gg(&mX, SPEC);
if (veryVerbose) { printf("\t\tDynamic Obj: "); P(X); }
{ // Testing concern 1.
if (veryVerbose) { printf("\t\t\tRegular Case :"); }
const Obj Y0(X);
if (veryVerbose) {
printf("\tObj : "); P_(Y0); P(Y0.capacity());
}
LOOP2_ASSERT(SPEC, N, W == Y0);
LOOP2_ASSERT(SPEC, N, W == X);
LOOP2_ASSERT(SPEC, N, Y0.get_allocator() ==
bslma::Default::defaultAllocator());
LOOP2_ASSERT(SPEC, N, LENGTH <= Y0.capacity());
}
{ // Testing concern 5.
if (veryVerbose) printf("\t\t\tInsert into created obj, "
"without test allocator:\n");
Obj Y1(X);
if (veryVerbose) {
printf("\t\t\t\tBefore Insert: "); P(Y1);
}
for (int i = 1; i < N + 1; ++i) {
const size_t oldCap = Y1.capacity();
const size_t remSlots = Y1.capacity() - Y1.size();
size_t newCap = 0 != remSlots
? -1
: Imp::computeNewCapacity(LENGTH + i,
oldCap,
Y1.max_size());
stretch(&Y1, 1, VALUES[i % NUM_VALUES]);
if (veryVerbose) {
printf("\t\t\t\tAfter Insert : ");
P_(Y1.capacity()); P_(i); P(Y1);
}
LOOP3_ASSERT(SPEC, N, i, Y1.size() == LENGTH + i);
LOOP3_ASSERT(SPEC, N, i, W != Y1);
LOOP3_ASSERT(SPEC, N, i, X != Y1);
if (oldCap == 0) {
LOOP3_ASSERT(SPEC, N, i,
Y1.capacity() ==
INITIAL_CAPACITY_FOR_NON_EMPTY_OBJECT);
}
else if (remSlots == 0) {
LOOP5_ASSERT(SPEC, N, i, Y1.capacity(), newCap,
Y1.capacity() == newCap);
}
else {
LOOP3_ASSERT(SPEC, N, i,
Y1.capacity() == oldCap);
}
}
}
{ // Testing concern 5 with test allocator.
if (veryVerbose)
printf("\t\t\tInsert into created obj, "
"with test allocator:\n");
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore Creation: "); P_(BB); P(B);
}
Obj Y11(X, AllocType(&testAllocator));
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter Creation: "); P_(AA); P(A);
printf("\t\t\t\tBefore Append: "); P(Y11);
}
size_t initCap = DEFAULT_CAPACITY;
if (LENGTH <= initCap) {
LOOP2_ASSERT(SPEC, N, BB + 0 == AA);
LOOP2_ASSERT(SPEC, N, B + 0 == A);
}
else {
LOOP2_ASSERT(SPEC, N, BB + 1 == AA);
LOOP2_ASSERT(SPEC, N, B + 1 == A);
}
for (int i = 1; i < N+1; ++i) {
const size_t oldCap = Y11.capacity();
const size_t initCap = DEFAULT_CAPACITY;
const Int64 CC = testAllocator.numBlocksTotal();
const Int64 C = testAllocator.numBlocksInUse();
stretch(&Y11, 1, VALUES[i % NUM_VALUES]);
const Int64 DD = testAllocator.numBlocksTotal();
const Int64 D = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore Append: "); P_(DD); P(D);
printf("\t\t\t\tAfter Append : "); P_(CC); P(C);
T_ T_ T_ T_ T_ P_(i); P_(Y11.capacity()); P(Y11);
}
// Blocks allocated should increase only when
// trying to add more than capacity. When adding
// the first element numBlocksInUse will increase
// by 1. In all other conditions numBlocksInUse
// should remain the same.
if (oldCap < Y11.capacity() && oldCap == initCap) {
LOOP3_ASSERT(SPEC, N, i, CC + 1 == DD);
LOOP3_ASSERT(SPEC, N, i, C + 1 == D);
}
else if (oldCap < Y11.capacity()) {
LOOP3_ASSERT(SPEC, N, i, CC + 1 == DD);
LOOP3_ASSERT(SPEC, N, i, C + 0 == D);
} else {
LOOP3_ASSERT(SPEC, N, i, CC + 0 == DD);
LOOP3_ASSERT(SPEC, N, i, C + 0 == D);
}
LOOP3_ASSERT(SPEC, N, i, Y11.size() == LENGTH + i);
LOOP3_ASSERT(SPEC, N, i, W != Y11);
LOOP3_ASSERT(SPEC, N, i, X != Y11);
LOOP3_ASSERT(SPEC, N, i,
Y11.get_allocator() == X.get_allocator());
}
}
{ // Exception checking.
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tBefore Creation: "); P_(BB); P(B);
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
const Obj Y2(X, AllocType(&testAllocator));
if (veryVerbose) {
printf("\t\t\tException Case :\n");
printf("\t\t\t\tObj : "); P(Y2);
}
LOOP2_ASSERT(SPEC, N, W == Y2);
LOOP2_ASSERT(SPEC, N, W == X);
LOOP2_ASSERT(SPEC, N,
Y2.get_allocator() == X.get_allocator());
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t\tAfter Creation: "); P_(AA); P(A);
}
const size_t initCap = DEFAULT_CAPACITY;
if (initCap < LENGTH) {
LOOP2_ASSERT(SPEC, N, BB + 1 == AA);
} else {
LOOP2_ASSERT(SPEC, N, BB + 0 == AA);
}
LOOP2_ASSERT(SPEC, N, B + 0 == A);
}
{ // with 'original' destroyed
Obj Y5(X);
if (veryVerbose) {
printf("\t\t\tWith Original deleted: \n");
printf("\t\t\t\tBefore Delete : "); P(Y5);
}
delete pX;
LOOP2_ASSERT(SPEC, N, W == Y5);
for (int i = 1; i < N+1; ++i) {
stretch(&Y5, 1, VALUES[i % NUM_VALUES]);
if (veryVerbose) {
printf("\t\t\t\tAfter Append to new obj : ");
P_(i);P(Y5);
}
LOOP3_ASSERT(SPEC, N, i, W != Y5);
}
}
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase6()
{
// ---------------------------------------------------------------------
// TESTING EQUALITY OPERATORS:
// Concerns:
// 1 Objects constructed with the same values are returned as equal.
// 2 Objects constructed such that they have same (logical) value but
// different internal representation (due to the lack or presence
// of an allocator, and/or different capacities) are always returned
// as equal.
// 3 Unequal objects are always returned as unequal.
// 4 Equality comparisons with 'const CHAR_TYPE *' yield the same results
// as equality comparisons with 'string' objects.
// 5 Correctly selects the 'bitwiseEqualityComparable' traits.
//
// Plan:
// For concerns 1 and 3, Specify a set A of unique allocators including
// no allocator. Specify a set S of unique object values having various
// minor or subtle differences, ordered by non-decreasing length.
// Verify the correctness of 'operator==' and 'operator!=' (returning
// either true or false) using all elements (u, ua, v, va) of the
// cross product S X A X S X A.
//
// For concern 2 create two objects using all elements in S one at a
// time. For the second object change its internal representation by
// extending it by different amounts in the set E, followed by erasing
// its contents using 'clear'. Then recreate the original value and
// verify that the second object still return equal to the first.
//
// For concern 4, test equality operators taking 'const CHAR_TYPE *'
// parameters right after equality comparisons of 'string' objects have
// been verified to perform correctly.
//
// For concern 5, we instantiate this test driver on a test type having
// allocators or not, and possessing the bitwise-equality-comparable
// trait or not.
//
// Testing:
// operator==(const string<C,CT,A>&, const string<C,CT,A>&);
// operator==(const C *, const string<C,CT,A>&);
// operator==(const string<C,CT,A>&, const C *);
// operator!=(const string<C,CT,A>&, const string<C,CT,A>&);
// operator!=(const C *, const string<C,CT,A>&);
// operator!=(const string<C,CT,A>&, const C *);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator1(veryVeryVerbose);
bslma::TestAllocator testAllocator2(veryVeryVerbose);
Allocator *AllocType[] = {
new Allocator(&testAllocator1),
new Allocator(&testAllocator2)
};
const int NUM_AllocType = sizeof AllocType / sizeof *AllocType;
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
static const char *SPECS[] = {
"",
"A", "B",
"AA", "AB", "BB", "BA",
"AAA", "BAA", "ABA", "AAB",
"AAAA", "BAAA", "ABAA", "AABA", "AAAB",
"AAAAA", "BAAAA", "ABAAA", "AABAA", "AAABA", "AAAAB",
"AAAAAA", "BAAAAA", "AABAAA", "AAABAA", "AAAAAB",
"AAAAAAA", "BAAAAAA", "AAAAABA",
"AAAAAAAA", "ABAAAAAA", "AAAAABAA",
"AAAAAAAAA", "AABAAAAAA", "AAAAABAAA",
"AAAAAAAAAA", "AAABAAAAAA", "AAAAABAAAA",
"AAAAAAAAAAA", "AAAABAAAAAA", "AAAAABAAAAA",
"AAAAAAAAAAAA", "AAAABAAAAAAA", "AAAAABAAAAAA",
"AAAAAAAAAAAAA", "AAAABAAAAAAAA", "AAAAABAAAAAAA",
"AAAAAAAAAAAAAA", "AAAABAAAAAAAAA", "AAAAABAAAAAAAA",
"AAAAAAAAAAAAAAA", "AAAABAAAAAAAAAA", "AAAAABAAAAAAAAA",
0 // null string required as last element
};
if (verbose) printf("\nCompare each pair of similar and different"
" values (u, ua, v, va) in S X A X S X A"
" without perturbation.\n");
{
int oldLen = -1;
// Create first object
for (int si = 0; SPECS[si]; ++si) {
for (int ai = 0; ai < NUM_AllocType; ++ai) {
const char *const U_SPEC = SPECS[si];
const int LENGTH = static_cast<int>(strlen(U_SPEC));
Obj mU(*AllocType[ai]); const Obj& U = gg(&mU, U_SPEC);
LOOP2_ASSERT(si, ai, LENGTH == static_cast<int>(U.size()));
// same lengths
if (LENGTH != oldLen) {
if (verbose)
printf( "\tUsing lhs objects of length %d.\n", LENGTH);
LOOP_ASSERT(U_SPEC, oldLen <= LENGTH);//non-decreasing
oldLen = LENGTH;
}
if (veryVerbose) { T_; T_;
P_(si); P_(U_SPEC); P(U); }
// Create second object
for (int sj = 0; SPECS[sj]; ++sj) {
for (int aj = 0; aj < NUM_AllocType; ++aj) {
const char *const V_SPEC = SPECS[sj];
Obj mV(*AllocType[aj]);
const Obj& V = gg(&mV, V_SPEC);
if (veryVerbose) {
T_; T_; P_(sj); P_(V_SPEC); P(V);
}
// First test comparisons with 'string'
const bool isSame = si == sj;
LOOP2_ASSERT(si, sj, isSame == (U == V));
LOOP2_ASSERT(si, sj, !isSame == (U != V));
// And then with 'const CHAR_TYPE *'
LOOP2_ASSERT(si, sj, isSame == (U == V.c_str()));
LOOP2_ASSERT(si, sj, !isSame == (U != V.c_str()));
LOOP2_ASSERT(si, sj, isSame == (U.c_str() == V));
LOOP2_ASSERT(si, sj, !isSame == (U.c_str() != V));
}
}
}
}
}
if (verbose) printf("\nCompare each pair of similar values (u, ua, v, va)"
" in S X A X S X A after perturbing.\n");
{
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15, 23, 24, 25, 30
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
int oldLen = -1;
// Create first object
for (int si = 0; SPECS[si]; ++si) {
for (int ai = 0; ai < NUM_AllocType; ++ai) {
const char *const U_SPEC = SPECS[si];
const size_t LENGTH = strlen(U_SPEC);
Obj mU(*AllocType[ai]); const Obj& U = mU;
gg(&mU, U_SPEC);
LOOP_ASSERT(si, LENGTH == U.size()); // same lengths
if ((int)LENGTH != oldLen) {
if (verbose)
printf( "\tUsing lhs objects of length " ZU ".\n",
LENGTH);
LOOP_ASSERT(U_SPEC, oldLen <= (int)LENGTH);
oldLen = static_cast<int>(LENGTH);
}
if (veryVerbose) { P_(si); P_(U_SPEC); P(U); }
// Create second object
for (int sj = 0; SPECS[sj]; ++sj) {
for (int aj = 0; aj < NUM_AllocType; ++aj) {
//Perform perturbation
for (int e = 0; e < NUM_EXTEND; ++e) {
const char *const V_SPEC = SPECS[sj];
Obj mV(*AllocType[aj]); const Obj& V = mV;
gg(&mV, V_SPEC);
stretchRemoveAll(&mV, EXTEND[e],
VALUES[e % NUM_VALUES]);
gg(&mV, V_SPEC);
if (veryVerbose) {
T_; T_; P_(sj); P_(V_SPEC); P(V);
}
// First test comparisons with 'string'
const bool isSame = si == sj;
LOOP2_ASSERT(si, sj, isSame == (U == V));
LOOP2_ASSERT(si, sj, !isSame == (U != V));
// And then with 'const CHAR_TYPE *'
LOOP2_ASSERT(si, sj, isSame == (U == V.c_str()));
LOOP2_ASSERT(si, sj, !isSame == (U != V.c_str()));
LOOP2_ASSERT(si, sj, isSame == (U.c_str() == V));
LOOP2_ASSERT(si, sj, !isSame == (U.c_str() != V));
}
}
}
}
}
}
delete AllocType[0];
delete AllocType[1];
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase6Negative()
{
// --------------------------------------------------------------------
// NEGATIVE TESTING EQUALITY OPERATORS
//
// Concerns:
// Equality comparison operators taking C-string pointer parameters
// assert on undefined behavior when the pointer is NULL.
//
// Plan:
// For each equality comparison operator, create a non-empty string and
// use it to test equality comparison operators by passing NULL to
// C-string pointer parameters.
//
// Testing:
// operator==(const C *s, const string<C,CT,A>& str);
// operator==(const string<C,CT,A>& str, const C *s);
// operator!=(const C *s, const string<C,CT,A>& str);
// operator!=(const string<C,CT,A>& str, const C *s);
// -----------------------------------------------------------------------
bsls::AssertFailureHandlerGuard guard(&bsls::AssertTest::failTestDriver);
Obj mX(g("ABCDE"));
const Obj& X = mX;
TYPE *nullStr = NULL;
// disable "unused variable" warning in non-safe mode:
#if !defined BSLS_ASSERT_SAFE_IS_ACTIVE
(void) nullStr;
#endif
if (veryVerbose) printf("\toperator==(s, str)\n");
{
ASSERT_SAFE_FAIL(nullStr == X);
ASSERT_SAFE_PASS(X.c_str() == X);
}
if (veryVerbose) printf("\toperator==(str, s)\n");
{
ASSERT_SAFE_FAIL(X == nullStr);
ASSERT_SAFE_PASS(X == X.c_str());
}
if (veryVerbose) printf("\toperator!=(s, str)\n");
{
ASSERT_SAFE_FAIL(nullStr != X);
ASSERT_SAFE_PASS(X.c_str() != X);
}
if (veryVerbose) printf("\toperator==(str, s)\n");
{
ASSERT_SAFE_FAIL(X != nullStr);
ASSERT_SAFE_PASS(X != X.c_str());
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase4()
{
// --------------------------------------------------------------------
// TESTING BASIC ACCESSORS:
// Concerns:
// 1) The returned value for operator[] and function at() is correct
// as long as pos < size(), and 'operator[] const' returns C() for
// 'pos == size()'.
// 2) The at() function throws out_of_range exception if
// pos >= size().
// 3) The elements stored at indices 0 up to size() - 1 are stored
// contiguously.
// 4) Changing the internal representation to get the same (logical)
// final value, should not change the result of the element
// accessor functions.
// 5) The internal memory management is correctly hooked up so that
// changes made to the state of the object via these accessors
// do change the state of the object.
//
// Plan:
// For 1 and 4 do the following:
// Specify a set S of representative object values ordered by
// increasing length. For each value w in S, initialize a newly
// constructed object x with w using 'gg' and verify that each basic
// accessor returns the expected result. Reinitialize and repeat
// the same test on an existing object y after perturbing y so as to
// achieve an internal state representation of w that is potentially
// different from that of x.
// For 3, using the object values of the previous experiment, verify that
// the array of 'size()' beginning at '&X[0]' is identical in contents to
// the object value.
//
// For 2, check that function at() throws a out_of_range exception
// when pos >= size().
//
// For 5, For each value w in S, create a object x with w using
// 'gg'. Create another empty object y and make it 'resize' capacity
// equal to the size of x. Now using the element accessor functions
// recreate the value of x in y. Verify that x == y.
// Note - Using untested resize(int).
//
// Testing:
// reference operator[](size_type pos);
// const_reference operator[](size_type pos) const;
// reference at(size_type pos);
// const_reference at(size_type pos) const;
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
bslma::TestAllocator testAllocator1(veryVeryVerbose);
bslma::TestAllocator testAllocator2(veryVeryVerbose);
Allocator *AllocType[] = {
new Allocator(&testAllocator),
new Allocator(&testAllocator1),
new Allocator(&testAllocator2)
};
const int NUM_AllocType = sizeof AllocType / sizeof *AllocType;
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
const size_t MAX_LENGTH = 32;
static const struct {
int d_lineNum; // source line number
const char *d_spec_p; // specification string
int d_length; // expected length
char d_elements[MAX_LENGTH + 1]; // expected element values
} DATA[] = {
//line spec length elements
//---- -------------- ------ ------------------------
{ L_, "", 0, { } },
{ L_, "A", 1, { VA } },
{ L_, "B", 1, { VB } },
{ L_, "AB", 2, { VA, VB } },
{ L_, "BC", 2, { VB, VC } },
{ L_, "BCA", 3, { VB, VC, VA } },
{ L_, "CAB", 3, { VC, VA, VB } },
{ L_, "CDAB", 4, { VC, VD, VA, VB } },
{ L_, "DABC", 4, { VD, VA, VB, VC } },
{ L_, "ABCDE", 5, { VA, VB, VC, VD, VE } },
{ L_, "EDCBA", 5, { VE, VD, VC, VB, VA } },
{ L_, "ABCDEA", 6, { VA, VB, VC, VD, VE,
VA } },
{ L_, "ABCDEAB", 7, { VA, VB, VC, VD, VE,
VA, VB } },
{ L_, "BACDEABC", 8, { VB, VA, VC, VD, VE,
VA, VB, VC } },
{ L_, "CBADEABCD", 9, { VC, VB, VA, VD, VE,
VA, VB, VC, VD } },
{ L_, "CBADEABCDAB", 11, { VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB } },
{ L_, "CBADEABCDABC", 12, { VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC } },
{ L_, "CBADEABCDABCDE", 14, { VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC, VD, VE } },
{ L_, "CBADEABCDABCDEA", 15, { VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC, VD, VE, VA } },
{ L_, "CBADEABCDABCDEAB", 16, { VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC, VD, VE, VA,
VB } },
{ L_, "CBADEABCDABCDEABCBADEABCDABCDEA", 31,
{ VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC, VD, VE, VA,
VB, VC, VB, VA, VD,
VE, VA, VB, VC, VD,
VA, VB, VC, VD, VE,
VA } },
{ L_, "CBADEABCDABCDEABCBADEABCDABCDEAB", 32,
{ VC, VB, VA, VD, VE,
VA, VB, VC, VD, VA,
VB, VC, VD, VE, VA,
VB, VC, VB, VA, VD,
VE, VA, VB, VC, VD,
VA, VB, VC, VD, VE,
VA, VB } }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) printf("\nTesting operator[] and function at(),"
" where pos < size().\n");
{
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *const SPEC = DATA[ti].d_spec_p;
const size_t LENGTH = DATA[ti].d_length;
const char *const e = DATA[ti].d_elements;
Obj mExp;
const Obj& EXP = gg(&mExp, e); // expected spec
ASSERT(LENGTH <= MAX_LENGTH);
for (int ai = 0; ai < NUM_AllocType; ++ai) {
Obj mX(*AllocType[ai]);
const Obj& X = gg(&mX, SPEC); // canonical organization
LOOP2_ASSERT(ti, ai, LENGTH == X.size()); // same lengths
if (veryVerbose) {
printf( "\ton objects of length " ZU ":\n", LENGTH);
}
if ((int)LENGTH != oldLen) {
LOOP2_ASSERT(LINE, ai, oldLen <= (int)LENGTH);
// non-decreasing
oldLen = static_cast<int>(LENGTH);
}
if (veryVerbose) printf("\t\tSpec = \"%s\"\n", SPEC);
if (veryVerbose) {
T_; T_; T_; P(X);
}
size_t i;
for (i = 0; i < LENGTH; ++i) {
LOOP3_ASSERT(LINE, ai, i, EXP[i] == mX[i]);
LOOP3_ASSERT(LINE, ai, i, EXP[i] == X[i]);
LOOP3_ASSERT(LINE, ai, i, EXP[i] == mX.at(i));
LOOP3_ASSERT(LINE, ai, i, EXP[i] == X.at(i));
LOOP3_ASSERT(LINE, ai, i, &mX[0] + i == &mX[i]);
LOOP3_ASSERT(LINE, ai, i, &X[0] + i == &X[i]);
}
LOOP2_ASSERT(LINE, ai, &mX[0] == &X[0]);
LOOP2_ASSERT(LINE, ai, TYPE() == X[LENGTH]);
for (; i < MAX_LENGTH; ++i) {
LOOP3_ASSERT(LINE, ai, i, 0 == e[i]);
}
// Check for perturbation.
static const int EXTEND[] = {
0, 1, 2, 3, 4, 5, 7, 8, 9, 15
};
const int NUM_EXTEND = sizeof EXTEND / sizeof *EXTEND;
Obj mY(*AllocType[ai]);
const Obj& Y = gg(&mY, SPEC);
{ // Perform the perturbation
for (int ei = 0; ei < NUM_EXTEND; ++ei) {
stretchRemoveAll(&mY, EXTEND[ei],
VALUES[ei % NUM_VALUES]);
gg(&mY, SPEC);
if (veryVerbose) { T_; T_; T_; P(Y); }
size_t j;
for (j = 0; j < LENGTH; ++j) {
LOOP4_ASSERT(LINE, ai, j, ei, EXP[j] == mY[j]);
LOOP4_ASSERT(LINE, ai, j, ei, EXP[j] == Y[j]);
LOOP4_ASSERT(LINE, ai, j, ei, EXP[j] == mY.at(j));
LOOP4_ASSERT(LINE, ai, j, ei, EXP[j] == Y.at(j));
}
for (; j < MAX_LENGTH; ++j) {
LOOP4_ASSERT(LINE, ai, j, ei, 0 == e[j]);
}
}
}
}
}
}
if (verbose) printf("\nTesting non-const operator[] and "
"function at() modify state of object correctly.\n");
{
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *const SPEC = DATA[ti].d_spec_p;
const size_t LENGTH = DATA[ti].d_length;
const char *const e = DATA[ti].d_elements;
for (int ai = 0; ai < NUM_AllocType; ++ai) {
Obj mX(*AllocType[ai]);
const Obj& X = gg(&mX, SPEC);
LOOP2_ASSERT(ti, ai, LENGTH == X.size()); // same lengths
if (veryVerbose) {
printf("\tOn objects of length " ZU ":\n", LENGTH);
}
if ((int)LENGTH != oldLen) {
LOOP2_ASSERT(LINE, ai, oldLen <= (int)LENGTH);
// non-decreasing
oldLen = static_cast<int>(LENGTH);
}
if (veryVerbose) printf( "\t\tSpec = \"%s\"\n", SPEC);
if (veryVerbose) {
T_; T_; T_; P(X);
}
Obj mY(*AllocType[ai]); const Obj& Y = mY;
Obj mZ(*AllocType[ai]); const Obj& Z = mZ;
mY.resize(LENGTH);
mZ.resize(LENGTH);
// Change state of Y and Z so its same as X
for (size_t j = 0; j < LENGTH; j++) {
mY[j] = TYPE(e[j]);
mZ.at(j) = TYPE(e[j]);
}
if (veryVerbose) {
printf("\t\tNew object1: "); P(Y);
printf("\t\tNew object2: "); P(Z);
}
LOOP2_ASSERT(ti, ai, Y == X);
LOOP2_ASSERT(ti, ai, Z == X);
}
}
}
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\tTesting for out_of_range exceptions thrown"
" by at() when pos >= size().\n");
{
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *const SPEC = DATA[ti].d_spec_p;
const size_t LENGTH = DATA[ti].d_length;
for (int ai = 0; ai < NUM_AllocType; ++ai) {
int exceptions, trials;
const int NUM_TRIALS = 2;
// Check exception behavior for non-const version of at()
// Checking the behavior for 'pos == size()' and
// 'pos > size()'.
for (exceptions = 0, trials = 0; trials < NUM_TRIALS
; ++trials) {
try {
Obj mX(*AllocType[ai]);
gg(&mX, SPEC);
mX.at(LENGTH + trials);
} catch (std::out_of_range) {
++exceptions;
if (veryVerbose) {
printf("In out_of_range exception.\n");
P_(LINE); P(trials);
}
continue;
}
}
ASSERT(exceptions == trials);
// Check exception behavior for const version of at()
for (exceptions = 0, trials = 0; trials < NUM_TRIALS
; ++trials) {
try {
Obj mX(*AllocType[ai]);
const Obj& X = gg(&mX, SPEC);
X.at(LENGTH + trials);
} catch (std::out_of_range) {
++exceptions;
if (veryVerbose) {
printf("In out_of_range exception." );
P_(LINE); P(trials);
}
continue;
}
}
ASSERT(exceptions == trials);
}
}
}
#endif // BDE_BUILD_TARGET_EXC
delete AllocType[0];
delete AllocType[1];
delete AllocType[2];
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase3()
{
// --------------------------------------------------------------------
// TESTING PRIMITIVE GENERATOR FUNCTIONS gg AND ggg:
// Having demonstrated that our primary manipulators work as expected
// under normal conditions, we want to verify (1) that valid
// generator syntax produces expected results and (2) that invalid
// syntax is detected and reported.
//
// Plan:
// For each of an enumerated sequence of 'spec' values, ordered by
// increasing 'spec' length, use the primitive generator function
// 'gg' to set the state of a newly created object. Verify that 'gg'
// returns a valid reference to the modified argument object and,
// using basic accessors, that the value of the object is as
// expected. Repeat the test for a longer 'spec' generated by
// prepending a string ending in a '~' character (denoting
// 'clear'). Note that we are testing the parser only; the
// primary manipulators are already assumed to work.
//
// For each of an enumerated sequence of 'spec' values, ordered by
// increasing 'spec' length, use the primitive generator function
// 'ggg' to set the state of a newly created object. Verify that
// 'ggg' returns the expected value corresponding to the location of
// the first invalid value of the 'spec'. Repeat the test for a
// longer 'spec' generated by prepending a string ending in a '~'
// character (denoting 'clear'). Note that we are testing the
// parser only; the primary manipulators are already assumed to work.
//
// Testing:
// string<C,CT,A>& gg(string<C,CT,A> *object, const char *spec);
// int ggg(string<C,CT,A> *object, const char *spec, int vF = 1);
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
if (verbose) printf("\nTesting generator on valid specs.\n");
{
const int MAX_LENGTH = 10;
static const struct {
int d_lineNum; // source line number
const char *d_spec_p; // specification string
int d_length; // expected length
char d_elements[MAX_LENGTH]; // expected element values
} DATA[] = {
//line spec length elements
//---- -------------- ------ ------------------------
{ L_, "", 0, { 0 } },
{ L_, "A", 1, { VA } },
{ L_, "B", 1, { VB } },
{ L_, "~", 0, { 0 } },
{ L_, "CD", 2, { VC, VD } },
{ L_, "E~", 0, { 0 } },
{ L_, "~E", 1, { VE } },
{ L_, "~~", 0, { 0 } },
{ L_, "ABC", 3, { VA, VB, VC } },
{ L_, "~BC", 2, { VB, VC } },
{ L_, "A~C", 1, { VC } },
{ L_, "AB~", 0, { 0 } },
{ L_, "~~C", 1, { VC } },
{ L_, "~B~", 0, { 0 } },
{ L_, "A~~", 0, { 0 } },
{ L_, "~~~", 0, { 0 } },
{ L_, "ABCD", 4, { VA, VB, VC, VD } },
{ L_, "~BCD", 3, { VB, VC, VD } },
{ L_, "A~CD", 2, { VC, VD } },
{ L_, "AB~D", 1, { VD } },
{ L_, "ABC~", 0, { 0 } },
{ L_, "ABCDE", 5, { VA, VB, VC, VD, VE } },
{ L_, "~BCDE", 4, { VB, VC, VD, VE } },
{ L_, "AB~DE", 2, { VD, VE } },
{ L_, "ABCD~", 0, { 0 } },
{ L_, "A~C~E", 1, { VE } },
{ L_, "~B~D~", 0, { 0 } },
{ L_, "~CBA~~ABCDE", 5, { VA, VB, VC, VD, VE } },
{ L_, "ABCDE~CDEC~E", 1, { VE } }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *const SPEC = DATA[ti].d_spec_p;
const size_t LENGTH = DATA[ti].d_length;
const char *const e = DATA[ti].d_elements;
const int curLen = (int)strlen(SPEC);
Obj mX(Z);
const Obj& X = gg(&mX, SPEC); // original spec
static const char *const MORE_SPEC = "~ABCDEABCDEABCDEABCDE~";
char buf[100]; strcpy(buf, MORE_SPEC); strcat(buf, SPEC);
Obj mY(Z);
const Obj& Y = gg(&mY, buf); // extended spec
if (curLen != oldLen) {
if (verbose) printf("\tof length %d:\n", curLen);
LOOP_ASSERT(LINE, oldLen <= curLen); // non-decreasing
oldLen = curLen;
}
if (veryVerbose) {
printf("\t\tSpec = \"%s\"\n", SPEC);
printf("\t\tBigSpec = \"%s\"\n", buf);
T_; T_; T_; P(X);
T_; T_; T_; P(Y);
}
LOOP_ASSERT(LINE, LENGTH == X.size());
LOOP_ASSERT(LINE, LENGTH == Y.size());
for (size_t i = 0; i < LENGTH; ++i) {
LOOP2_ASSERT(LINE, i, TYPE(e[i]) == X[i]);
LOOP2_ASSERT(LINE, i, TYPE(e[i]) == Y[i]);
}
}
}
if (verbose) printf("\nTesting generator on invalid specs.\n");
{
static const struct {
int d_lineNum; // source line number
const char *d_spec_p; // specification string
int d_index; // offending character index
} DATA[] = {
//line spec index
//---- ------------- -----
{ L_, "", -1, }, // control
{ L_, "~", -1, }, // control
{ L_, " ", 0, },
{ L_, ".", 0, },
{ L_, "L", -1, }, // control
{ L_, "M", 0, },
{ L_, "Z", 0, },
{ L_, "AE", -1, }, // control
{ L_, "aE", 0, },
{ L_, "Ae", 1, },
{ L_, ".~", 0, },
{ L_, "~!", 1, },
{ L_, " ", 0, },
{ L_, "ABC", -1, }, // control
{ L_, " BC", 0, },
{ L_, "A C", 1, },
{ L_, "AB ", 2, },
{ L_, "?#:", 0, },
{ L_, " ", 0, },
{ L_, "ABCDE", -1, }, // control
{ L_, "aBCDE", 0, },
{ L_, "ABcDE", 2, },
{ L_, "ABCDe", 4, },
{ L_, "AbCdE", 1, }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
int oldLen = -1;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const char *const SPEC = DATA[ti].d_spec_p;
const int INDEX = DATA[ti].d_index;
const size_t LENGTH = strlen(SPEC);
Obj mX(Z);
if ((int)LENGTH != oldLen) {
if (verbose) printf("\tof length " ZU ":\n", LENGTH);
// LOOP_ASSERT(LINE, oldLen <= (int)LENGTH); // non-decreasing
oldLen = static_cast<int>(LENGTH);
}
if (veryVerbose) printf("\t\tSpec = \"%s\"\n", SPEC);
int result = ggg(&mX, SPEC, veryVerbose);
LOOP_ASSERT(LINE, INDEX == result);
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase2()
{
// --------------------------------------------------------------------
// TESTING PRIMARY MANIPULATORS (BOOTSTRAP):
// The basic concern is that the default constructor, the destructor,
// and, under normal conditions (i.e., no aliasing), the primary
// manipulators
// - push_back (black-box)
// - clear (white-box)
// operate as expected. We have the following specific concerns:
// 1) The default constructor
// 1a) creates the correct initial value.
// 1b) does *not* allocate memory.
// 1c) has the internal memory management system hooked up
// properly so that *all* internally allocated memory
// draws from the same user-supplied allocator whenever
// one is specified.
// 2) The destructor properly deallocates all allocated memory to
// its corresponding allocator from any attainable state.
// 3) 'push_back'
// 3a) produces the expected value.
// 3b) increases capacity as needed.
// 3c) maintains valid internal state.
// 3d) is exception neutral with respect to memory allocation.
// 4) 'clear'
// 4a) produces the expected value (empty).
// 4b) properly destroys each contained element value.
// 4c) maintains valid internal state.
// 4d) does not allocate memory.
// 5) The size based parameters of the class reflect the platform.
//
// Plan:
// To address concerns 1a - 1c, create an object using the default
// constructor:
// - With and without passing in an allocator.
// - In the presence of exceptions during memory allocations using
// a 'bslma::TestAllocator' and varying its *allocation* *limit*.
// - Where the object is constructed with an object allocator, and
// neither of global and default allocator is used to supply memory.
//
// To address concerns 3a - 3c, construct a series of independent
// objects, ordered by increasing length. In each test, allow the
// object to leave scope without further modification, so that the
// destructor asserts internal object invariants appropriately.
// After the final insert operation in each test, use the (untested)
// basic accessors to cross-check the value of the object
// and the 'bslma::TestAllocator' to confirm whether a resize has
// occurred.
//
// To address concerns 4a-4c, construct a similar test, replacing
// 'push_back' with 'clear'; this time, however, use the test
// allocator to record *numBlocksInUse* rather than *numBlocksTotal*.
//
// To address concerns 2, 3d, 4d, create a small "area" test that
// exercises the construction and destruction of objects of various
// lengths and capacities in the presence of memory allocation
// exceptions. Two separate tests will be performed.
//
// Let S be the sequence of integers { 0 .. N - 1 }.
// (1) for each i in S, use the default constructor and 'push_back'
// to create an instance of length i, confirm its value (using
// basic accessors), and let it leave scope.
// (2) for each (i, j) in S X S, use 'push_back' to create an
// instance of length i, use 'clear' to clear its value
// and confirm (with 'length'), use insert to set the instance
// to a value of length j, verify the value, and allow the
// instance to leave scope.
//
// The first test acts as a "control" in that 'clear' is not
// called; if only the second test produces an error, we know that
// 'clear' is to blame. We will rely on 'bslma::TestAllocator'
// and purify to address concern 2, and on the object invariant
// assertions in the destructor to address concerns 3d and 4d.
//
// To address concern 5, the values will be explicitly compared to
// the expected values. This will be done first so as to ensure all
// other tests are reliable and may depend upon the class's
// constants.
//
// Testing:
// string<C,CT,A>(const A& a = A());
// ~string<C,CT,A>();
// void push_back(const T&);
// void clear();
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
// --------------------------------------------------------------------
if (verbose) printf("\n\tTesting default ctor (thoroughly).\n");
if (verbose) printf("\t\tWithout passing in an allocator.\n");
{
const Obj X;
if (veryVerbose) { T_; T_; P(X); }
ASSERT(0 == X.size());
}
if (verbose) printf("\t\tPassing in an allocator.\n");
{
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
const Obj X(Z);
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) { T_; T_; P(X); }
ASSERT(0 == X.size());
ASSERT(AA + 0 == BB);
ASSERT(A + 0 == B);
}
if (verbose) printf("\t\tIn place using a test allocator.\n");
{
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(0 == defaultAllocator_p->numBytesInUse());
ASSERT(0 == objectAllocator_p->numBytesInUse());
Obj x(objectAllocator_p);
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(0 == defaultAllocator_p->numBytesInUse());
ASSERT(0 == objectAllocator_p->numBytesInUse());
}
ASSERT(0 == globalAllocator_p->numBytesInUse());
ASSERT(0 == defaultAllocator_p->numBytesInUse());
ASSERT(0 == objectAllocator_p->numBytesInUse());
// --------------------------------------------------------------------
if (verbose)
printf("\n\tTesting 'push_back' (bootstrap) without allocator.\n");
{
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t li = 0; li < NUM_TRIALS; ++li) {
if (verbose)
printf("\t\tOn an object of initial length " ZU ".\n", li);
Obj mX; const Obj& X = mX;
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
LOOP_ASSERT(li, li == X.size());
if(veryVerbose){
printf("\t\t\tBEFORE: "); P_(X.capacity()); P(X);
}
mX.push_back(VALUES[li % NUM_VALUES]);
if(veryVerbose){
printf("\t\t\tAFTER: "); P_(X.capacity()); P(X);
}
LOOP_ASSERT(li, li + 1 == X.size());
for (size_t i = 0; i < li; ++i) {
LOOP2_ASSERT(li, i, VALUES[i % NUM_VALUES] == X[i]);
}
LOOP_ASSERT(li, VALUES[li % NUM_VALUES] == X[li]);
}
}
// --------------------------------------------------------------------
if (verbose)
printf("\n\tTesting 'push_back' (bootstrap) with allocator.\n");
{
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t li = 0; li < NUM_TRIALS; ++li) {
if (verbose) printf("\t\tOn an object of initial length " ZU ".\n",
li);
Obj mX(Z); const Obj& X = mX;
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
LOOP_ASSERT(li, li == X.size());
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tBEFORE: ");
P_(BB); P_(B); P_(X.capacity()); P(X);
}
mX.push_back(VALUES[li % NUM_VALUES]);
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\t AFTER: ");
P_(AA); P_(A); P_(X.capacity()); P(X);
}
// LOOP_ASSERT(li, BB + NUM_ALLOCS[li + 1] - NUM_ALLOCS[li] == AA);
// LOOP_ASSERT(li, B + 1 == A);
LOOP_ASSERT(li, li + 1 == X.size());
for (size_t i = 0; i < li; ++i) {
LOOP2_ASSERT(li, i, VALUES[i % NUM_VALUES] == X[i]);
}
LOOP_ASSERT(li, VALUES[li % NUM_VALUES] == X[li]);
}
}
// --------------------------------------------------------------------
if (verbose) printf("\n\tTesting 'clear' without allocator.\n");
{
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t li = 0; li < NUM_TRIALS; ++li) {
if (verbose) printf("\t\tOn an object of initial length " ZU ".\n",
li);
Obj mX; const Obj& X = mX;
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
if(veryVerbose){
printf("\t\t\tBEFORE ");
P_(X.capacity()); P(X);
}
LOOP_ASSERT(li, li == X.size());
mX.clear();
if(veryVerbose){
printf("\t\t\tAFTER ");
P_(X.capacity()); P(X);
}
LOOP_ASSERT(li, 0 == X.size());
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
LOOP_ASSERT(li, li == X.size());
if(veryVerbose){
printf("\t\t\tAFTER SECOND INSERT ");
P_(X.capacity()); P(X);
}
}
}
// --------------------------------------------------------------------
if (verbose) printf("\n\tTesting 'clear' with allocator.\n");
{
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t li = 0; li < NUM_TRIALS; ++li) {
if (verbose) printf("\t\tOn an object of initial length " ZU ".\n",
li);
Obj mX(Z); const Obj& X = mX;
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
LOOP_ASSERT(li, li == X.size());
const Int64 BB = testAllocator.numBlocksTotal();
const Int64 B = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tBEFORE: ");
P_(BB); P_(B);
typename Obj::size_type Cap = X.capacity();P_(Cap);P(X);
}
mX.clear();
const Int64 AA = testAllocator.numBlocksTotal();
const Int64 A = testAllocator.numBlocksInUse();
if (veryVerbose) {
printf("\t\t\tAFTER: ");
P_(AA); P_(A); P_(X.capacity()); P(X);
}
for (size_t i = 0; i < li; ++i) {
mX.push_back(VALUES[i % NUM_VALUES]);
}
LOOP_ASSERT(li, li == X.size());
const Int64 CC = testAllocator.numBlocksTotal();
const Int64 C = testAllocator.numBlocksInUse();
if(veryVerbose){
printf("\t\t\tAFTER SECOND INSERT: ");
P_(CC); P_(C); P_(X.capacity()); P(X);
}
LOOP_ASSERT(li, li == X.size());
LOOP_ASSERT(li, BB == AA);
LOOP_ASSERT(li, BB == CC);
LOOP_ASSERT(li, B == A);
LOOP_ASSERT(li, B == C);
}
}
// --------------------------------------------------------------------
if (verbose) printf("\n\tTesting the destructor and exception neutrality "
"with allocator.\n");
if (verbose) printf("\t\tWith 'push_back' only\n");
{
// For each lengths li up to some modest limit:
// 1) create an instance
// 2) insert { V0, V1, V2, V3, V4, V0, ... } up to length li
// 3) verify initial length and contents
// 4) allow the instance to leave scope
// 5) make sure that the destructor cleans up
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t li = 0; li < NUM_TRIALS; ++li) { // i is the length
if (verbose) printf("\t\t\tOn an object of length " ZU ".\n", li);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
Obj mX(Z); const Obj& X = mX; // 1.
for (size_t i = 0; i < li; ++i) { // 2.
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.push_back(VALUES[i % NUM_VALUES]);
guard.release();
}
LOOP_ASSERT(li, li == X.size()); // 3.
for (size_t i = 0; i < li; ++i) {
LOOP2_ASSERT(li, i, VALUES[i % NUM_VALUES] == X[i]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END // 4.
LOOP_ASSERT(li, 0 == testAllocator.numBlocksInUse()); // 5.
}
}
if (verbose) printf("\t\tWith 'push_back' and 'clear'\n");
{
// For each pair of lengths (i, j) up to some modest limit:
// 1) create an instance
// 2) insert V0 values up to a length of i
// 3) verify initial length and contents
// 4) clear contents from instance
// 5) verify length is 0
// 6) insert { V0, V1, V2, V3, V4, V0, ... } up to length j
// 7) verify new length and contents
// 8) allow the instance to leave scope
// 9) make sure that the destructor cleans up
const size_t NUM_TRIALS = LARGE_SIZE_VALUE;
for (size_t i = 0; i < NUM_TRIALS; ++i) { // i is first length
if (verbose)
printf("\t\t\tOn an object of initial length " ZU ".\n", i);
for (size_t j = 0; j < NUM_TRIALS; ++j) { // j is second length
if (veryVerbose)
printf("\t\t\t\tAnd with final length " ZU ".\n", j);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) {
size_t k; // loop index
Obj mX(Z); const Obj& X = mX; // 1.
for (k = 0; k < i; ++k) { // 2.
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.push_back(VALUES[0]);
guard.release();
}
LOOP2_ASSERT(i, j, i == X.size()); // 3.
for (k = 0; k < i; ++k) {
LOOP3_ASSERT(i, j, k, VALUES[0] == X[k]);
}
mX.clear(); // 4.
LOOP2_ASSERT(i, j, 0 == X.size()); // 5.
for (k = 0; k < j; ++k) { // 6.
ExceptionGuard<Obj> guard(&mX, X, L_);
mX.push_back(VALUES[k % NUM_VALUES]);
guard.release();
}
LOOP2_ASSERT(i, j, j == X.size()); // 7.
for (k = 0; k < j; ++k) {
LOOP3_ASSERT(i, j, k, VALUES[k % NUM_VALUES] == X[k]);
}
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END // 8.
LOOP_ASSERT(i, 0 == testAllocator.numBlocksInUse()); // 9.
}
}
}
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCase1()
{
// --------------------------------------------------------------------
// BREATHING TEST:
// We want to exercise basic value-semantic functionality. In
// particular we want to demonstrate a base-line level of correct
// operation of the following methods and operators:
// - default and copy constructors (and also the destructor)
// - the assignment operator (including aliasing)
// - equality operators: 'operator==' and 'operator!='
// - primary manipulators: 'push_back' and 'clear' methods
// - basic accessors: 'size' and 'operator[]'
// In addition we would like to exercise objects with potentially
// different internal organizations representing the same value.
//
// Plan:
// Create four objects using both the default and copy constructors.
// Exercise these objects using primary manipulators, basic
// accessors, equality operators, and the assignment operator.
// Invoke the primary manipulator [1&5], copy constructor [2&8], and
// assignment operator [9&10] in situations where the internal data
// (i) does *not* and (ii) *does* have to resize. Try aliasing with
// assignment for a non-empty instance [11] and allow the result to
// leave scope, enabling the destructor to assert internal object
// invariants. Display object values frequently in verbose mode:
//
// 1) Create an object x1 (default ctor). { x1: }
// 2) Create a second object x2 (copy from x1). { x1: x2: }
// 3) Append an element value A to x1). { x1:A x2: }
// 4) Append the same element value A to x2). { x1:A x2:A }
// 5) Append another element value B to x2). { x1:A x2:AB }
// 6) Remove all elements from x1. { x1: x2:AB }
// 7) Create a third object x3 (default ctor). { x1: x2:AB x3: }
// 8) Create a forth object x4 (copy of x2). { x1: x2:AB x3: x4:AB }
// 9) Assign x2 = x1 (non-empty becomes empty). { x1: x2: x3: x4:AB }
// 10) Assign x3 = x4 (empty becomes non-empty).{ x1: x2: x3:AB x4:AB }
// 11) Assign x4 = x4 (aliasing). { x1: x2: x3:AB x4:AB }
//
// Testing:
// This "test" *exercises* basic functionality.
// --------------------------------------------------------------------
bslma::TestAllocator testAllocator(veryVeryVerbose);
Allocator Z(&testAllocator);
const TYPE *values = 0;
const TYPE *const& VALUES = values;
const int NUM_VALUES = getValues(&values);
(void) NUM_VALUES;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 1) Create an object x1 (default ctor)."
"\t\t\t{ x1: }\n");
Obj mX1(Z); const Obj& X1 = mX1;
if (verbose) { T_; P(X1); }
if (verbose) printf("\ta) Check initial state of x1.\n");
ASSERT(0 == X1.size());
if(veryVerbose){
typename Obj::size_type capacity = X1.capacity();
T_; T_;
P(capacity);
}
if (verbose) printf(
"\tb) Try equality operators: x1 <op> x1.\n");
ASSERT( X1 == X1 ); ASSERT(!(X1 != X1));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 2) Create a second object x2 (copy from x1)."
"\t\t{ x1: x2: }\n");
Obj mX2(X1, AllocType(&testAllocator)); const Obj& X2 = mX2;
if (verbose) { T_; P(X2); }
if (verbose) printf(
"\ta) Check the initial state of x2.\n");
ASSERT(0 == X2.size());
if (verbose) printf(
"\tb) Try equality operators: x2 <op> x1, x2.\n");
ASSERT( X2 == X1 ); ASSERT(!(X2 != X1));
ASSERT( X2 == X2 ); ASSERT(!(X2 != X2));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 3) Append an element value A to x1)."
"\t\t\t{ x1:A x2: }\n");
mX1.push_back(VALUES[0]);
if (verbose) { T_; P(X1); }
if (verbose) printf(
"\ta) Check new state of x1.\n");
ASSERT(1 == X1.size());
ASSERT(VALUES[0] == X1[0]);
if (verbose) printf(
"\tb) Try equality operators: x1 <op> x1, x2.\n");
ASSERT( X1 == X1 ); ASSERT(!(X1 != X1));
ASSERT(!(X1 == X2)); ASSERT( X1 != X2 );
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 4) Append the same element value A to x2)."
"\t\t{ x1:A x2:A }\n");
mX2.push_back(VALUES[0]);
if (verbose) { T_; P(X2); }
if (verbose) printf(
"\ta) Check new state of x2.\n");
ASSERT(1 == X2.size());
ASSERT(VALUES[0] == X2[0]);
if (verbose) printf(
"\tb) Try equality operators: x2 <op> x1, x2.\n");
ASSERT( X2 == X1 ); ASSERT(!(X2 != X1));
ASSERT( X2 == X2 ); ASSERT(!(X2 != X2));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 5) Append another element value B to x2)."
"\t\t{ x1:A x2:AB }\n");
mX2.push_back(VALUES[1]);
if (verbose) { T_; P(X2); }
if (verbose) printf(
"\ta) Check new state of x2.\n");
ASSERT(2 == X2.size());
ASSERT(VALUES[0] == X2[0]);
ASSERT(VALUES[1] == X2[1]);
if (verbose) printf(
"\tb) Try equality operators: x2 <op> x1, x2.\n");
ASSERT(!(X2 == X1)); ASSERT( X2 != X1 );
ASSERT( X2 == X2 ); ASSERT(!(X2 != X2));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 6) Remove all elements from x1."
"\t\t\t{ x1: x2:AB }\n");
mX1.clear();
if (verbose) { T_; P(X1); }
if (verbose) printf(
"\ta) Check new state of x1.\n");
ASSERT(0 == X1.size());
if (verbose) printf(
"\tb) Try equality operators: x1 <op> x1, x2.\n");
ASSERT( X1 == X1 ); ASSERT(!(X1 != X1));
ASSERT(!(X1 == X2)); ASSERT( X1 != X2 );
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 7) Create a third object x3 (default ctor)."
"\t\t{ x1: x2:AB x3: }\n");
Obj mX3(Z); const Obj& X3 = mX3;
if (verbose) { T_; P(X3); }
if (verbose) printf(
"\ta) Check new state of x3.\n");
ASSERT(0 == X3.size());
if (verbose) printf(
"\tb) Try equality operators: x3 <op> x1, x2, x3.\n");
ASSERT( X3 == X1 ); ASSERT(!(X3 != X1));
ASSERT(!(X3 == X2)); ASSERT( X3 != X2 );
ASSERT( X3 == X3 ); ASSERT(!(X3 != X3));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 8) Create a forth object x4 (copy of x2)."
"\t\t{ x1: x2:AB x3: x4:AB }\n");
Obj mX4(X2, AllocType(&testAllocator)); const Obj& X4 = mX4;
if (verbose) { T_; P(X4); }
if (verbose) printf(
"\ta) Check new state of x4.\n");
ASSERT(2 == X4.size());
ASSERT(VALUES[0] == X4[0]);
ASSERT(VALUES[1] == X4[1]);
if (verbose) printf(
"\tb) Try equality operators: x4 <op> x1, x2, x3, x4.\n");
ASSERT(!(X4 == X1)); ASSERT( X4 != X1 );
ASSERT( X4 == X2 ); ASSERT(!(X4 != X2));
ASSERT(!(X4 == X3)); ASSERT( X4 != X3 );
ASSERT( X4 == X4 ); ASSERT(!(X4 != X4));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n 9) Assign x2 = x1 (non-empty becomes empty)."
"\t\t{ x1: x2: x3: x4:AB }\n");
mX2 = X1;
if (verbose) { T_; P(X2); }
if (verbose) printf(
"\ta) Check new state of x2.\n");
ASSERT(0 == X2.size());
if (verbose) printf(
"\tb) Try equality operators: x2 <op> x1, x2, x3, x4.\n");
ASSERT( X2 == X1 ); ASSERT(!(X2 != X1));
ASSERT( X2 == X2 ); ASSERT(!(X2 != X2));
ASSERT( X2 == X3 ); ASSERT(!(X2 != X3));
ASSERT(!(X2 == X4)); ASSERT( X2 != X4 );
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n10) Assign x3 = x4 (empty becomes non-empty)."
"\t\t{ x1: x2: x3:AB x4:AB }\n");
mX3 = X4;
if (verbose) { T_; P(X3); }
if (verbose) printf(
"\ta) Check new state of x3.\n");
ASSERT(2 == X3.size());
ASSERT(VALUES[0] == X3[0]);
ASSERT(VALUES[1] == X3[1]);
if (verbose) printf(
"\tb) Try equality operators: x3 <op> x1, x2, x3, x4.\n");
ASSERT(!(X3 == X1)); ASSERT( X3 != X1 );
ASSERT(!(X3 == X2)); ASSERT( X3 != X2 );
ASSERT( X3 == X3 ); ASSERT(!(X3 != X3));
ASSERT( X3 == X4 ); ASSERT(!(X3 != X4));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) printf("\n11) Assign x4 = x4 (aliasing)."
"\t\t\t\t{ x1: x2: x3:AB x4:AB }\n");
mX4 = X4;
if (verbose) { T_; P(X4); }
if (verbose) printf(
"\ta) Check new state of x4.\n");
ASSERT(2 == X4.size());
ASSERT(VALUES[0] == X4[0]);
ASSERT(VALUES[1] == X4[1]);
if (verbose)
printf("\tb) Try equality operators: x4 <op> x1, x2, x3, x4.\n");
ASSERT(!(X4 == X1)); ASSERT( X4 != X1 );
ASSERT(!(X4 == X2)); ASSERT( X4 != X2 );
ASSERT( X4 == X3 ); ASSERT(!(X4 != X3));
ASSERT( X4 == X4 ); ASSERT(!(X4 != X4));
}
template <class TYPE, class TRAITS, class ALLOC>
void TestDriver<TYPE,TRAITS,ALLOC>::testCaseM1(const int /* NITER */,
const int /* RANDOM_SEED */)
{
// --------------------------------------------------------------------
// PERFORMANCE TEST
// We have the following concerns:
// 1) That performance does not regress between versions.
// 2) That no surprising performance (both extremely fast or slow) is
// detected, which might be indicating missed optimizations or
// inadvertent loss of performance (e.g., by wrongly setting the
// capacity and triggering too frequent reallocations).
// 3) That small "improvements" can be tested w.r.t. to performance, in a
// uniform benchmark (e.g., measuring the overhead of allocating for
// empty strings).
//
// Plan: We follow a simple benchmark which performs the operation under
// timing test in a loop. Specifically, we wish to measure the time
// taken by:
// C1) The various constructors.
// C2) The copy constructor.
// A1) The copy assignment.
// A2) The 'assign' operations.
// P1) The 'append' operation in its various forms (including
// 'push_back').
// I1) The 'insert' operation in its various forms, at the end (should
// be compared to the corresponding 'append' sequence).
// B1) The 'insert' operation in its various forms.
// M3) The 'replace' operation in its various forms.
// S1) The 'swap' operation in its various forms.
// F1) The 'find' and 'rfind' operations.
// F2) The 'find_first_of' and 'find_last_of' operations.
// F3) The 'find_first_not_of' and 'find_last_not_of' operations.
// Also we wish to record the size of the various string
// instantiations.
//
// We create two tables, one containing long strings, and another
// containing short strings. All strings are preallocated so that we do
// not measure the performance of the random generator. In order not to
// measure the time overhead of the test allocator, we use the default
// allocator throughout. As for choosing the overloads to use, we rely
// on the implementation and avoid those that are simple inline
// forwarding calls (this might need to be adjusted for different
// implementations, however most implementations rely on a single
// implementation and the other calls can reduce to it).
// Note: This is a *synthetic* benchmark. It does not replace measuring
// real benchmarks (e.g., for strings, ADSP) whose conclusions may differ
// due to different memory allocation and access patterns, function call
// frequencies, etc. Its main use is for comparing two implementations
// (versions) against the same benchmark, and to test that one
// improvement in one function does not translate into a slow-down in
// another function.
//
// Also note, that this is spaghetti code but we make no attempt at
// shortening it with helper functions or macros, since we feel that
//
// Testing:
// This "test" measures performance of basic operations, for performance
// regression.
//
//
// RESULTS: Native SunProSTL on sundev13 as of Tue Jun 24 16:48:36 EDT 2008
// ------------------------------------------------------------------------
//
// String size: 4 bytes.
// Using 50000 short words and 1000 long words.
// Total length about same: 999618 (short) and 997604 (long).
//
// Short Long Total
// ----- ---- -----
// Constructors:
// C1 Default ctor: 0.003849s 0.000098s 0.003947s
// C2 From 'char*': 0.01829s 0.00043s 0.018722s
// C3 Copy ctor: 0.02700s 0.00044s 0.027436s
// Assignment (no reallocation):
// A1 'operator=': 0.02696s 0.00051s 0.027473s
// A2 Assign string: 0.10399s 0.00984s 0.113824s
// A3 Assign range: 0.11826s 0.01286s 0.131116s
// Append (with reallocations):
// P1 Append chars: 0.58007s 2.54784s 3.127911s
// P2 Append string: 0.87475s 3.07695s 3.951698s
// (without reallocation):
// P3 Append string: 0.13705s 0.02840s 0.165452s
// P4 Append range: 0.15452s 0.07269s 0.227208s
// Insertions at end (with reallocations):
// I1 Insert chars: 0.22898s 2.03761s 2.266580s
// I2 Insert string: 0.54691s 2.39825s 2.945158s
// at end (without reallocation):
// I3 Insert string: 0.15257s 0.06108s 0.213649s
// I4 Insert range: 0.17466s 0.07843s 0.253086s
// Insertions at beginning (with reallocations):
// B1 Insert chars: 0.23185s 2.17408s 2.405936s
// B2 Insert string: 0.24647s 2.07533s 2.321807s
// (without reallocation):
// B3 Insert string: 0.14609s 0.22978s 0.375868s
// B4 Insert range: 0.17793s 0.20753s 0.385453s
// Replacements (without reallocation):
// R1 Replace at end: 0.16203s 0.06911s 0.231147s
// R2 Replace at begin: 0.15793s 1.08946s 1.247386s
// Misc.:
// M1 Swap reverse: 0.07511s 0.06057s 0.135686s
// M2 Substring: 5.60723s 14.51155s 20.118778s
//
// RESULTS: bslstl 1.11 on sundev13 as of Mon Jun 30 14:23:52 EDT 2008
// --------------------------------------------------------------------
//
// String size: 16 bytes.
// Using 50000 short words and 1000 long words.
// Total length about same: 999618 (short) and 997604 (long).
//
// Total amount of work should be about same in both
// long and short columns (one long string vs. many
// short strings), except for reallocations.
//
// Short Long Total
// ----- ---- -----
// Constructors:
// C1 Default ctor: 0.007775s 0.000244s 0.008019s
// C2 From 'char*': 0.06390s 0.00924s 0.073137s
// C3 Copy ctor: 0.06638s 0.00931s 0.075684s
// Assignment (no reallocation):
// A1 'operator=': 0.02828s 0.01366s 0.041943s
// A2 Assign string: 0.02685s 0.01311s 0.039953s
// A3 Assign range: 0.02439s 0.01429s 0.038676s
// Append (with reallocations):
// P1 Append chars: 0.56922s 0.52341s 1.092630s
// P2 Append string: 0.69453s 0.60602s 1.300548s
// (without reallocation):
// P3 Append string: 0.13577s 0.02976s 0.165528s
// P4 Append range: 0.13689s 0.06424s 0.201128s
// Insertions at end (with reallocations):
// I1 Insert chars: 0.23625s 0.19838s 0.434627s
// I2 Insert string: 0.22206s 0.16017s 0.382224s
// at end (without reallocation):
// I3 Insert string: 0.13643s 0.06546s 0.201888s
// I4 Insert range: 0.14023s 0.06459s 0.204820s
// Insertions at beginning (with reallocations):
// B1 Insert chars: 0.22982s 1.27716s 1.506978s
// B2 Insert string: 0.22201s 0.38553s 0.607539s
// (without reallocation):
// B3 Insert string: 0.14811s 0.49707s 0.645182s
// B4 Insert range: 0.14965s 0.50169s 0.651337s
// Replacements (without reallocation):
// R1 Replace at end: 0.16184s 0.07699s 0.238831s
// R2 Replace at begin: 0.16303s 1.23734s 1.400366s
// Misc.:
// M1 Swap reverse: 0.23449s 0.09505s 0.329545s
// M2 Substring: 5.18101s 31.76464s 36.945650s
//
// RESULTS: Native gcc STL on sundev13 as of Tue Jun 24 16:48:36 EDT 2008
// ----------------------------------------------------------------------
//
// String size: 4 bytes.
// Using 50000 short words and 1000 long words.
// Total length about same: 999618 (short) and 997604 (long).
//
// Short Long Total
// ----- ---- -----
// Constructors:
// C1 Default ctor: 0.001821s 0.000066s 0.001887s
// C2 From 'char*': 0.01383s 0.00048s 0.014304s
// C3 Copy ctor: 0.01726s 0.00019s 0.017452s
// Assignment (no reallocation):
// A1 'operator=': 0.00372s 0.00007s 0.003786s
// A2 Assign string: 0.00128s 0.00003s 0.001310s
// A3 Assign range: 0.11978s 0.01919s 0.138965s
// Append (with reallocations):
// P1 Append chars: 0.61198s 0.48359s 1.095569s
// P2 Append string: 0.85236s 0.66129s 1.513646s
// (without reallocation):
// P3 Append string: 0.15236s 0.02859s 0.180949s
// P4 Append range: 0.16615s 0.05822s 0.224371s
// Insertions at end (with reallocations):
// I1 Insert chars: 0.19453s 0.15631s 0.350844s
// I2 Insert string: 0.19757s 0.14761s 0.345184s
// at end (without reallocation):
// I3 Insert string: 0.14629s 0.05944s 0.205725s
// I4 Insert range: 0.14613s 0.06080s 0.206930s
// Insertions at beginning (with reallocations):
// B1 Insert chars: 0.21156s 0.22866s 0.440219s
// B2 Insert string: 0.24475s 0.23070s 0.475451s
// (without reallocation):
// B3 Insert string: 0.15124s 0.19940s 0.350643s
// B4 Insert range: 0.18475s 0.21291s 0.397659s
// Replacements (without reallocation):
// R1 Replace at end: 0.16595s 0.07109s 0.237031s
// R2 Replace at begin: 0.22566s 1.30403s 1.529692s
// Misc.:
// M1 Swap reverse: 1.30312s 0.39883s 1.701954s
// M2 Substring: 4.79876s 11.50113s 16.299887s
//
// RESULTS: Native STL on ibm1 as of Tue Jun 24 16:48:36 EDT 2008
// ------------------------------------------------------------------
//
// String size: 16 bytes.
// Using 50000 short words and 1000 long words.
// Total length about same: 999618 (short) and 997604 (long).
//
// Short Long Total
// ----- ---- -----
// Constructors:
// C1 Default ctor: 0.001741s 0.000031s 0.001772s
// C2 From 'char*': 0.02315s 0.00278s 0.025921s
// C3 Copy ctor: 0.02373s 0.00277s 0.026501s
// Assignment (no reallocation):
// A1 'operator=': 0.00253s 0.00071s 0.003236s
// A2 Assign string: 0.00672s 0.00098s 0.007693s
// A3 Assign range: 0.00788s 0.00042s 0.008292s
// Append (with reallocations):
// P1 Append chars: 0.15841s 0.17874s 0.337155s
// P2 Append string: 0.17893s 0.18019s 0.359119s
// (without reallocation):
// P3 Append string: 0.06268s 0.01879s 0.081468s
// P4 Append range: 0.04941s 0.03089s 0.080301s
// Insertions at end (with reallocations):
// I1 Insert chars: 0.06832s 0.06723s 0.135552s
// I2 Insert string: 0.07338s 0.06499s 0.138365s
// at end (without reallocation):
// I3 Insert string: 0.04835s 0.02264s 0.070989s
// I4 Insert range: 0.05462s 0.02913s 0.083743s
// Insertions at beginning (with reallocations):
// B1 Insert chars: 0.06699s 0.07817s 0.145161s
// B2 Insert string: 0.07192s 0.07696s 0.148877s
// (without reallocation):
// B3 Insert string: 0.03464s 0.03325s 0.067894s
// B4 Insert range: 0.04500s 0.04113s 0.086138s
// Replacements (without reallocation):
// R1 Replace at end: 0.05194s 0.02473s 0.076671s
// R2 Replace at begin: 0.04611s 0.29988s 0.345990s
// Misc.:
// M1 Swap reverse: 0.01834s 0.01893s 0.037267s
// M2 Substring: 2.23025s 6.25982s 8.490068s
//
// RESULTS: bslstl 1.11 on ibm1 as of Mon Jun 30 14:24:46 EDT 2008
// --------------------------------------------------------------------
//
// --------------------------------------------------------------------
bsls::Stopwatch t;
printf("\n\tString size:\t\t" ZU " bytes.\n", sizeof(Obj));
const TYPE DEFAULT_VALUE = TYPE(::DEFAULT_VALUE);
// DATA INITIALIZATION (NOT TIMED)
const int SHORT_LENGTH = 16; // length of short words
const int SHORT_SIGMA = 8; // max deviation for short words
const int NSHORT = 50000; // number of short words
const int LONG_LENGTH = 800; // length of long words
const int LONG_SIGMA = 400; // max deviation for long words
const int NLONG = 1000; // number of long words
ASSERT(NSHORT * (SHORT_LENGTH + SHORT_SIGMA / 2) ==
NLONG * (LONG_LENGTH + LONG_SIGMA / 2));
const int SL_RATIO = NSHORT / NLONG;
ASSERT(NLONG < NSHORT && 0 < SL_RATIO );
Obj *shortWords = new Obj[NSHORT];
size_t totalShortLength = 0;
Obj *longWords = new Obj[NLONG];
size_t totalLongLength = 0;
for (int i = 0; i < NSHORT; ++i) {
const size_t LENGTH = SHORT_LENGTH + (rand() % (SHORT_SIGMA + 1));
shortWords[i].assign(LENGTH, DEFAULT_VALUE);
totalShortLength += LENGTH;
}
for (int i = 0; i < NLONG; ++i) {
const size_t LENGTH = LONG_LENGTH + (rand() % (LONG_SIGMA + 1));
longWords[i].assign(LENGTH, DEFAULT_VALUE);
totalLongLength += LENGTH;
}
printf("\tUsing %d short words and %d long words.\n"
"\tTotal length about same: " ZU " (short) and " ZU " (long).\n\n",
NSHORT, NLONG, totalShortLength, totalLongLength);
printf("\tTotal amount of work should be about same in both\n"
"\tlong and short columns (one long string vs. many\n"
"\tshort strings), except for reallocations.\n\n");
printf("\t\t\t\tShort\t\tLong\t\tTotal\n");
printf("\t\t\t\t-----\t\t----\t\t-----\n");
printf("\tConstructors:\n");
// {
// C1) CONSTRUCTORS
double timeC1 = 0., timeC1short = 0., timeC1long = 0.;
t.reset(); t.start();
Obj *shortStrings = new Obj[NSHORT];
timeC1short = t.elapsedTime();
size_t *shortStringLength = new size_t[NSHORT];
t.reset(); t.start();
Obj *longStrings = new Obj[NLONG];
timeC1long = t.elapsedTime();
size_t *longStringLength = new size_t[NLONG];
printf("\t C1\tDefault ctor:\t%1.6fs\t%1.6fs\t%1.6fs\n",
timeC1short, timeC1long, timeC1 = timeC1short + timeC1long);
// C2) CONSTRUCTORS
double timeC2 = 0., timeC2short = 0., timeC2long = 0.;
for (int i = 0; i < NSHORT; ++i) {
(shortStrings + i)->~Obj();
}
t.reset(); t.start();
for (int i = 0; i < NSHORT; ++i) {
new(shortStrings + i) Obj(shortWords[i]);
}
timeC2short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) {
shortStringLength[i] = shortStrings[i].length();
}
for (int i = 0; i < NLONG; ++i) {
(longStrings + i)->~Obj();
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
new(longStrings + i) Obj(longWords[i]);
}
timeC2long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) {
longStringLength[i] = longStrings[i].length();
}
printf("\t C2\tFrom 'char*':\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeC2short, timeC2long, timeC2 = timeC2short + timeC2long);
// C3) COPY CONSTRUCTOR (with allocations)
double timeC3 = 0., timeC3short = 0., timeC3long = 0.;
void *shortStringBufCopy = new bsls::ObjectBuffer<Obj>[NSHORT];
void *longStringBufCopy = new bsls::ObjectBuffer<Obj>[NLONG];
Obj *shortStringCopy = (Obj *)shortStringBufCopy;
Obj *longStringCopy = (Obj *)longStringBufCopy;
t.reset(); t.start();
for (int i = 0; i < NSHORT; ++i) {
new(shortStringCopy + i) Obj(shortStrings[i]);
}
timeC3short = t.elapsedTime();
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
new(longStringCopy + i) Obj(longStrings[i]);
}
timeC3long = t.elapsedTime();
printf("\t C3\tCopy ctor:\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeC3short, timeC3long, timeC3 = timeC3short + timeC3long);
// }
printf("\tAssignment (no reallocation):\n");
// {
// A1) COPY ASSIGNMENT (without allocations)
double timeA1 = 0., timeA1short = 0., timeA1long = 0.;
t.reset(); t.start();
for (int i = 0; i < NSHORT; ++i) {
shortStringCopy[i] = shortStrings[i];
}
timeA1short = t.elapsedTime();
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
longStringCopy[i] = longStrings[i];
}
timeA1long = t.elapsedTime();
printf("\t A1\t'operator=':\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeA1short, timeA1long, timeA1 = timeA1short + timeA1long);
// A2) ASSIGN OPERATIONS (again, no allocation)
double timeA2 = 0., timeA2short = 0., timeA2long = 0.;
t.reset(); t.start();
for (int i = 0; i < NSHORT; ++i) {
shortStringCopy[i].assign(shortStrings[i]);
}
timeA2short = t.elapsedTime();
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
longStringCopy[i].assign(longStrings[i]);
}
timeA2long = t.elapsedTime();
printf("\t A2\tAssign string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeA2short, timeA2long, timeA2 = timeA2short + timeA2long);
// A3.
double timeA3 = 0., timeA3short = 0., timeA3long = 0.;
t.reset(); t.start();
for (int i = 0; i < NSHORT; ++i) {
shortStringCopy[i].assign(shortStrings[i].begin(),
shortStrings[i].end());
}
timeA3short = t.elapsedTime();
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
longStringCopy[i].assign(longStrings[i].begin(),
longStrings[i].end());
}
timeA3long = t.elapsedTime();
printf("\t A3\tAssign range:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeA3short, timeA3long, timeA3 = timeA3short + timeA3long);
// }
#define COMPARE_WITH_NATIVE_SUNPRO_STL 1
// When comparing performance with the native Sunpro STL (based on Rogue
// Wave), a bug causes the native STL to reallocate every time after
// push_back, instead of doubling the capacity. This prohibits the testing
// of P1, I1, and B1.
printf("\tAppend (with reallocations):\n");
// {
// P1) PUSH_BACK OPERATION (with reallocations, i.e., changes capacity)
// Pushing individual chars into either short/long strings, should take
// slightly shorter for long strings since there will be fewer
// reallocations.
double timeP1 = 0., timeP1short = 0., timeP1long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (int j = 0; j < longStringLength[ilong]; ++j) {
shortStrings[i].push_back(longStringCopy[ilong][j]);
}
#else
shortStrings[i].append(longStringCopy[ilong]);
#endif
}
timeP1short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStrings[i].erase(shortStringLength[i]);
ASSERT(shortStringLength[i] == shortStrings[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (int j = 0; j < longStringLength[i]; ++j) {
for (int k = 0; k < SL_RATIO; ++k) {
longStrings[i].push_back(longStringCopy[i][j]);
}
}
#else
for (int k = 0; k < SL_RATIO; ++k) {
longStrings[i].append(longStringCopy[i]);
}
#endif
}
timeP1long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStrings[i].erase(longStringLength[i]);
ASSERT(longStringLength[i] == longStrings[i].length());
}
printf("\t P1\tAppend chars:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeP1short, timeP1long, timeP1 = timeP1short + timeP1long);
// P2) APPEND OPERATION (with reallocations, i.e., changes capacity)
// Unlike P1, pushing whole string at once will be more efficient since
// only one allocation for short strings (final length is known), or
// only a few reallocations for long strings.
double timeP2 = 0., timeP2short = 0., timeP2long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].append(longStrings[ilong]);
}
timeP2short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].append(longStrings[i]);
}
}
timeP2long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t P2\tAppend string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeP2short, timeP2long, timeP2 = timeP2short + timeP2long);
// }
printf("\t\t(without reallocation):\n");
// {
// P3) AGAIN (this time, without reallocation)
double timeP3 = 0., timeP3short = 0., timeP3long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].append(longStrings[ilong]);
}
timeP3short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i, ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].append(longStrings[i]);
}
}
timeP3long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t P3\tAppend string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeP3short, timeP3long, timeP3 = timeP3short + timeP3long);
// P4) APPEND RANGE
double timeP4 = 0., timeP4short = 0., timeP4long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].append(longStrings[ilong].begin(),
longStrings[ilong].end());
}
timeP4short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].append(longStrings[i].begin(),
longStrings[i].end());
}
}
timeP4long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t P4\tAppend range:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeP4short, timeP4long, timeP4 = timeP4short + timeP4long);
// }
printf("\tInsertions at end (with reallocations):\n");
// {
// I1) INSERT OPERATION (with reallocations, i.e., changes capacity)
double timeI1 = 0., timeI1short = 0., timeI1long = 0.;
for (int i = 0; i < NSHORT; ++i) { // restore length *and* capacity
Obj(shortWords[i]).swap(shortStrings[i]);
ASSERT(shortStringLength[i] == shortStrings[i].length());
// ASSERT(shortStringLength[i] == shortStrings[i].capacity());
}
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (int j = 0; j < longStringLength[ilong]; ++j) {
shortStrings[i].insert(shortStrings[i].end(),
longStrings[ilong][j]);
}
#else
shortStrings[i].insert(shortStrings[i].length(),
longStrings[ilong]);
#endif
}
timeI1short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStrings[i].erase(shortStringLength[i]);
ASSERT(shortStringLength[i] == shortStrings[i].length());
}
for (int i = 0; i < NLONG; ++i) { // restore length *and* capacity
Obj(longWords[i]).swap(longStrings[i]);
ASSERT(longStringLength[i] == longStrings[i].length());
// ASSERT(longStringLength[i] == longStrings[i].capacity());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (int j = 0; j < longStringLength[i]; ++j) {
for (int k = 0; k < SL_RATIO; ++k) {
longStrings[i].insert(longStrings[i].end(),
longStringCopy[i][j]);
}
}
#else
for (int k = 0; k < SL_RATIO; ++k) {
longStrings[i].insert(longStrings[i].length(),
longStringCopy[i]);
}
#endif
}
timeI1long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStrings[i].erase(longStringLength[i]);
ASSERT(longStringLength[i] == longStrings[i].length());
}
printf("\t I1\tInsert chars:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeI1short, timeI1long, timeI1 = timeI1short + timeI1long);
// I2) INSERT OPERATION (with reallocations, i.e., changes capacity)
double timeI2 = 0., timeI2short = 0., timeI2long = 0.;
for (int i = 0; i < NSHORT; ++i) { // restore length *and* capacity
Obj(shortWords[i]).swap(shortStringCopy[i]);
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
// ASSERT(shortStringLength[i] == shortStringCopy[i].capacity());
}
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert(shortStringCopy[i].length(),
longStrings[ilong]);
}
timeI2short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
for (int i = 0; i < NLONG; ++i) { // restore length *and* capacity
Obj(longWords[i]).swap(longStringCopy[i]);
ASSERT(longStringLength[i] == longStringCopy[i].length());
// ASSERT(longStringLength[i] == longStringCopy[i].capacity());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].insert(longStringCopy[i].length(),
longStrings[i]);
}
}
timeI2long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t I2\tInsert string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeI2short, timeI2long, timeI2 = timeI2short + timeI2long);
// }
printf("\t\tat end (without reallocation):\n");
// {
// I3) AGAIN (this time, without reallocation)
double timeI3 = 0., timeI3short = 0., timeI3long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert(shortStringCopy[i].length(),
longStrings[ilong]);
}
timeI3short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].insert(longStringCopy[i].length(),
longStrings[i]);
}
}
timeI3long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t I3\tInsert string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeI3short, timeI3long, timeI3 = timeI3short + timeI3long);
// I4) INSERT RANGE
double timeI4 = 0., timeI4short = 0., timeI4long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert(shortStringCopy[i].end(),
longStrings[ilong].begin(),
longStrings[ilong].end());
}
timeI4short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].insert(longStringCopy[i].end(),
longStrings[i].begin(),
longStrings[i].end());
}
}
timeI4long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t I4\tInsert range:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeI4short, timeI4long, timeI4 = timeI4short + timeI4long);
// }
printf("\tInsertions at beginning (with reallocations):\n");
// {
// B1) INSERT OPERATION (with reallocations, i.e., changes capacity)
double timeB1 = 0., timeB1short = 0., timeB1long = 0.;
for (int i = 0; i < NSHORT; ++i) { // restore length *and* capacity
Obj(shortWords[i]).swap(shortStrings[i]);
ASSERT(shortStringLength[i] == shortStrings[i].length());
// ASSERT(shortStringLength[i] == shortStrings[i].capacity());
}
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (size_t j = 0; j < longStringLength[ilong]; ++j) {
shortStrings[i].insert(j, 1, longStringCopy[ilong][j]);
}
#else
shortStrings[i].insert((size_t)0, longStringCopy[ilong]);
#endif
}
timeB1short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStrings[i].erase(shortStringLength[i]);
ASSERT(shortStringLength[i] == shortStrings[i].length());
}
for (int i = 0; i < NLONG; ++i) { // restore length *and* capacity
Obj(longWords[i]).swap(longStrings[i]);
ASSERT(longStringLength[i] == longStrings[i].length());
// ASSERT(longStringLength[i] == longStrings[i].capacity());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
size_t pos = 0;
#if !COMPARE_WITH_NATIVE_SUNPRO_STL
for (size_t j = 0; j < longStringLength[i]; ++j) {
for (int k = 0; k < SL_RATIO; ++k, ++pos) {
longStrings[i].insert(pos, 1, longStringCopy[i][j]);
}
}
#else
for (int k = 0; k < SL_RATIO; ++k, ++pos) {
longStrings[i].insert(pos, longStringCopy[i]);
}
#endif
}
timeB1long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStrings[i].erase(longStringLength[i]);
ASSERT(longStringLength[i] == longStrings[i].length());
}
printf("\t B1\tInsert chars:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeB1short, timeB1long, timeB1 = timeB1short + timeB1long);
// B2) INSERT OPERATION (with reallocations, i.e., changes capacity)
double timeB2 = 0., timeB2short = 0., timeB2long = 0.;
for (int i = 0; i < NSHORT; ++i) { // restore length *and* capacity
Obj(shortWords[i]).swap(shortStringCopy[i]);
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
// ASSERT(shortStringLength[i] == shortStringCopy[i].capacity());
}
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert((size_t)0, longStrings[ilong]);
}
timeB2short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStringLength[i]);
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
for (int i = 0; i < NLONG; ++i) { // restore length *and* capacity
Obj(longWords[i]).swap(longStringCopy[i]);
ASSERT(longStringLength[i] == longStringCopy[i].length());
// ASSERT(longStringLength[i] == longStringCopy[i].capacity());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
size_t pos = 0;
for (int k = 0; k < SL_RATIO; ++k, pos += longStringLength[i]) {
longStringCopy[i].insert(pos, longStrings[i]);
}
}
timeB2long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStringLength[i]);
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t B2\tInsert string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeB2short, timeB2long, timeB2 = timeB2short + timeB2long);
// }
printf("\t\t(without reallocation):\n");
// {
// B3) AGAIN (this time, without reallocation)
double timeB3 = 0., timeB3short = 0., timeB3long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert((size_t)0, longStrings[ilong]);
}
timeB3short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStringLength[i]);
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
size_t pos = 0;
for (int k = 0; k < SL_RATIO; ++k, pos += longStringLength[i]) {
longStringCopy[i].insert(pos, longStrings[i]);
}
}
timeB3long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStringLength[i]);
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t B3\tInsert string:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeB3short, timeB3long, timeB3 = timeB3short + timeB3long);
// B4) INSERT RANGE
double timeB4 = 0., timeB4short = 0., timeB4long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].insert(shortStringCopy[i].begin(),
longStrings[ilong].begin(),
longStrings[ilong].end());
}
timeB4short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
typename Obj::iterator pos = longStringCopy[i].begin();
for (int k = 0; k < SL_RATIO; ++k, pos += longStringLength[i]) {
longStringCopy[i].insert(pos,
longStrings[i].begin(),
longStrings[i].end());
}
}
timeB4long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t B4\tInsert range:"
"\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeB4short, timeB4long, timeB4 = timeB4short + timeB4long);
// }
printf("\tReplacements (without reallocation):\n");
// {
// R1) REPLACE AT END
double timeR1 = 0., timeR1short = 0., timeR1long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].replace(shortStringCopy[i].end() - 1,
shortStringCopy[i].end(),
longStrings[ilong]);
}
timeR1short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].replace(longStringCopy[i].end() - 1,
longStringCopy[i].end(),
longStrings[i]);
}
}
timeR1long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t R1\tReplace at end:\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeR1short, timeR1long, timeR1 = timeR1short + timeR1long);
// R2) REPLACE AT BEGINNING
double timeR2 = 0., timeR2short = 0., timeR2long = 0.;
t.reset(); t.start();
for (int i = 0, ilong = 0; i < NSHORT; ++i, ++ilong) {
ilong = ilong < NLONG ? ilong : ilong - NLONG;
shortStringCopy[i].replace(shortStringCopy[i].begin(),
shortStringCopy[i].begin() + 1,
longStrings[ilong]);
}
timeR2short = t.elapsedTime();
for (int i = 0; i < NSHORT; ++i) { // restore length but not capacity
shortStringCopy[i].erase(shortStrings[i].length());
ASSERT(shortStringLength[i] == shortStringCopy[i].length());
}
t.reset(); t.start();
for (int i = 0; i < NLONG; ++i) {
for (int k = 0; k < SL_RATIO; ++k) {
longStringCopy[i].replace(longStringCopy[i].begin(),
longStringCopy[i].begin() + 1,
longStrings[i]);
}
}
timeR2long = t.elapsedTime();
for (int i = 0; i < NLONG; ++i) { // restore length but not capacity
longStringCopy[i].erase(longStrings[i].length());
ASSERT(longStringLength[i] == longStringCopy[i].length());
}
printf("\t R2\tReplace at begin: %1.5fs\t%1.5fs\t%1.6fs\n",
timeR2short, timeR2long, timeR2 = timeR2short + timeR2long);
// }
printf("\tMisc.:\n");
// {
// M1) SWAP OPERATION
double timeM1 = 0., timeM1short = 0., timeM1long = 0.;
t.reset(); t.start();
for (int k = 0; k < SL_RATIO; ++k) {
for (int i = 0; i < NSHORT; ++i) {
shortStrings[i].swap(shortStrings[NSHORT - 1 - i]);
}
}
timeM1short = t.elapsedTime();
t.reset(); t.start();
for (int k = 0; k < SL_RATIO * SL_RATIO; ++k) {
for (int i = 0; i < NLONG; ++i) {
longStrings[i].swap(longStrings[NLONG - 1 - i]);
}
}
timeM1long = t.elapsedTime();
printf("\t M1\tSwap reverse:\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeM1short, timeM1long, timeM1 = timeM1short + timeM1long);
// M2) SUBSTRING (plus assignment)
double timeM2 = 0., timeM2short = 0., timeM2long = 0.;
t.reset(); t.start();
for (int k = 0; k < SL_RATIO; ++k) {
for (int i = 0; i < NSHORT; ++i) {
shortStringCopy[i] = shortStrings[i].substr(
0, shortStringLength[i]);
}
}
timeM2short = t.elapsedTime();
t.reset(); t.start();
for (int k = 0; k < SL_RATIO * SL_RATIO; ++k) {
for (int i = 0; i < NLONG; ++i) {
longStringCopy[i] = longStrings[i].substr(0,
longStringLength[i]);
}
}
timeM2long = t.elapsedTime();
printf("\t M2\tSubstring:\t%1.5fs\t%1.5fs\t%1.6fs\n",
timeM2short, timeM2long, timeM2 = timeM2short + timeM2long);
// }
// F1) FIND AND RFIND OPERATIONS
// F2) FIND_FIRST_OF AND FIND_LAST_OF OPERATIONS
// F3) FIND_FIRST_NOT_OF AND FIND_LAST_NOT_OF OPERATIONS
}
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
namespace BloombergLP {
namespace bslstl {
class StringRef {
// This 'class' provides a dummy implementation for use with the usage
// example. The interface is minimal and only supports functions needed
// for testing.
// DATA
const char *d_begin_p;
const char *d_end_p;
public:
// CREATORS
StringRef(const char *begin, const char *end)
: d_begin_p(begin)
, d_end_p(end)
{
}
// ACCESSORS
const char *begin() const { return d_begin_p; }
const char *end() const { return d_end_p; }
bool isEmpty() const { return d_begin_p == d_end_p; }
};
} // close package namespace
} // close enterprise namespace
namespace UsageExample {
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 2: 'string' as a data member
///- - - - - - - - - - - - - - - - - -
// The most common use of 'string' objects are as data members in user-defined
// classes. In this example, we will show how 'string' objects can be used as
// data members.
//
// First, we begin to define a 'class', 'Employee', that represents the data
// corresponding to an employee of a company:
//..
class Employee {
// This simply constrained (value-semantic) attribute class represents
// the information about an employee. An employee's first and last
// name are represented as 'string' objects and their employee
// identification number is represented by an 'int'. Note that the
// class invariants are identically the constraints on the individual
// attributes.
//
// This class:
//: o supports a complete set of *value-semantic* operations
//: o except for 'bslx' serialization
//: o is *exception-neutral* (agnostic)
//: o is *alias-safe*
//: o is 'const' *thread-safe*
//
// DATA
bsl::string d_firstName; // first name
bsl::string d_lastName; // last name
int d_id; // identification number
//..
// Next, we define the creators for this class:
//..
public:
// CREATORS
Employee(bslma::Allocator *basicAllocator = 0);
// Create a 'Employee' object having the (default) attribute
// values:
//..
// firstName() == ""
// lastName() == ""
// id() == 0
//..
// Optionally specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default
// allocator is used.
//
Employee(const bslstl::StringRef& firstName,
const bslstl::StringRef& lastName,
int id,
bslma::Allocator *basicAllocator = 0);
// Create a 'Employee' object having the specified 'firstName',
// 'lastName', and 'id'' attribute values. Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is
// 0, the currently installed default allocator is used.
//
Employee(const Employee& original,
bslma::Allocator *basicAllocator = 0);
// Create a 'Employee' object having the same value as the
// specified 'original' object. Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is
// 0, the currently installed default allocator is used.
//
//! ~Employee() = default;
// Destroy this object.
//..
// Notice that all constructors of the 'Employee' class are optionally provided
// an allocator that is then passed through to the 'string' data members of
// 'Employee'. This allows the user to control how memory is allocated by
// 'Employee' objects. Also note that the type of the 'firstName' and
// 'lastName' arguments of the value constructor is 'bslstl::StringRef'. The
// 'bslstl::StringRef' allows specifying a 'string' or a 'const char *' to
// represent a string value. For the sake of brevity its implementation is
// not explored here.
//
// Then, declare the remaining methods of the class:
//..
// MANIPULATORS
Employee& operator=(const Employee& rhs);
// Assign to this object the value of the specified 'rhs' object,
// and return a reference providing modifiable access to this
// object.
//
void setFirstName(const bslstl::StringRef& value);
// Set the 'firstName' attribute of this object to the specified
// 'value'.
//
void setLastName(const bslstl::StringRef& value);
// Set the 'lastName' attribute of this object to the specified
// 'value'.
//
void setId(int value);
// Set the 'id' attribute of this object to the specified 'value'.
//
// ACCESSORS
const bsl::string& firstName() const;
// Return a reference providing non-modifiable access to the
// 'firstName' attribute of this object.
//
const bsl::string& lastName() const;
// Return a reference providing non-modifiable access to the
// 'lastName' attribute of this object.
//
int id() const;
// Return the value of the 'id' attribute of this object.
};
//..
// Next, we declare the free operators for 'Employee':
//..
inline
bool operator==(const Employee& lhs, const Employee& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// value, and 'false' otherwise. Two 'Employee' objects have the same
// value if all of their corresponding values of their 'firstName',
// 'lastName', and 'id' attributes are the same.
//
inline
bool operator!=(const Employee& lhs, const Employee& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects do not have
// the same value, and 'false' otherwise. Two 'Employee' objects do
// not have the same value if any of the corresponding values of their
// 'firstName', 'lastName', or 'id' attributes are not the same.
//..
// Then, we implement the various methods of the 'Employee' class:
//..
// CREATORS
inline
Employee::Employee(bslma::Allocator *basicAllocator)
: d_firstName(basicAllocator)
, d_lastName(basicAllocator)
, d_id(0)
{
}
//
inline
Employee::Employee(const bslstl::StringRef& firstName,
const bslstl::StringRef& lastName,
int id,
bslma::Allocator *basicAllocator)
: d_firstName(firstName.begin(), firstName.end(), basicAllocator)
, d_lastName(lastName.begin(), lastName.end(), basicAllocator)
, d_id(id)
{
BSLS_ASSERT_SAFE(!firstName.isEmpty());
BSLS_ASSERT_SAFE(!lastName.isEmpty());
}
//
inline
Employee::Employee(const Employee& original,
bslma::Allocator *basicAllocator)
: d_firstName(original.d_firstName, basicAllocator)
, d_lastName(original.d_lastName, basicAllocator)
, d_id(original.d_id)
{
}
//..
// Notice that the 'basicAllocator' parameter can simply be passed as an
// argument to the constructor of 'bsl::string'.
//
// Now, we implement the remaining manipulators of the 'Employee' class:
//..
// MANIPULATORS
inline
Employee& Employee::operator=(const Employee& rhs)
{
d_firstName = rhs.d_firstName;
d_lastName = rhs.d_lastName;
d_id = rhs.d_id;
return *this;
}
//
inline
void Employee::setFirstName(const bslstl::StringRef& value)
{
BSLS_ASSERT_SAFE(!value.isEmpty());
//
d_firstName.assign(value.begin(), value.end());
}
//
inline
void Employee::setLastName(const bslstl::StringRef& value)
{
BSLS_ASSERT_SAFE(!value.isEmpty());
//
d_lastName.assign(value.begin(), value.end());
}
//
inline
void Employee::setId(int value)
{
d_id = value;
}
//
// ACCESSORS
inline
const bsl::string& Employee::firstName() const
{
return d_firstName;
}
//
inline
const bsl::string& Employee::lastName() const
{
return d_lastName;
}
//
inline
int Employee::id() const
{
return d_id;
}
//..
// Finally, we implement the free operators for 'Employee' class:
//..
inline
bool operator==(const Employee& lhs, const Employee& rhs)
{
return lhs.firstName() == rhs.firstName()
&& lhs.lastName() == rhs.lastName()
&& lhs.id() == rhs.id();
}
//
inline
bool operator!=(const Employee& lhs, const Employee& rhs)
{
return lhs.firstName() != rhs.firstName()
|| lhs.lastName() != rhs.lastName()
|| lhs.id() != rhs.id();
}
//..
//
///Example 3: A stream text replacement filter
///- - - - - - - - - - - - - - - - - - - - - -
// In this example, we will utilize the 'string' type and its associated
// utility functions to define a function that reads data from an input stream,
// replaces all occurrences of a specified text fragment with another text
// fragment, and writes the resulting text to an output stream.
//
// First, we define the signature of the function, 'replace':
//..
void replace(std::ostream& outputStream,
std::istream& inputStream,
const bsl::string& oldString,
const bsl::string& newString)
// Read data from the specified 'inputStream' and replace all
// occurrences of the text contained in the specified 'oldString' in
// the stream with the text contained in the specified 'newString'.
// Write the modified data to the specified 'outputStream'.
//..
// Then, we provide the implementation for 'replace':
//..
{
const int oldStringSize = oldString.size();
const int newStringSize = newString.size();
bsl::string line;
//
bsl::getline(inputStream, line);
//..
// Notice that we can use the 'getline' free function defined in this component
// to read a single line of data from an input stream into a 'bsl::string'.
//..
if (!inputStream) {
return; // RETURN
}
//
do {
//..
// Next, we use the 'find' function to search the contents of 'line' for
// characters matching the contents of 'oldString':
//..
bsl::string::size_type pos = line.find(oldString);
while (bsl::string::npos != pos) {
//..
// Now, we use the 'replace' method to modify the contents of 'line' matching
// 'oldString' to 'newString':
//..
line.replace(pos, oldStringSize, newString);
pos = line.find(oldString, pos + newStringSize);
//..
// Notice that we provide 'find' with the starting position from which to start
// searching.
//..
}
//..
// Finally, we write the updated contents of 'line' to the output stream:
//..
outputStream << line;
//
bsl::getline(inputStream, line);
} while (inputStream);
}
//..
} // close namespace UsageExample
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
veryVeryVeryVerbose = argc > 5;
// As part of our overall allocator testing strategy, we will create three
// test allocators.
// Object Test Allocator.
bslma::TestAllocator objectAllocator("Object Allocator",
veryVeryVeryVerbose);
objectAllocator_p = &objectAllocator;
// Default Test Allocator.
bslma::TestAllocator defaultAllocator("Default Allocator",
veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard guard(&defaultAllocator);
defaultAllocator_p = &defaultAllocator;
// Global Test Allocator.
bslma::TestAllocator globalAllocator("Global Allocator",
veryVeryVeryVerbose);
bslma::Allocator *originalGlobalAllocator =
bslma::Default::setGlobalAllocator(&globalAllocator);
globalAllocator_p = &globalAllocator;
setbuf(stdout, NULL); // Use unbuffered output
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 33: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
//: 1 The usage example provided in the component header file compiles,
//: links, and runs as shown.
//
// Plan:
//: 1 Incorporate usage example from header into test driver, remove
//: leading comment characters, and replace 'assert' with 'ASSERT'.
//: (C-1)
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) printf("\nUSAGE EXAMPLE"
"\n=============\n");
{
using namespace UsageExample;
bslma::TestAllocator defaultAllocator("defaultAllocator");
bslma::DefaultAllocatorGuard defaultGuard(&defaultAllocator);
bslma::TestAllocator objectAllocator("objectAllocator");
bslma::TestAllocator scratch("scratch");
///Example 1: Basic Syntax
///- - - - - - - - - - - -
// In this example, we will show how to create and use the 'string' typedef.
//
// First, we will default-construct a 'string' object:
//..
bsl::string s;
ASSERT(s.empty());
ASSERT(0 == s.size());
ASSERT("" == s);
//..
// Then, we will construct a 'string' object from a string literal:
//..
bsl::string t = "Hello World";
ASSERT(!t.empty());
ASSERT(11 == t.size());
ASSERT("Hello World" == t);
//..
// Next, we will clear the contents of 't' and assign it a couple of values:
// first from a string literal; and second from another 'string' object:
//..
t.clear();
ASSERT(t.empty());
ASSERT("" == t);
//
t = "Good Morning";
ASSERT(!t.empty());
ASSERT("Good Morning" == t);
//
t = s;
ASSERT(t.empty());
ASSERT("" == t);
ASSERT(t == s);
//..
// Then, we will create three 'string' objects: the first representing a street
// name, the second a state, and the third a zipcode. We will then concatenate
// them into a single address 'string' and print the contents of that 'string'
// on standard output:
//..
const bsl::string street = "731 Lexington Avenue";
const bsl::string state = "NY";
const bsl::string zipcode = "10022";
//
const bsl::string fullAddress = street + " " + state + " " + zipcode;
//
if (veryVerbose) {
dbg_print(fullAddress);
}
//..
// The above print statement should produce a single line of output:
//..
// 731 Lexington Avenue NY 10022
//..
// Then, we search the contents of 'address' (using the 'find' function) to
// determine if it lies on a specified street:
//..
const bsl::string streetName = "Lexington";
//
if (bsl::string::npos != fullAddress.find(streetName, 0)) {
if (veryVerbose) {
dbg_print("The address " + fullAddress + " is located on "
+ streetName + ".");
}
}
//..
// Next, we show how to get a reference providing modifiable access to the
// null-terminated string literal stored by a 'string' object using the 'c_str'
// function. Note that the returned string literal can be passed to various
// standard functions expecting a null-terminated string:
//..
const bsl::string v = "Another string";
const char *cs = v.c_str();
ASSERT(strlen(cs) == v.size());
//..
// Then, we construct two 'string' objects, 'x' and 'y', using a user-specified
// allocator:
//..
bslma::TestAllocator allocator1, allocator2;
//
const char *SHORT_STRING = "A small string";
const char *LONG_STRING = "This long string would definitely cause "
"memory to be allocated on creation";
//
const bsl::string x(SHORT_STRING, &allocator1);
const bsl::string y(LONG_STRING, &allocator2);
//
ASSERT(SHORT_STRING == x);
ASSERT(LONG_STRING == y);
//..
// Notice that, no memory was allocated from the allocator for object 'x'
// because of the short-string optimization used in the 'string' type.
//
// Finally, we can track memory usage of 'x' and 'y' using 'allocator1' and
// 'allocator2' and check that memory was allocated only by 'allocator2':
//..
ASSERT(0 == allocator1.numBlocksInUse());
ASSERT(1 == allocator2.numBlocksInUse());
//..
//
}
///Example 2: 'string' as a data member
///- - - - - - - - - - - - - - - - - -
{
using namespace UsageExample;
// Default ctor
Employee e1; const Employee& E1 = e1;
ASSERT("" == E1.firstName());
ASSERT("" == E1.lastName());
ASSERT(0 == E1.id());
// Value ctor
bsl::string FIRST_NAME = "Joe";
bsl::string LAST_NAME = "Smith";
bslstl::StringRef FIRST(FIRST_NAME.begin(), FIRST_NAME.end());
bslstl::StringRef LAST(LAST_NAME.begin(), LAST_NAME.end());
int ID = 1;
Employee e2(FIRST, LAST, ID); const Employee& E2 = e2;
ASSERT(FIRST_NAME == E2.firstName());
ASSERT(LAST_NAME == E2.lastName());
ASSERT(ID == E2.id());
// Equality operators
ASSERT(! (e1 == e2));
ASSERT( e1 != e2);
// Manipulators and accessors
e1.setFirstName(FIRST);
ASSERT(FIRST_NAME == e1.firstName());
e1.setLastName(LAST);
ASSERT(LAST_NAME == e1.lastName());
e1.setId(ID);
ASSERT(ID == e1.id());
ASSERT( e1 == e2);
ASSERT(! (e1 != e2));
// Copy constructor
Employee e3(e1); const Employee& E3 = e3;
(void) E3;
ASSERT( e1 == e3);
ASSERT(! (e1 != e3));
}
///Example 3: A 'string' replace function
///- - - - - - - - - - - - - - - - - - -
{
using namespace UsageExample;
static const struct {
int d_lineNum; // source line number
const char *d_old_p; // old string to replace
const char *d_new_p; // new string to replace with
const char *d_orig_p; // original result
const char *d_exp_p; // expected result
} DATA[] = {
//line old new orig exp
//---- ---- ---- ---- ----
{ L_, "a", "b", "abcdeabc", "bbcdebbc" },
{ L_, "b", "a", "abcdeabc", "aacdeaac" },
{ L_, "ab", "xy", "ababefgh", "xyxyefgh" },
{ L_, "abc", "xyz", "abcdefgh", "xyzdefgh" },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
for (int ti = 0; ti < NUM_DATA ; ++ti) {
const int LINE = DATA[ti].d_lineNum;
const string OLD = DATA[ti].d_old_p;
const string NEW = DATA[ti].d_new_p;
const string ORIG = DATA[ti].d_orig_p;
const string EXP = DATA[ti].d_exp_p;
std::istringstream is(ORIG);
std::ostringstream os;
replace(os, is, OLD, NEW);
LOOP_ASSERT(LINE, EXP == os.str());
}
}
} break;
case 32: {
// ------------------------------------------------------------------
// TESTING 'to_string' AND 'to_wstring'
//
// Testing
// string to_string(int value);
// string to_string(long value);
// string to_string(long long value);
// string to_string(unsigned value);
// string to_string(unsigned long value);
// string to_string(unsigned long long value);
// string to_string(float value);
// string to_string(double value);
// string to_string(long double value);
// string to_wstring(int value);
// string to_wstring(long value);
// string to_wstring(long long value);
// string to_wstring(unsigned value);
// string to_wstring(unsigned long value);
// string to_wstring(unsigned long long value);
// string to_wstring(float value);
// string to_wstring(double value);
// string to_wstring(long double value);
// ------------------------------------------------------------------
if (verbose) printf("\nTESTING 'to_string' AND 'to_wstring'"
"\n====================================\n");
TestDriver<char>::testCase32();
}break;
case 31: {
// --------------------------------------------------------------------
// TESTING 'stof', 'stod','stold'
//
// Testing
// float stof(const string& str, std::size_t* pos =0);
// float stof(const wstring& str, std::size_t* pos =0);
// double stod(const string& str, std::size_t* pos =0);
// double stod(const wstring& str, std::size_t* pos =0);
// long double stold(const string& str, std::size_t* pos =0);
// long double stold(const wstring& str, std::size_t* pos =0);
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'stof', 'stod','stold'"
"\n==============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase31();
}break;
case 30: {
// --------------------------------------------------------------------
// TESTING 'stoi', 'stol','stoul', 'stoll', 'stoull'
//
// Testing
// int stoi(const string& str, std::size_t* pos = 0, int base = 10);
// int stoi(const wstring& str, std::size_t* pos = 0, int base = 10);
// long stol(const string& str, std::size_t* pos = 0, int base = 10);
// long stol(const wstring& str, std::size_t* pos = 0,
// int base = 10);
// unsigned long stoul(const string& str, std::size_t* pos = 0,
// int base = 10);
// unsigned long stoul(const wstring& str, std::size_t* pos = 0,
// int base = 10);
// long long stoll(const string& str, std::size_t* pos = 0,
// int base = 10);
// long long stoll(const wstring& str, std::size_t* pos = 0,
// int base = 10);
// unsigned long long stoull(const string& str,
// std::size_t* pos = 0, int base = 10);
// unsigned long long stoull(const wstring& str,
// std::size_t* pos = 0, int base = 10);
// --------------------------------------------------------------------
if (verbose)
printf("\nTESTING 'stoi', 'stol','stoul', 'stoll', 'stoull'"
"\n=================================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase30();
}break;
case 29: {
// --------------------------------------------------------------------
// TESTING 'hashAppend'
// Verify that the hashAppend function works properly and is picked
// up by 'bslh::Hash'
//
// Concerns:
//: 1 'bslh::Hash' picks up 'hashAppend(string)' and can hash strings
//: 2 'hashAppend' hashes the entire string, regardless of 'char' or
//: 'wchar'
//
// Plan:
//: 1 Use 'bslh::Hash' to hash a few values of strings with each char
//: type. (C-1,2)
//
// Testing:
// hashAppend(HASHALG& hashAlg, const basic_string& str);
// hashAppend(HASHALG& hashAlg, const native_std::basic_string& str);
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'hashAppend'"
"\n====================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase29();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase29();
} break;
case 28: {
// --------------------------------------------------------------------
// TESTING THE SHORT STRING OPTIMIZATION
//
// Concerns:
// - String should have an initial non-zero capacity (short string
// buffer).
// - It shouldn't allocate up to that capacity.
// - It should work with the char_type larger than the short string
// buffer.
// - It should work with the NULL-terminator different from '\0' to
// make sure that the implementation always uses char_type() default
// constructor to terminate the string rather than a null literal.
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING THE SHORT STRING OPTIMIZATION"
"\n=====================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase28();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase28();
if (verbose)
printf("\n... with 'UserChar' that can be pretty large.\n");
TestDriver<UserChar<1> >::testCase28();
TestDriver<UserChar<2> >::testCase28();
TestDriver<UserChar<3> >::testCase28();
TestDriver<UserChar<4> >::testCase28();
TestDriver<UserChar<5> >::testCase28();
TestDriver<UserChar<6> >::testCase28();
TestDriver<UserChar<7> >::testCase28();
TestDriver<UserChar<8> >::testCase28();
} break;
case 27: {
// --------------------------------------------------------------------
// REPRODUCING KNOWN BUG CAUSING SEGFAULT IN FIND
//
// Concerns:
// That a known bug in string::find on Sun cc is reproduced in this
// test suite.
//
// Testing:
// This is a problem with the native library, being pursued in DRQS
// 16870796. This test will do nothing unless run in verbose mode.
// --------------------------------------------------------------------
if (verbose) printf("\nReproducing known segfault in string::find"
"\n==========================================\n");
if (verbose) {
const char *pc = std::char_traits<char>::find("bcabcd", 2, 'a');
P((const void *) pc);
ASSERT(0 == pc);
const wchar_t *pw =
std::char_traits<wchar_t>::find(L"bcabcd", 2, L'a');
P((const void *) pw);
ASSERT(0 == pw);
bsl::basic_string<wchar_t, std::char_traits<wchar_t> > s =
L"aababcabcd";
s.find(L"abcde", 0, 5); // segfaults
}
} break;
case 26: {
// --------------------------------------------------------------------
// TESTING CONVERSIONS WITH NATIVE STRINGS
//
// Testing:
// CONCERNS:
// - A bsl::basic_string is implicitly convertible to a
// native_std::basic_string with the same CHAR_TYPE and
// CHAR_TRAITS.
// - A native_std::basic_string is implicitly convertible to a
// bsl::basic_string with the same CHAR_TYPE and
// CHAR_TRAITS.
// - A bsl::basic_string and a native_std::basic_string with the
// same template parameters will have the same npos value.
// --------------------------------------------------------------------
if (verbose) printf("\nTesting conversions to/from native string"
"\n=========================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase26();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase26();
} if (test) break;
case 25: {
// --------------------------------------------------------------------
// TESTING EXCEPTIONS
//
// Testing:
// CONCERN: std::length_error is used properly
// --------------------------------------------------------------------
if (verbose) printf("\nTesting use of 'std::length_error'"
"\n=================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase25();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase25();
} if (test) break;
case 24: {
// --------------------------------------------------------------------
// TESTING COMPARISONS
//
// Testing:
// int compare(const string& str) const;
// int compare(pos1, n1, const string& str) const;
// int compare(pos1, n1, const string& str, pos2, n2) const;
// int compare(const C* s) const;
// int compare(pos1, n1, const C* s) const;
// int compare(pos1, n1, const C* s, n2) const;
// bool operator<(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator>(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator<=(const string<C,CT,A>&, const string<C,CT,A>&);
// bool operator>=(const string<C,CT,A>&, const string<C,CT,A>&);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting comparisons"
"\n===================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase24();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase24();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative testing comparisons"
"\n============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase24Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase24Negative();
#endif
} if (test) break;
case 23: {
// --------------------------------------------------------------------
// TESTING COMPARISONS
//
// Testing:
// string substr(pos, n) const;
// size_type copy(char *s, n, pos = 0) const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting substring operations"
"\n============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase23();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase23();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing 'copy'"
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase23Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase23Negative();
#endif
} if (test) break;
case 22: {
// --------------------------------------------------------------------
// TESTING FIND VARIANTS
//
// Testing:
// size_type find(const string& str, pos = 0) const;
// size_type find(const C *s, pos, n) const;
// size_type find(const C *s, pos = 0) const;
// size_type find(C c, pos = 0) const;
// size_type rfind(const string& str, pos = 0) const;
// size_type rfind(const C *s, pos, n) const;
// size_type rfind(const C *s, pos = 0) const;
// size_type rfind(C c, pos = 0) const;
// size_type find_first_of(const string& str, pos = 0) const;
// size_type find_first_of(const C *s, pos, n) const;
// size_type find_first_of(const C *s, pos = 0) const;
// size_type find_first_of(C c, pos = 0) const;
// size_type find_last_of(const string& str, pos = 0) const;
// size_type find_last_of(const C *s, pos, n) const;
// size_type find_last_of(const C *s, pos = 0) const;
// size_type find_last_of(C c, pos = 0) const;
// size_type find_first_not_of(const string& str, pos = 0) const;
// size_type find_first_not_of(const C *s, pos, n) const;
// size_type find_first_not_of(const C *s, pos = 0) const;
// size_type find_first_not_of(C c, pos = 0) const;
// size_type find_last_not_of(const string& str, pos = 0) const;
// size_type find_last_not_of(const C *s, pos, n) const;
// size_type find_last_not_of(const C *s, pos = 0) const;
// size_type find_last_not_of(C c, pos = 0) const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting 'find...' methods."
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase22();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase22();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative testing 'find...' methods."
"\n===================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase22Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase22Negative();
#endif
} if (test) break;
case 21: {
// --------------------------------------------------------------------
// TESTING SWAP
//
// Testing:
// void swap(string&);
// void swap(string<C,CT,A>& lhs, string<C,CT,A>& rhs);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting 'swap'"
"\n==============\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase21();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase21();
} if (test) break;
case 20: {
// --------------------------------------------------------------------
// TESTING REPLACE
//
// Testing:
// string& replace(pos1, n1, const string& str);
// string& replace(pos1, n1, const string& str, pos2, n2);
// string& replace(pos1, n1, const C *s, n2);
// string& replace(pos1, n1, const C *s);
// string& replace(pos1, n1, size_type n2, C c);
// replace(const_iterator p, const_iterator q, const string& str);
// replace(const_iterator p, const_iterator q, const C *s, n2);
// replace(const_iterator p, const_iterator q, const C *s);
// replace(const_iterator p, const_iterator q, size_type n2, C c);
// template <class InputIter>
// replace(const_iterator p, const_iterator q, InputIter f, l);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting 'replace' with value"
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase20();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase20();
if (verbose) printf("\nTesting 'replace' with range"
"\n==========================\n");
if (verbose) printf("\n... with 'char' "
"and arbitrary input iterator.\n");
TestDriver<char>::testCase20Range(CharList<char>());
if (verbose) printf("\n... with 'char' "
"and arbitrary random-access iterator.\n");
TestDriver<char>::testCase20Range(CharArray<char>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary input iterator.\n");
TestDriver<wchar_t>::testCase20Range(CharList<wchar_t>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary random-access iterator.\n");
TestDriver<wchar_t>::testCase20Range(CharArray<wchar_t>());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing 'replace'"
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase20Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase20Negative();
#endif
} if (test) break;
case 19: {
// --------------------------------------------------------------------
// TESTING ERASE
//
// Testing:
// iterator erase(size_type pos, n);
// iterator erase(const_iterator position);
// iterator erase(const_iterator first, iterator last);
// void pop_back();
// --------------------------------------------------------------------
if (verbose) printf("\nTesting 'erase' and 'pop_back'"
"\n==============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase19();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase19();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing for 'erase' and 'pop_back'"
"\n===========================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase19Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase19Negative();
#endif
} if (test) break;
case 18: {
// --------------------------------------------------------------------
// TESTING INSERTION
//
// Testing:
// iterator insert(const_iterator position, const T& value);
// iterator insert(const_iterator pos, size_type n, const T& val);
// template <class InputIter>
// iterator
// insert(const_iterator pos, InputIter first, InputIter last);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Value Insertion"
"\n=======================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase18();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase18();
if (verbose) printf("\nTesting Range Insertion"
"\n=======================\n");
if (verbose) printf("\n... with 'char' "
"and arbitrary input iterator.\n");
TestDriver<char>::testCase18Range(CharList<char>());
if (verbose) printf("\n... with 'char' "
"and arbitrary random-access iterator.\n");
TestDriver<char>::testCase18Range(CharArray<char>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary input iterator.\n");
TestDriver<wchar_t>::testCase18Range(CharList<wchar_t>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary random-access iterator.\n");
TestDriver<wchar_t>::testCase18Range(CharArray<wchar_t>());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Insertion"
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase18Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase18Negative();
#endif
} if (test) break;
case 17: {
// --------------------------------------------------------------------
// TESTING APPEND
//
// Testing:
// template <class InputIter>
// void append(InputIter first, InputIter last);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Value Append"
"\n====================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase17();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase17();
if (verbose) printf("\nTesting Range Append"
"\n====================\n");
if (verbose) printf("\n... with 'char' "
"and arbitrary input iterator.\n");
TestDriver<char>::testCase17Range(CharList<char>());
if (verbose) printf("\n... with 'char' "
"and arbitrary random-access iterator.\n");
TestDriver<char>::testCase17Range(CharArray<char>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary input iterator.\n");
TestDriver<wchar_t>::testCase17Range(CharList<wchar_t>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary random-access iterator.\n");
TestDriver<wchar_t>::testCase17Range(CharArray<wchar_t>());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Range Append"
"\n=============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase17Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase17Negative();
#endif
} if (test) break;
case 16: {
// --------------------------------------------------------------------
// TESTING ITERATORS
//
// Testing:
// iterator begin();
// iterator end();
// reverse_iterator rbegin();
// reverse_iterator rend();
// const_iterator begin() const;
// const_iterator end() const;
// const_reverse_iterator rbegin() const;
// const_reverse_iterator rend() const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Iterators"
"\n=================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase16();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase16();
} if (test) break;
case 15: {
// --------------------------------------------------------------------
// TESTING ELEMENT ACCESS
//
// Testing:
// T& operator[](size_type position);
// T& at(size_type n);
// T& front();
// T& back();
// const T& front() const;
// const T& back() const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Element Access"
"\n======================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase15();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase15();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Element Access"
"\n===============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase15Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase15Negative();
#endif
} if (test) break;
case 14: {
// --------------------------------------------------------------------
// TESTING CAPACITY
//
// Testing:
// void reserve(size_type n);
// void resize(size_type n, T val);
// size_type max_size() const;
// size_type capacity() const;
// bool empty() const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Reserve and Capacity"
"\n============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase14();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase14();
} if (test) break;
case 13: {
// --------------------------------------------------------------------
// TESTING ASSIGNMENT
//
// Testing:
// void assign(size_t n, const T& val);
// template<class InputIter>
// void assign(InputIter first, InputIter last);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Initial-Length Assignment"
"\n=================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase13();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase13();
if (verbose) printf("\nTesting Initial-Range Assignment"
"\n================================\n");
if (verbose) printf("\n... with 'char' "
"and arbitrary input iterator.\n");
TestDriver<char>::testCase13Range(CharList<char>());
if (verbose) printf("\n... with 'char' "
"and arbitrary random-access iterator.\n");
TestDriver<char>::testCase13Range(CharArray<char>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary input iterator.\n");
TestDriver<wchar_t>::testCase13Range(CharList<wchar_t>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary random-access iterator.\n");
TestDriver<wchar_t>::testCase13Range(CharArray<wchar_t>());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Assignment"
"\n===========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase13Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase13Negative();
#endif
} if (test) break;
case 12: {
// --------------------------------------------------------------------
// TESTING CONSTRUCTORS
//
// Testing:
// string<C,CT,A>(size_type n, const T& val = T(), a = A());
// template<class InputIter>
// string<C,CT,A>(InputIter first, InputIter last, a = A());
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Initial-Length Constructor"
"\n==================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase12();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase12();
if (verbose) printf("\nTesting Initial-Range Constructor"
"\n=================================\n");
if (verbose) printf("\n... with 'char' "
"and arbitrary input iterator.\n");
TestDriver<char>::testCase12Range(CharList<char>());
if (verbose) printf("\n... with 'char' "
"and arbitrary random-access iterator.\n");
TestDriver<char>::testCase12Range(CharArray<char>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary input iterator.\n");
TestDriver<wchar_t>::testCase12Range(CharList<wchar_t>());
if (verbose) printf("\n... with 'wchar_t' "
"and arbitrary random-access iterator.\n");
TestDriver<wchar_t>::testCase12Range(CharArray<wchar_t>());
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative testing of Constructors"
"\n================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase12Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase12Negative();
#endif
} if (test) break;
case 11: {
// --------------------------------------------------------------------
// TESTING ALLOCATOR-RELATED CONCERNS
//
// Testing:
// Allocator TRAITS
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Allocator concerns"
"\n==================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase11();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase11();
} if (test) break;
case 10: {
// --------------------------------------------------------------------
// TESTING STREAMING FUNCTIONALITY:
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Streaming Functionality"
"\n===============================\n");
if (verbose)
printf("There is no streaming for this component.\n");
} if (test) break;
case 9: {
// --------------------------------------------------------------------
// TESTING ASSIGNMENT OPERATOR:
// Now that we can generate many values for our test objects, and
// compare results of assignments, we can test the assignment
// operator. This is achieved by the 'testCase9' class method of
// the test driver template, instantiated for the basic test type.
// See that function for a list of concerns and a test plan.
//
// Testing:
// Obj& operator=(const Obj& rhs);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Assignment Operator"
"\n===========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase9();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase9();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Assignment Operator"
"\n====================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase9Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase9Negative();
#endif
} if (test) break;
case 8: {
// --------------------------------------------------------------------
// TESTING GENERATOR FUNCTION, g:
// Since 'g' is implemented almost entirely using 'gg', we need to
// verify only that the arguments are properly forwarded, that 'g'
// does not affect the test allocator, and that 'g' returns an
// object by value. Because the generator is used for various types
// in higher numbered test cases, we need to test it on all test
// types. This is achieved by the 'testCase8' class method of the
// test driver template, instantiated for the basic test type. See
// that function for a list of concerns and a test plan.
//
// Testing:
// Obj g(const char *spec);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Generator Function g"
"\n============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase8();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase8();
} if (test) break;
case 7: {
// --------------------------------------------------------------------
// TESTING COPY CONSTRUCTOR:
// Having now full confidence in 'operator==', we can use it
// to test that copy constructors preserve the notion of
// value. This is achieved by the 'testCase7' class method of the
// test driver template, instantiated for the basic test type. See
// that function for a list of concerns and a test plan.
//
// Testing:
// string(const string& original);
// string(const string& original, alloc);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Copy Constructors"
"\n=========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase7();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase7();
} if (test) break;
case 6: {
// --------------------------------------------------------------------
// TESTING EQUALITY OPERATORS:
// Since 'operators==' is implemented in terms of basic accessors,
// it is sufficient to verify only that a difference in value of any
// one basic accessor for any two given objects implies inequality.
// However, to test that no other internal state information is
// being considered, we want also to verify that 'operator==' reports
// true when applied to any two objects whose internal
// representations may be different yet still represent the same
// (logical) value. This is achieved by the 'testCase6' class
// method of the test driver template, instantiated for the basic
// test type. See that function for a list of concerns and a test
// plan.
//
// Testing:
// operator==(const Obj&, const Obj&);
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Equality Operators"
"\n==========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase6();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase6();
#ifdef BDE_BUILD_TARGET_EXC
if (verbose) printf("\nNegative Testing Equality Operators"
"\n===================================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase6Negative();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase6Negative();
#endif
} if (test) break;
case 5: {
// --------------------------------------------------------------------
// TESTING OUTPUT (<<) OPERATOR:
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Output (<<) Operator"
"\n============================\n");
if (verbose)
printf("There is no output operator for this component.\n");
} if (test) break;
case 4: {
// --------------------------------------------------------------------
// TESTING BASIC ACCESSORS:
// Having implemented an effective generation mechanism, we now would
// like to test thoroughly the basic accessor functions
// - size() const
// - operator[](int) const
// Also, we want to ensure that various internal state
// representations for a given value produce identical results. This
// is achieved by the 'testCase4' class method of the test driver
// template, instantiated for the basic test type. See that function
// for a list of concerns and a test plan.
//
// Testing:
// int size() const;
// const int& operator[](int index) const;
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Basic Accessors"
"\n=======================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase4();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase4();
} if (test) break;
case 3: {
// --------------------------------------------------------------------
// TESTING GENERATOR FUNCTIONS
// This is achieved by the 'testCase3' class method of the test
// driver template, instantiated for the basic test type. See that
// function for a list of concerns and a test plan.
//
// Testing:
// void ggg(Obj *object, const char *spec);
// Obj& gg(Obj *object, const char *spec, );
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Generator Functions"
"\n===========================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase3();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase3();
} if (test) break;
case 2: {
// --------------------------------------------------------------------
// TESTING PRIMARY MANIPULATORS (BOOTSTRAP):
// We want to ensure that the primary manipulators
// - push_back (black-box)
// - clear (white-box)
// operate as expected. This is achieved by the 'testCase2' class
// method of the test driver template, instantiated for the basic
// test type. See that function for a list of concerns and a test
// plan.
//
// Testing:
// void push_back(T const& v);
// void clear();
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Primary Manipulators"
"\n============================\n");
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCase2();
if (verbose) printf("\n... with 'wchar_t'.\n");
TestDriver<wchar_t>::testCase2();
} if (test) break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// We want to exercise basic value-semantic functionality. This is
// achieved by the 'testCase1' class method of the test driver
// template, instantiated for a few basic test types. See that
// function for a list of concerns and a test plan. In addition, we
// want to make sure that we can use any standard-compliant
// allocator, including not necessarily rebound to the same type as
// the contained element, and that various manipulators and accessors
// work as expected in normal operation.
//
// Testing:
// This "test" *exercises* basic functionality.
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
if (verbose) printf("\nStandard value-semantic test.\n");
if (verbose) printf("\n\t... with 'char' type.\n");
TestDriver<char>::testCase1();
if (verbose) printf("\n\t... with 'wchar_t' type.\n");
TestDriver<wchar_t>::testCase1();
if (verbose) printf("\nAdditional tests: allocators.\n");
bslma::TestAllocator testAllocator(veryVeryVerbose);
bsl::allocator<int> zza(&testAllocator);
bsl::basic_string<char,
bsl::char_traits<char>,
bsl::allocator<char> > zz1, zz2(zza);
if (verbose) printf("\nAdditional tests: misc.\n");
bsl::basic_string<char, bsl::char_traits<char> > myStr(5, 'a');
bsl::basic_string<char, bsl::char_traits<char> >::const_iterator citer;
ASSERT(5 == myStr.size());
for (citer = myStr.begin(); citer != myStr.end(); ++citer) {
ASSERT('a' == *citer);
}
if (verbose) P(myStr);
myStr.insert(myStr.begin(), 'z');
ASSERT(6 == myStr.size());
ASSERT('z' == myStr[0]);
for (citer = myStr.begin() + 1; citer != myStr.end(); ++citer) {
ASSERT('a' == *citer);
}
if (verbose) P(myStr);
myStr.erase(myStr.begin() + 2, myStr.begin() + 4);
ASSERT(4 == myStr.size());
ASSERT('z' == myStr[0]);
for (citer = myStr.begin() + 1; citer != myStr.end(); ++citer) {
ASSERT('a' == *citer);
}
if (verbose) P(myStr);
if (verbose) printf("\nAdditional tests: traits.\n");
ASSERT((bslmf::IsBitwiseMoveable<bsl::basic_string<char,
bsl::char_traits<char> > >::value));
ASSERT((bslmf::IsBitwiseMoveable<bsl::basic_string<wchar_t,
bsl::char_traits<wchar_t> > >::value));
if (verbose) printf("\nStreaming test.\n");
std::ostringstream ostrm;
myStr.assign("hello world");
ostrm << myStr << '\0';
ASSERT(ostrm.good());
LOOP_ASSERT(ostrm.str().c_str(),
0 == strcmp(ostrm.str().c_str(), "hello world"));
// can operator<< handle negative width?
ostrm.str("");
ostrm << std::setw(-10) << myStr;
ASSERT(ostrm.str() == myStr);
char inbuf[] = " goodbye world\n";
std::istringstream istrm(inbuf);
istrm >> myStr;
ASSERT(istrm.good());
LOOP_ASSERT(myStr.c_str(), "goodbye" == myStr);
getline(istrm, myStr);
ASSERT(! istrm.fail());
LOOP_ASSERT(myStr.c_str(), " world" == myStr);
getline(istrm, myStr);
ASSERT(istrm.fail());
myStr = "done";
getline(istrm, myStr);
LOOP_ASSERT(myStr.c_str(), "done" == myStr);
// can operator>> handle negative width?
istrm.str("setw");
istrm.clear();
istrm >> setw(-10) >> myStr;
LOOP_ASSERT(myStr.c_str(), myStr == "setw");
} break;
case -1: {
// --------------------------------------------------------------------
// PERFORMANCE TEST
// We have the following concerns:
// 1) That performance does not regress between versions.
// 2) That small "improvements" can be tested w.r.t. to performance,
// in a uniform benchmark.
//
// Plan: We follow a simple benchmark which copies strings into a
// table. We create two tables, one containing long strings, and
// another containing short strings. All strings are preallocated so
// that we do not measure the performance of the random generator.
// Specifically, we wish to measure the time taken by
// C1) The various constructors.
// C2) The copy constructor.
// A1) The copy assignment.
// A2) The 'assign' operations.
// M1) The 'append' operation in its various forms (including
// 'push_back').
// M2) The 'insert' operation in its various forms.
// M3) The 'replace' operation in its various forms.
// S1) The 'swap' operation in its various forms.
// F1) The 'find' and 'rfind' operations.
// F2) The 'find_first_of' and 'find_last_of' operations.
// F3) The 'find_first_not_of' and 'find_last_not_of' operations.
// Also we wish to record the size of the various string
// instantiations.
//
// Note: This is a *synthetic* benchmark. It does not replace
// measuring real benchmarks (e.g., for strings, ADSP) whose
// conclusions may differ due to different memory allocation and
// access patterns, function call frequencies, etc.
//
// Testing:
// This "test" measures performance of basic operations, for
// performance regression.
// --------------------------------------------------------------------
if (verbose) printf("\nTesting Performance"
"\n===================\n");
const int NITER = (argc < 3) ? 1 : atoi(argv[2]);
if (verbose)
printf("\tUsing %d repetitions of the tests (default 1).\n", NITER);
const int RANDOM_SEED = (argc < 4) ? 0x12345678 : atoi(argv[3]);
if (veryVerbose)
printf("\tUsing %d random seed (of the tests (default 1).\n", NITER);
srand(RANDOM_SEED);
if (verbose) printf("\n... with 'char'.\n");
TestDriver<char>::testCaseM1(NITER, RANDOM_SEED);
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
bslma::Default::setGlobalAllocator(originalGlobalAllocator);
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| {
"content_hash": "28f28d6a4e74f14a82d9aa288e81f374",
"timestamp": "",
"source": "github",
"line_count": 16438,
"max_line_length": 79,
"avg_line_length": 39.78914709818713,
"alnum_prop": 0.4433318961431319,
"repo_name": "idispatch/bde",
"id": "a0e6fb8b47e72ea5f5ae7b3670bc8813f0192f70",
"size": "654054",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "groups/bsl/bslstl/bslstl_string.t.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "147162"
},
{
"name": "C++",
"bytes": "80424920"
},
{
"name": "Objective-C",
"bytes": "86496"
},
{
"name": "Perl",
"bytes": "2008"
},
{
"name": "Python",
"bytes": "890"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Suggeritore_Cisco.Logic
{
class Engine
{
private const double ACCEPTABLE_MINIMUM_PRECISION_THRESHOLD = 45;
private List<QuestionAnswer> listQuestionAnswers;
private string cisco;
private struct QuestionAnswer
{
public string Question;
public string Answer;
}
public Engine(string capitolo)
{
listQuestionAnswers = new List<QuestionAnswer>();
//Read from resource
using (var st = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Suggeritore_Cisco.Resources.Cisco.xml"))
{
var bytes = new byte[st.Length];
st.Read(bytes, 0, (int)st.Length);
cisco = Encoding.UTF8.GetString(bytes);
}
var doc = new XmlDocument();
//Parse xml file.
using (var reader = XmlReader.Create(new StringReader(cisco)))
{
doc.Load(reader);
foreach (XmlNode xn in doc) //Tutti i nodi del documento
if (xn.Name == "COLLECTION") //Vede se il nodo corrisponde a "COLLECTION"
foreach (XmlNode node in xn.ChildNodes) //Legge i sottonodi del nodo "COLLECTION"
if (node.Name == "CISCO" && node.Attributes["capitolo"].Value == capitolo) //Vede se il nodo corrisponde a "CISCO" e che abbia come uguaglianza il capitolo con il parametro
foreach (XmlNode nodoRichiesta in node) //Preleva tutti i sottonodi del capitolo scelto
listQuestionAnswers.Add(new QuestionAnswer { Question = nodoRichiesta.ChildNodes[0].InnerText.Replace("\\n","\n"), Answer = nodoRichiesta.ChildNodes[1].InnerText.Replace("\\n", "\n") }); // lo aggiunge
}
listQuestionAnswers.Sort((a1, a2) => a2.Question.Length.CompareTo(a1.Question.Length));
}
public KeyValuePair<string[], double> GetRisposta(string domanda)
{
switch (domanda) //Incomplete request.
{
case "Refer to the exhibit.":
case "Refer to the exhibit":
case "Fill in the blank.":
case "Fill in the blank":
return new KeyValuePair<string[], double>(new[] { "Incomplete request", "Incomplete request" }, 100);
}
var correspondence = new List<KeyValuePair<QuestionAnswer, double>>(listQuestionAnswers.Count);
Parallel.ForEach(listQuestionAnswers, (dr) => //Multithreaded as comparing char per char is cpu heavy.
{
var computedPercentage = ComputePercentage(domanda, dr.Question);
if (computedPercentage >= ACCEPTABLE_MINIMUM_PRECISION_THRESHOLD) //Add to the list if the correspondence percentage between 2 strings is equal or more to ACCEPTABLE_MINIMUM_PRECISION_THRESHOLD value.
correspondence.Add(new KeyValuePair<QuestionAnswer, double>(dr, computedPercentage)); //Then add it.
});
correspondence.Sort((a1, a2) => a2.Value.CompareTo(a1.Value)); //order by percent
if (correspondence.Count == 0) return new KeyValuePair<string[], double>(null, 0); //If 0 means no corresponding question was found.
var percentage = correspondence[0].Value;
return new KeyValuePair<string[], double>(new[] {correspondence[0].Key.Question, correspondence[0].Key.Answer}, percentage); //return a new KeyValyePair containing the corresponding question and answer.
}
private static double ComputePercentage(string str1, string str2)
{
var str2Lng = str2.Length;
var distance = str1.DamerauLevenshteinDistanceTo(str2);
var distanceDifference = str2Lng - distance;
return (str2Lng - (str2Lng - distanceDifference)) / (double)str2Lng * 100;
}
}
} | {
"content_hash": "2caca78ca27bef31fe871f2e062bf7a9",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 237,
"avg_line_length": 47.252873563218394,
"alnum_prop": 0.6129895402578448,
"repo_name": "ADeltaX/Suggeritore-Cisco",
"id": "29e2069fd4fa2918f7ed39dc24e7416031e21aee",
"size": "4113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Suggeritore Cisco/Logic/Executer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "40933"
}
],
"symlink_target": ""
} |
Cupcake Bridge helps users makes bridges automagically!
Get the Cupcake browser extension for [Chrome](https://chrome.google.com/webstore/detail/cupcake/dajjbehmbnbppjkcnpdkaniapgdppdnc) and [Firefox](https://addons.mozilla.org/en-us/firefox/addon/cupcakebridge/)
### Releases
* Chrome - [download on google](https://chrome.google.com/webstore/detail/cupcake/dajjbehmbnbppjkcnpdkaniapgdppdnc)
* Firefox - [download from Mozilla](https://addons.mozilla.org/en-us/firefox/addon/cupcakebridge/) (Special thanks to [Uzair Farooq](uzairfarooq11@gmail.com) for creating the original Firefox port of Cupcake.
* Opera 26 (works on v15+)
* Wordpress
* Facebook App (html5/css3/javascript)
* Flex shim
* Drupal 7+ module
### Security
In 2015, a full security audit of both Cupcake and Flashproxy was conducted by Cure53. Both projects passed the audit with compliments. The full report is [available here](https://github.com/glamrock/cupcake/blob/master/security/audit1.pdf).
### What even is Cupcake?
Cupcake uses something called Flashproxy to create special Tor pathways that are harder to block. As with all circumvention projects, there's a *lot* more to it than that, but that is the jist. Flashproxy was created by David Fifield, and there is a lot of ongoing research in this area. You can learn more at the <a href="http://crypto.stanford.edu/flashproxy">Stanford Flashproxy site</a>. Cupcake exists as an easy way to distribute Flashproxy, with the goal of getting as many people to become bridges as possible.
Cupcake can be distributed in two ways:
* As a chrome or firefox add-on (turning your computer in to a less temporary proxy)
* As a module/theme/app on popular web platforms (turning every visitor to your site in to a temporary proxy)
### What the frak is a Flashproxy?
There is this thing called a Flash Proxy[[1](https://crypto.stanford.edu/flashproxy/)] - basically a code snippet that you run on sites and visitors become tor bridges temporarily.
I kind of love/hate the idea, because visitors aren't willing participants and the bridges last a short short while. But it means that you don't have to run the whole Tor shebang if you only want to make bridges. It's really innovative, and uses technology that the majority of computer owners have enabled (JavaScript).
So, what I decided to do is take that same client-side code snippets and turn it into a browser extension. People install it and they opt-in to become really robust bridges. It was a total experiment, but it went so well that I decided to expand the project.
### But... why bother with flash proxies?
*"The purpose of this project is to create many ephemeral bridge IP
addresses, with the goal of outpacing a censor's ability to block them.
Rather than increasing the number of bridges at static addresses, we aim
to make existing bridges reachable by a larger and changing pool of
addresses."* [[2](https://gitweb.torproject.org/flashproxy.git/blob/HEAD:/README)]
### Oh. Well okay then. Carry on.
[I knew you'd come around!](https://www.youtube.com/watch?v=HrlSkcHQnwI)
### How to help
The easiest way to help the project is by installing one of the browser extensions. It's not resource intensive at *all* -- flashproxy uses about as much bandwidth in a day as a 5-minute YouTube video (around 6mb).
* Translation - [Help Out!](https://www.transifex.com/projects/p/cupcake/)
### High-priority tasks that are difficult to fix
* Enabling wordpress.COM users to add flashproxy to their theme. (Can you help with this? Send me an email! griffin @ cryptolab.net )
### Low-priority tasks that demand a lot of time
* Joomla Extension
* Flash/SWF App Shim (actionscript & html)
### Failed experiments
* /img-embed
### Surprisingly-sucessful experiments
* Tumblr post demo [post](http://newhopegriffin.tumblr.com/post/47018950850/le-demo)
* Tumblr theme demo
* Facebook App (html5/css3/javascript)
### Code notes
#### chrome/manifest.json
- *incognito:split* This is useful during testing, so that incognito won't use cookies from standard browsing mode.
- *incognito:spanning* When deployed, prevents incognito windows from creating additional Cupcake processes. Proxy will continue even if all the browser windows are in incognito mode.
- *permissions:background* is used so that the extension will notify of updates and display the post-installation page. Also used so that Cupcake will start/run on startup, before the browser is started (Windows only).
- *permissions:cookies* allows reading/writing of cookies, but may not be necessary, since Cupcake doesn't currently use the Cookies API.
#### Financials
Much of the Cupcake Bridge projects are self-funded by @glamrock, but the Chrome and Firefox extensions were covered under a generous grant from the [Open Tech Fund](https://www.opentech.fund/project/cupcake-bridge) from 2013-2014.
### License
My software is free to use, free to give to friends, & open-source, so everyone can make sure it's safe for people to use. Want to make changes? Go for it! :dog: Cupcake uses the Revised BSD license -- see license.txt for more legal info.
#### Cute dog

### References
[1] https://crypto.stanford.edu/flashproxy/
[2] https://gitweb.torproject.org/flashproxy.git/blob/HEAD:/README
[3] https://gitweb.torproject.org/flashproxy.git/tree/proxy
| {
"content_hash": "4f3a66b764e30d4e0e1f094943e924aa",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 520,
"avg_line_length": 68.10126582278481,
"alnum_prop": 0.7726765799256505,
"repo_name": "glamrock/cupcake",
"id": "845e8c506e6f8b20d2fcabaf7bafbbcd9df257e1",
"size": "5489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v1_readme.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "16418"
},
{
"name": "HTML",
"bytes": "16252"
},
{
"name": "JavaScript",
"bytes": "278137"
},
{
"name": "PHP",
"bytes": "32847"
}
],
"symlink_target": ""
} |
package com.pineone.icbms.sda.comm.sch.dto;
/**
* 스케줄러용 DTO
*/
public class SchDTO {
private String task_group_id;
private String task_id;
private String task_class;
private String task_expression;
private String last_work_time;
private String use_yn;
private String cuser;
private String cdate;
private String uuser;
private String udate;
public SchDTO() {
super();
}
public String getTask_group_id() {
return task_group_id;
}
public void setTask_group_id(String task_group_id) {
this.task_group_id = task_group_id;
}
public String getTask_id() {
return task_id;
}
public void setTask_id(String task_id) {
this.task_id = task_id;
}
public String getTask_class() {
return task_class;
}
public void setTask_class(String task_class) {
this.task_class = task_class;
}
public String getTask_expression() {
return task_expression;
}
public void setTask_expression(String task_expression) {
this.task_expression = task_expression;
}
public String getLast_work_time() {
return last_work_time;
}
public void setLast_work_time(String last_work_time) {
this.last_work_time = last_work_time;
}
public String getUse_yn() {
return use_yn;
}
public void setUse_yn(String use_yn) {
this.use_yn = use_yn;
}
public String getCuser() {
return cuser;
}
public void setCuser(String cuser) {
this.cuser = cuser;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getUuser() {
return uuser;
}
public void setUuser(String uuser) {
this.uuser = uuser;
}
public String getUdate() {
return udate;
}
public void setUdate(String udate) {
this.udate = udate;
}
@Override
public String toString() {
return "SchDTO [task_group_id=" + task_group_id + ", task_id=" + task_id + ", task_class=" + task_class
+ ", task_expression=" + task_expression + ", last_work_time=" + last_work_time + ", use_yn=" + use_yn
+ ", cuser=" + cuser + ", cdate=" + cdate + ", uuser=" + uuser + ", udate=" + udate + "]";
}
}
| {
"content_hash": "9df1b70682d72ad996af05f0c54f58e4",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 106,
"avg_line_length": 19.89090909090909,
"alnum_prop": 0.6307129798903108,
"repo_name": "iotoasis/SDA",
"id": "0d7dfe67e796a8a602e48cb6a86c9f8db27a2a60",
"size": "2198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sda-common/src/main/java/com/pineone/icbms/sda/comm/sch/dto/SchDTO.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "1092562"
}
],
"symlink_target": ""
} |
package zhy.com.highlight.position;
import android.graphics.RectF;
import zhy.com.highlight.HighLight;
/**
* Created by caizepeng on 16/8/20.
*/
public class OnTopPosCallback extends OnBaseCallback {
public OnTopPosCallback() {
}
public OnTopPosCallback(float offset) {
super(offset);
}
@Override
public void getPosition(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {
marginInfo.leftMargin = rectF.right - rectF.width() / 2;
marginInfo.bottomMargin = bottomMargin+rectF.height()+offset;
}
}
| {
"content_hash": "9de9ee3ee6a2e08a8ff5f7e055e6e4a1",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 114,
"avg_line_length": 25.652173913043477,
"alnum_prop": 0.7084745762711865,
"repo_name": "isanwenyu/Highlight",
"id": "c92eb4ec9904ba10f81739148e0eac47cd933656",
"size": "590",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "highlight/src/main/java/zhy/com/highlight/position/OnTopPosCallback.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "56749"
}
],
"symlink_target": ""
} |
'use strict';
System.register(['aurelia-templating', 'aurelia-dependency-injection', 'aurelia-framework', '../common/attributeManager', '../common/attributes', '../element/element'], function (_export, _context) {
"use strict";
var bindable, customElement, noView, inject, computedFrom, AttributeManager, getBooleanFromAttributeValue, Ui5Element, _createClass, _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, Ui5gridTableRowSetting;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
return {
setters: [function (_aureliaTemplating) {
bindable = _aureliaTemplating.bindable;
customElement = _aureliaTemplating.customElement;
noView = _aureliaTemplating.noView;
}, function (_aureliaDependencyInjection) {
inject = _aureliaDependencyInjection.inject;
}, function (_aureliaFramework) {
computedFrom = _aureliaFramework.computedFrom;
}, function (_commonAttributeManager) {
AttributeManager = _commonAttributeManager.AttributeManager;
}, function (_commonAttributes) {
getBooleanFromAttributeValue = _commonAttributes.getBooleanFromAttributeValue;
}, function (_elementElement) {
Ui5Element = _elementElement.Ui5Element;
}],
execute: function () {
_createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
_export('Ui5gridTableRowSetting', Ui5gridTableRowSetting = (_dec = customElement('ui5-grid-table-row-setting'), _dec2 = inject(Element), _dec3 = bindable(), _dec4 = bindable(), _dec5 = bindable(), _dec6 = bindable(), _dec7 = bindable(), _dec8 = bindable(), _dec9 = bindable(), _dec10 = bindable(), _dec11 = computedFrom('_gridtablerowsetting'), _dec(_class = _dec2(_class = (_class2 = function (_Ui5Element) {
_inherits(Ui5gridTableRowSetting, _Ui5Element);
function Ui5gridTableRowSetting(element) {
_classCallCheck(this, Ui5gridTableRowSetting);
var _this = _possibleConstructorReturn(this, _Ui5Element.call(this, element));
_this._gridtablerowsetting = null;
_this._parent = null;
_this._relation = null;
_initDefineProp(_this, 'ui5Id', _descriptor, _this);
_initDefineProp(_this, 'ui5Class', _descriptor2, _this);
_initDefineProp(_this, 'ui5Tooltip', _descriptor3, _this);
_initDefineProp(_this, 'prevId', _descriptor4, _this);
_initDefineProp(_this, 'highlight', _descriptor5, _this);
_initDefineProp(_this, 'highlightText', _descriptor6, _this);
_initDefineProp(_this, 'navigated', _descriptor7, _this);
_initDefineProp(_this, 'validationSuccess', _descriptor8, _this);
_initDefineProp(_this, 'validationError', _descriptor9, _this);
_initDefineProp(_this, 'parseError', _descriptor10, _this);
_initDefineProp(_this, 'formatError', _descriptor11, _this);
_initDefineProp(_this, 'modelContextChange', _descriptor12, _this);
_this.element = element;
_this.attributeManager = new AttributeManager(_this.element);
return _this;
}
Ui5gridTableRowSetting.prototype.fillProperties = function fillProperties(params) {
params.highlight = this.highlight;
params.highlightText = this.highlightText;
params.navigated = getBooleanFromAttributeValue(this.navigated);
_Ui5Element.prototype.fillProperties.call(this, params);
};
Ui5gridTableRowSetting.prototype.defaultFunc = function defaultFunc() {};
Ui5gridTableRowSetting.prototype.attached = function attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id) this._gridtablerowsetting = new sap.ui.table.RowSettings(this.ui5Id, params);else this._gridtablerowsetting = new sap.ui.table.RowSettings(params);
if (this.ui5Class) this._gridtablerowsetting.addStyleClass(this.ui5Class);
if (this.ui5Tooltip) this._gridtablerowsetting.setTooltip(this.ui5Tooltip);
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || this._parent.UIElement.sId != this._gridtablerowsetting.sId) {
var prevSibling = null;
this._relation = this._parent.addChild(this._gridtablerowsetting, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
} else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._gridtablerowsetting, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
}
} else {
if (this._gridtablerowsetting.placeAt) this._gridtablerowsetting.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({ "ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
this.attributeManager.addAttributes({ "ui5-id": this._gridtablerowsetting.sId });
};
Ui5gridTableRowSetting.prototype.detached = function detached() {
try {
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if (this._gridtablerowsetting) this._parent.removeChildByRelation(this._gridtablerowsetting, this._relation);
}
} else {
this._gridtablerowsetting.destroy();
}
_Ui5Element.prototype.detached.call(this);
} catch (err) {}
};
Ui5gridTableRowSetting.prototype.addChild = function addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (var _iterator = path, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
elem = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
elem = _i.value;
}
try {
if (elem.localName == 'tooltip') {
this._gridtablerowsetting.setTooltip(child);return elem.localName;
}
if (elem.localName == 'customdata') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerowsetting.insertCustomData(child, _index);else this._gridtablerowsetting.addCustomData(child, 0);return elem.localName;
}
if (elem.localName == 'layoutdata') {
this._gridtablerowsetting.setLayoutData(child);return elem.localName;
}
if (elem.localName == 'dependents') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerowsetting.insertDependent(child, _index);else this._gridtablerowsetting.addDependent(child, 0);return elem.localName;
}
if (elem.localName == 'dragdropconfig') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerowsetting.insertDragDropConfig(child, _index);else this._gridtablerowsetting.addDragDropConfig(child, 0);return elem.localName;
}
} catch (err) {}
}
};
Ui5gridTableRowSetting.prototype.removeChildByRelation = function removeChildByRelation(child, relation) {
try {
if (relation == 'tooltip') {
this._gridtablerowsetting.destroyTooltip(child);
}
if (relation == 'customdata') {
this._gridtablerowsetting.removeCustomData(child);
}
if (relation == 'layoutdata') {
this._gridtablerowsetting.destroyLayoutData(child);
}
if (relation == 'dependents') {
this._gridtablerowsetting.removeDependent(child);
}
if (relation == 'dragdropconfig') {
this._gridtablerowsetting.removeDragDropConfig(child);
}
} catch (err) {}
};
Ui5gridTableRowSetting.prototype.highlightChanged = function highlightChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.setHighlight(newValue);
}
};
Ui5gridTableRowSetting.prototype.highlightTextChanged = function highlightTextChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.setHighlightText(newValue);
}
};
Ui5gridTableRowSetting.prototype.navigatedChanged = function navigatedChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.setNavigated(getBooleanFromAttributeValue(newValue));
}
};
Ui5gridTableRowSetting.prototype.validationSuccessChanged = function validationSuccessChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.attachValidationSuccess(newValue);
}
};
Ui5gridTableRowSetting.prototype.validationErrorChanged = function validationErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.attachValidationError(newValue);
}
};
Ui5gridTableRowSetting.prototype.parseErrorChanged = function parseErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.attachParseError(newValue);
}
};
Ui5gridTableRowSetting.prototype.formatErrorChanged = function formatErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.attachFormatError(newValue);
}
};
Ui5gridTableRowSetting.prototype.modelContextChangeChanged = function modelContextChangeChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerowsetting !== null) {
this._gridtablerowsetting.attachModelContextChange(newValue);
}
};
_createClass(Ui5gridTableRowSetting, [{
key: 'UIElement',
get: function get() {
return this._gridtablerowsetting;
}
}]);
return Ui5gridTableRowSetting;
}(Ui5Element), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'ui5Id', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Class', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Tooltip', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'prevId', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, 'highlight', [_dec3], {
enumerable: true,
initializer: function initializer() {
return 'None';
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, 'highlightText', [_dec4], {
enumerable: true,
initializer: function initializer() {
return '';
}
}), _descriptor7 = _applyDecoratedDescriptor(_class2.prototype, 'navigated', [_dec5], {
enumerable: true,
initializer: function initializer() {
return false;
}
}), _descriptor8 = _applyDecoratedDescriptor(_class2.prototype, 'validationSuccess', [_dec6], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor9 = _applyDecoratedDescriptor(_class2.prototype, 'validationError', [_dec7], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor10 = _applyDecoratedDescriptor(_class2.prototype, 'parseError', [_dec8], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor11 = _applyDecoratedDescriptor(_class2.prototype, 'formatError', [_dec9], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor12 = _applyDecoratedDescriptor(_class2.prototype, 'modelContextChange', [_dec10], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _applyDecoratedDescriptor(_class2.prototype, 'UIElement', [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, 'UIElement'), _class2.prototype)), _class2)) || _class) || _class));
_export('Ui5gridTableRowSetting', Ui5gridTableRowSetting);
}
};
}); | {
"content_hash": "32e7e883adb82b0958361d4eb6400ef0",
"timestamp": "",
"source": "github",
"line_count": 384,
"max_line_length": 440,
"avg_line_length": 51.736979166666664,
"alnum_prop": 0.5397896008456234,
"repo_name": "Hochfrequenz/aurelia-openui5-bridge",
"id": "11cf616d7cd1a55a0d8648a4544da5e432bf7064",
"size": "19867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/system/grid-table-row-setting/grid-table-row-setting.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "59606"
},
{
"name": "JavaScript",
"bytes": "1265604"
}
],
"symlink_target": ""
} |
package eu.bcvsolutions.idm.acc.dto;
import java.util.UUID;
import org.springframework.hateoas.core.Relation;
import eu.bcvsolutions.idm.core.api.domain.Embedded;
import eu.bcvsolutions.idm.core.api.dto.AbstractDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleCatalogueDto;
/*
* Role catalogue relation on account (DTO)
*
*/
@Relation(collectionRelation = "roleCatalogueAccounts")
public class AccRoleCatalogueAccountDto extends AbstractDto implements EntityAccountDto {
private static final long serialVersionUID = 1L;
@Embedded(dtoClass = AccAccountDto.class)
private UUID account;
@Embedded(dtoClass = IdmRoleCatalogueDto.class)
private UUID roleCatalogue;
private boolean ownership = true;
public UUID getAccount() {
return account;
}
public void setAccount(UUID account) {
this.account = account;
}
public boolean isOwnership() {
return ownership;
}
public void setOwnership(boolean ownership) {
this.ownership = ownership;
}
public UUID getRoleCatalogue() {
return roleCatalogue;
}
public void setRoleCatalogue(UUID roleCatalogue) {
this.roleCatalogue = roleCatalogue;
}
@Override
public UUID getEntity() {
return this.roleCatalogue;
}
@Override
public void setEntity(UUID entity) {
this.roleCatalogue = entity;
}
}
| {
"content_hash": "4cdb85d016d5d1af0393a04a3255f5ba",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 89,
"avg_line_length": 21.4,
"alnum_prop": 0.7663551401869159,
"repo_name": "bcvsolutions/CzechIdMng",
"id": "d3efc87b0330b3d3a5914f9f994a37e396a49934",
"size": "1284",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/dto/AccRoleCatalogueAccountDto.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20553"
},
{
"name": "HTML",
"bytes": "1826"
},
{
"name": "Java",
"bytes": "17776464"
},
{
"name": "JavaScript",
"bytes": "4985617"
},
{
"name": "Less",
"bytes": "56975"
},
{
"name": "Shell",
"bytes": "2793"
},
{
"name": "TSQL",
"bytes": "114398"
}
],
"symlink_target": ""
} |
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports !== "undefined") {
factory();
} else {
var mod = {
exports: {}
};
factory();
global.bootstrapTableFilterControl = mod.exports;
}
})(this, function () {
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
var _get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* @author: Dennis Hernández
* @webSite: http://djhvscf.github.io/Blog
* @version: v2.2.0
*/
(function ($) {
var Utils = $.fn.bootstrapTable.utils;
var UtilsFilterControl = {
getOptionsFromSelectControl: function getOptionsFromSelectControl(selectControl) {
return selectControl.get(selectControl.length - 1).options;
},
hideUnusedSelectOptions: function hideUnusedSelectOptions(selectControl, uniqueValues) {
var options = UtilsFilterControl.getOptionsFromSelectControl(selectControl);
for (var i = 0; i < options.length; i++) {
if (options[i].value !== '') {
if (!uniqueValues.hasOwnProperty(options[i].value)) {
selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).hide();
} else {
selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).show();
}
}
}
},
addOptionToSelectControl: function addOptionToSelectControl(selectControl, _value, text) {
var value = $.trim(_value);
var $selectControl = $(selectControl.get(selectControl.length - 1));
if (!UtilsFilterControl.existOptionInSelectControl(selectControl, value)) {
$selectControl.append($('<option></option>').attr('value', value).text($('<div />').html(text).text()));
}
},
sortSelectControl: function sortSelectControl(selectControl) {
var $selectControl = $(selectControl.get(selectControl.length - 1));
var $opts = $selectControl.find('option:gt(0)');
$opts.sort(function (a, b) {
var aa = $(a).text().toLowerCase();
var bb = $(b).text().toLowerCase();
if ($.isNumeric(a) && $.isNumeric(b)) {
// Convert numerical values from string to float.
aa = parseFloat(aa);
bb = parseFloat(bb);
}
return aa > bb ? 1 : aa < bb ? -1 : 0;
});
$selectControl.find('option:gt(0)').remove();
$selectControl.append($opts);
},
existOptionInSelectControl: function existOptionInSelectControl(selectControl, value) {
var options = UtilsFilterControl.getOptionsFromSelectControl(selectControl);
for (var i = 0; i < options.length; i++) {
if (options[i].value === value.toString()) {
// The value is not valid to add
return true;
}
}
// If we get here, the value is valid to add
return false;
},
fixHeaderCSS: function fixHeaderCSS(_ref) {
var $tableHeader = _ref.$tableHeader;
$tableHeader.css('height', '77px');
},
getCurrentHeader: function getCurrentHeader(_ref2) {
var $header = _ref2.$header,
options = _ref2.options,
$tableHeader = _ref2.$tableHeader;
var header = $header;
if (options.height) {
header = $tableHeader;
}
return header;
},
getCurrentSearchControls: function getCurrentSearchControls(_ref3) {
var options = _ref3.options;
var searchControls = 'select, input';
if (options.height) {
searchControls = 'table select, table input';
}
return searchControls;
},
getCursorPosition: function getCursorPosition(el) {
if (Utils.isIEBrowser()) {
if ($(el).is('input[type=text]')) {
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
return -1;
}
return -1;
},
setCursorPosition: function setCursorPosition(el) {
$(el).val(el.value);
},
copyValues: function copyValues(that) {
var header = UtilsFilterControl.getCurrentHeader(that);
var searchControls = UtilsFilterControl.getCurrentSearchControls(that);
that.options.valuesFilterControl = [];
header.find(searchControls).each(function () {
that.options.valuesFilterControl.push({
field: $(this).closest('[data-field]').data('field'),
value: $(this).val(),
position: UtilsFilterControl.getCursorPosition($(this).get(0)),
hasFocus: $(this).is(':focus')
});
});
},
setValues: function setValues(that) {
var field = null;
var result = [];
var header = UtilsFilterControl.getCurrentHeader(that);
var searchControls = UtilsFilterControl.getCurrentSearchControls(that);
if (that.options.valuesFilterControl.length > 0) {
// Callback to apply after settings fields values
var fieldToFocusCallback = null;
header.find(searchControls).each(function (index, ele) {
field = $(this).closest('[data-field]').data('field');
result = $.grep(that.options.valuesFilterControl, function (valueObj) {
return valueObj.field === field;
});
if (result.length > 0) {
$(this).val(result[0].value);
if (result[0].hasFocus) {
// set callback if the field had the focus.
fieldToFocusCallback = function (fieldToFocus, carretPosition) {
// Closure here to capture the field and cursor position
var closedCallback = function closedCallback() {
fieldToFocus.focus();
UtilsFilterControl.setCursorPosition(fieldToFocus, carretPosition);
};
return closedCallback;
}($(this).get(0), result[0].position);
}
}
});
// Callback call.
if (fieldToFocusCallback !== null) {
fieldToFocusCallback();
}
}
},
collectBootstrapCookies: function collectBootstrapCookies() {
var cookies = [];
var foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g);
if (foundCookies) {
$.each(foundCookies, function (i, _cookie) {
var cookie = _cookie;
if (/./.test(cookie)) {
cookie = cookie.split('.').pop();
}
if ($.inArray(cookie, cookies) === -1) {
cookies.push(cookie);
}
});
return cookies;
}
},
escapeID: function escapeID(id) {
return String(id).replace(/(:|\.|\[|\]|,)/g, '\\$1');
},
isColumnSearchableViaSelect: function isColumnSearchableViaSelect(_ref4) {
var filterControl = _ref4.filterControl,
searchable = _ref4.searchable;
return filterControl && filterControl.toLowerCase() === 'select' && searchable;
},
isFilterDataNotGiven: function isFilterDataNotGiven(_ref5) {
var filterData = _ref5.filterData;
return filterData === undefined || filterData.toLowerCase() === 'column';
},
hasSelectControlElement: function hasSelectControlElement(selectControl) {
return selectControl && selectControl.length > 0;
},
initFilterSelectControls: function initFilterSelectControls(that) {
var data = that.data;
var itemsPerPage = that.pageTo < that.options.data.length ? that.options.data.length : that.pageTo;
var z = that.options.pagination ? that.options.sidePagination === 'server' ? that.pageTo : that.options.totalRows : that.pageTo;
$.each(that.header.fields, function (j, field) {
var column = that.columns[that.fieldsColumnsIndex[field]];
var selectControl = $('.bootstrap-table-filter-control-' + UtilsFilterControl.escapeID(column.field));
if (UtilsFilterControl.isColumnSearchableViaSelect(column) && UtilsFilterControl.isFilterDataNotGiven(column) && UtilsFilterControl.hasSelectControlElement(selectControl)) {
if (selectControl.get(selectControl.length - 1).options.length === 0) {
// Added the default option
UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder);
}
var uniqueValues = {};
for (var i = 0; i < z; i++) {
// Added a new value
var fieldValue = data[i][field];
var formattedValue = Utils.calculateObjectValue(that.header, that.header.formatters[j], [fieldValue, data[i], i], fieldValue);
uniqueValues[formattedValue] = fieldValue;
}
// eslint-disable-next-line guard-for-in
for (var key in uniqueValues) {
UtilsFilterControl.addOptionToSelectControl(selectControl, uniqueValues[key], key);
}
UtilsFilterControl.sortSelectControl(selectControl);
if (that.options.hideUnusedSelectOptions) {
UtilsFilterControl.hideUnusedSelectOptions(selectControl, uniqueValues);
}
}
});
that.trigger('created-controls');
},
getFilterDataMethod: function getFilterDataMethod(objFilterDataMethod, searchTerm) {
var keys = Object.keys(objFilterDataMethod);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === searchTerm) {
return objFilterDataMethod[searchTerm];
}
}
return null;
},
createControls: function createControls(that, header) {
var addedFilterControl = false;
var isVisible = void 0;
var html = void 0;
$.each(that.columns, function (i, column) {
isVisible = 'hidden';
html = [];
if (!column.visible) {
return;
}
if (!column.filterControl) {
html.push('<div class="no-filter-control"></div>');
} else {
html.push('<div class="filter-control">');
var nameControl = column.filterControl.toLowerCase();
if (column.searchable && that.options.filterTemplate[nameControl]) {
addedFilterControl = true;
isVisible = 'visible';
html.push(that.options.filterTemplate[nameControl](that, column.field, isVisible, column.filterControlPlaceholder ? column.filterControlPlaceholder : '', 'filter-control-' + i));
}
}
$.each(header.children().children(), function (i, tr) {
var $tr = $(tr);
if ($tr.data('field') === column.field) {
$tr.find('.fht-cell').append(html.join(''));
return false;
}
});
if (column.filterData !== undefined && column.filterData.toLowerCase() !== 'column') {
var filterDataType = UtilsFilterControl.getFilterDataMethod(
/* eslint-disable no-use-before-define */
filterDataMethods, column.filterData.substring(0, column.filterData.indexOf(':')));
var filterDataSource = void 0;
var selectControl = void 0;
if (filterDataType !== null) {
filterDataSource = column.filterData.substring(column.filterData.indexOf(':') + 1, column.filterData.length);
selectControl = $('.bootstrap-table-filter-control-' + UtilsFilterControl.escapeID(column.field));
UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder);
filterDataType(filterDataSource, selectControl);
} else {
throw new SyntaxError('Error. You should use any of these allowed filter data methods: var, json, url.' + ' Use like this: var: {key: "value"}');
}
var variableValues = void 0;
var key = void 0;
// eslint-disable-next-line default-case
switch (filterDataType) {
case 'url':
$.ajax({
url: filterDataSource,
dataType: 'json',
success: function success(data) {
// eslint-disable-next-line guard-for-in
for (var _key in data) {
UtilsFilterControl.addOptionToSelectControl(selectControl, _key, data[_key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
}
});
break;
case 'var':
variableValues = window[filterDataSource];
// eslint-disable-next-line guard-for-in
for (key in variableValues) {
UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
break;
case 'jso':
variableValues = JSON.parse(filterDataSource);
// eslint-disable-next-line guard-for-in
for (key in variableValues) {
UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
break;
}
}
});
if (addedFilterControl) {
header.off('keyup', 'input').on('keyup', 'input', function (event, obj) {
// Simulate enter key action from clear button
event.keyCode = obj ? obj.keyCode : event.keyCode;
if (that.options.searchOnEnterKey && event.keyCode !== 13) {
return;
}
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
var $currentTarget = $(event.currentTarget);
if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
return;
}
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
});
header.off('change', 'select').on('change', 'select', function (event) {
if (that.options.searchOnEnterKey && event.keyCode !== 13) {
return;
}
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
});
header.off('mouseup', 'input').on('mouseup', 'input', function (event) {
var $input = $(this);
var oldValue = $input.val();
if (oldValue === '') {
return;
}
setTimeout(function () {
var newValue = $input.val();
if (newValue === '') {
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
}
}, 1);
});
if (header.find('.date-filter-control').length > 0) {
$.each(that.columns, function (i, _ref6) {
var filterControl = _ref6.filterControl,
field = _ref6.field,
filterDatepickerOptions = _ref6.filterDatepickerOptions;
if (filterControl !== undefined && filterControl.toLowerCase() === 'datepicker') {
header.find('.date-filter-control.bootstrap-table-filter-control-' + field).datepicker(filterDatepickerOptions).on('changeDate', function (_ref7) {
var currentTarget = _ref7.currentTarget;
$(currentTarget).val(currentTarget.value);
// Fired the keyup event
$(currentTarget).keyup();
});
}
});
}
} else {
header.find('.filterControl').hide();
}
},
getDirectionOfSelectOptions: function getDirectionOfSelectOptions(_alignment) {
var alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase();
switch (alignment) {
case 'left':
return 'ltr';
case 'right':
return 'rtl';
case 'auto':
return 'auto';
default:
return 'ltr';
}
}
};
var filterDataMethods = {
var: function _var(filterDataSource, selectControl) {
var variableValues = window[filterDataSource];
// eslint-disable-next-line guard-for-in
for (var key in variableValues) {
UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
},
url: function url(filterDataSource, selectControl) {
$.ajax({
url: filterDataSource,
dataType: 'json',
success: function success(data) {
// eslint-disable-next-line guard-for-in
for (var key in data) {
UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
}
});
},
json: function json(filterDataSource, selectControl) {
var variableValues = JSON.parse(filterDataSource);
// eslint-disable-next-line guard-for-in
for (var key in variableValues) {
UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
}
UtilsFilterControl.sortSelectControl(selectControl);
}
};
var bootstrap = {
3: {
icons: {
clear: 'glyphicon-trash icon-clear'
}
},
4: {
icons: {
clear: 'fa-trash icon-clear'
}
}
}[Utils.bootstrapVersion];
$.extend($.fn.bootstrapTable.defaults, {
filterControl: false,
onColumnSearch: function onColumnSearch(field, text) {
return false;
},
onCreatedControls: function onCreatedControls() {
return true;
},
filterShowClear: false,
alignmentSelectControlOptions: undefined,
filterTemplate: {
input: function input(that, field, isVisible, placeholder) {
return Utils.sprintf('<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" placeholder="%s">', field, isVisible, placeholder);
},
select: function select(_ref8, field, isVisible) {
var options = _ref8.options;
return Utils.sprintf('<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" dir="%s"></select>', field, isVisible, UtilsFilterControl.getDirectionOfSelectOptions(options.alignmentSelectControlOptions));
},
datepicker: function datepicker(that, field, isVisible) {
return Utils.sprintf('<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s">', field, isVisible);
}
},
disableControlWhenSearch: false,
searchOnEnterKey: false,
// internal variables
valuesFilterControl: []
});
$.extend($.fn.bootstrapTable.columnDefaults, {
filterControl: undefined,
filterData: undefined,
filterDatepickerOptions: undefined,
filterStrictSearch: false,
filterStartsWithSearch: false,
filterControlPlaceholder: ''
});
$.extend($.fn.bootstrapTable.Constructor.EVENTS, {
'column-search.bs.table': 'onColumnSearch',
'created-controls.bs.table': 'onCreatedControls'
});
$.extend($.fn.bootstrapTable.defaults.icons, {
clear: bootstrap.icons.clear
});
$.extend($.fn.bootstrapTable.locales, {
formatClearFilters: function formatClearFilters() {
return 'Clear Filters';
}
});
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
$.fn.bootstrapTable.methods.push('triggerSearch');
$.fn.bootstrapTable.methods.push('clearFilterControl');
$.BootstrapTable = function (_$$BootstrapTable) {
_inherits(_class, _$$BootstrapTable);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
_createClass(_class, [{
key: 'init',
value: function init() {
// Make sure that the filterControl option is set
if (this.options.filterControl) {
var that = this;
// Make sure that the internal variables are set correctly
this.options.valuesFilterControl = [];
this.$el.on('reset-view.bs.table', function () {
// Create controls on $tableHeader if the height is set
if (!that.options.height) {
return;
}
// Avoid recreate the controls
if (that.$tableHeader.find('select').length > 0 || that.$tableHeader.find('input').length > 0) {
return;
}
UtilsFilterControl.createControls(that, that.$tableHeader);
}).on('post-header.bs.table', function () {
UtilsFilterControl.setValues(that);
}).on('post-body.bs.table', function () {
if (that.options.height) {
UtilsFilterControl.fixHeaderCSS(that);
}
}).on('column-switch.bs.table', function () {
UtilsFilterControl.setValues(that);
}).on('load-success.bs.table', function () {
that.EnableControls(true);
}).on('load-error.bs.table', function () {
that.EnableControls(true);
});
}
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'init', this).call(this);
}
}, {
key: 'initToolbar',
value: function initToolbar() {
this.showToolbar = this.showToolbar || this.options.filterControl && this.options.filterShowClear;
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initToolbar', this).call(this);
if (this.options.filterControl && this.options.filterShowClear) {
var $btnGroup = this.$toolbar.find('>.btn-group');
var $btnClear = $btnGroup.find('.filter-show-clear');
if (!$btnClear.length) {
$btnClear = $([Utils.sprintf('<button class="btn btn-%s filter-show-clear" ', this.options.buttonsClass), Utils.sprintf('type="button" title="%s">', this.options.formatClearFilters()), Utils.sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.clear), '</button>'].join('')).appendTo($btnGroup);
$btnClear.off('click').on('click', $.proxy(this.clearFilterControl, this));
}
}
}
}, {
key: 'initHeader',
value: function initHeader() {
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initHeader', this).call(this);
if (!this.options.filterControl) {
return;
}
UtilsFilterControl.createControls(this, this.$header);
}
}, {
key: 'initBody',
value: function initBody() {
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initBody', this).call(this);
UtilsFilterControl.initFilterSelectControls(this);
}
}, {
key: 'initSearch',
value: function initSearch() {
var that = this;
var fp = $.isEmptyObject(that.filterColumnsPartial) ? null : that.filterColumnsPartial;
if (fp === null || Object.keys(fp).length <= 1) {
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initSearch', this).call(this);
}
if (this.options.sidePagination === 'server') {
return;
}
if (fp === null) {
return;
}
// Check partial column filter
that.data = fp ? that.options.data.filter(function (item, i) {
var itemIsExpected = [];
Object.keys(item).forEach(function (key, index) {
var thisColumn = that.columns[that.fieldsColumnsIndex[key]];
var fval = (fp[key] || '').toLowerCase();
var value = item[key];
if (fval === '') {
itemIsExpected.push(true);
} else {
// Fix #142: search use formated data
if (thisColumn && thisColumn.searchFormatter) {
value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header, that.header.formatters[$.inArray(key, that.header.fields)], [value, item, i], value);
}
if ($.inArray(key, that.header.fields) !== -1) {
if (typeof value === 'string' || typeof value === 'number') {
if (thisColumn.filterStrictSearch) {
if (value.toString().toLowerCase() === fval.toString().toLowerCase()) {
itemIsExpected.push(true);
} else {
itemIsExpected.push(false);
}
} else if (thisColumn.filterStartsWithSearch) {
if (('' + value).toLowerCase().indexOf(fval) === 0) {
itemIsExpected.push(true);
} else {
itemIsExpected.push(false);
}
} else {
if (('' + value).toLowerCase().includes(fval)) {
itemIsExpected.push(true);
} else {
itemIsExpected.push(false);
}
}
}
}
}
});
return !itemIsExpected.includes(false);
}) : that.data;
}
}, {
key: 'initColumnSearch',
value: function initColumnSearch(filterColumnsDefaults) {
UtilsFilterControl.copyValues(this);
if (filterColumnsDefaults) {
this.filterColumnsPartial = filterColumnsDefaults;
this.updatePagination();
// eslint-disable-next-line guard-for-in
for (var filter in filterColumnsDefaults) {
this.trigger('column-search', filter, filterColumnsDefaults[filter]);
}
}
}
}, {
key: 'onColumnSearch',
value: function onColumnSearch(event) {
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
UtilsFilterControl.copyValues(this);
var text = $.trim($(event.currentTarget).val());
var $field = $(event.currentTarget).closest('[data-field]').data('field');
if ($.isEmptyObject(this.filterColumnsPartial)) {
this.filterColumnsPartial = {};
}
if (text) {
this.filterColumnsPartial[$field] = text;
} else {
delete this.filterColumnsPartial[$field];
}
// if the searchText is the same as the previously selected column value,
// bootstrapTable will not try searching again (even though the selected column
// may be different from the previous search). As a work around
// we're manually appending some text to bootrap's searchText field
// to guarantee that it will perform a search again when we call this.onSearch(event)
this.searchText += 'randomText';
this.options.pageNumber = 1;
this.EnableControls(false);
this.onSearch(event);
this.trigger('column-search', $field, text);
}
}, {
key: 'clearFilterControl',
value: function clearFilterControl() {
if (this.options.filterControl && this.options.filterShowClear) {
var that = this;
var cookies = UtilsFilterControl.collectBootstrapCookies();
var header = UtilsFilterControl.getCurrentHeader(that);
var table = header.closest('table');
var controls = header.find(UtilsFilterControl.getCurrentSearchControls(that));
var search = that.$toolbar.find('.search input');
var hasValues = false;
var timeoutId = 0;
$.each(that.options.valuesFilterControl, function (i, item) {
hasValues = hasValues ? true : item.value !== '';
item.value = '';
});
UtilsFilterControl.setValues(that);
// clear cookies once the filters are clean
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
if (cookies && cookies.length > 0) {
$.each(cookies, function (i, item) {
if (that.deleteCookie !== undefined) {
that.deleteCookie(item);
}
});
}
}, that.options.searchTimeOut);
// If there is not any value in the controls exit this method
if (!hasValues) {
return;
}
// Clear each type of filter if it exists.
// Requires the body to reload each time a type of filter is found because we never know
// which ones are going to be present.
if (controls.length > 0) {
this.filterColumnsPartial = {};
$(controls[0]).trigger(controls[0].tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 });
} else {
return;
}
if (search.length > 0) {
that.resetSearch();
}
// use the default sort order if it exists. do nothing if it does not
if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {
var sorter = header.find(Utils.sprintf('[data-field="%s"]', $(controls[0]).closest('table').data('sortName')));
if (sorter.length > 0) {
that.onSort({ type: 'keypress', currentTarget: sorter });
$(sorter).find('.sortable').trigger('click');
}
}
}
}
}, {
key: 'triggerSearch',
value: function triggerSearch() {
var header = UtilsFilterControl.getCurrentHeader(this);
var searchControls = UtilsFilterControl.getCurrentSearchControls(this);
header.find(searchControls).each(function () {
var el = $(this);
if (el.is('select')) {
el.change();
} else {
el.keyup();
}
});
}
}, {
key: 'EnableControls',
value: function EnableControls(enable) {
if (this.options.disableControlWhenSearch && this.options.sidePagination === 'server') {
var header = UtilsFilterControl.getCurrentHeader(this);
var searchControls = UtilsFilterControl.getCurrentSearchControls(this);
if (!enable) {
header.find(searchControls).prop('disabled', 'disabled');
} else {
header.find(searchControls).removeProp('disabled');
}
}
}
}]);
return _class;
}($.BootstrapTable);
})(jQuery);
}); | {
"content_hash": "b4e54324d64874ef2dacfa722ec81203",
"timestamp": "",
"source": "github",
"line_count": 911,
"max_line_length": 335,
"avg_line_length": 38.1602634467618,
"alnum_prop": 0.5591128753883328,
"repo_name": "joeyparrish/cdnjs",
"id": "59a706f0f5c9d69acd9a42f16043a0ce6f6a448b",
"size": "34765",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ajax/libs/bootstrap-table/1.13.2/extensions/filter-control/bootstrap-table-filter-control.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package top.inject.dada.request;
import top.inject.dada.model.in.DaDaStore;
import top.inject.dada.protocol.Request;
import java.util.ArrayList;
@Request(url = "/api/shop/add")
public class StoreCreateRequest extends ArrayList<DaDaStore> {
}
| {
"content_hash": "cb9b54c642af4c074efdf836a74c62b9",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 62,
"avg_line_length": 22.363636363636363,
"alnum_prop": 0.7845528455284553,
"repo_name": "TamirTian/DaDaSDK",
"id": "8bd56864861504f068f7e02de78ff0d4ffd6a83d",
"size": "246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/top/inject/dada/request/StoreCreateRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "74778"
}
],
"symlink_target": ""
} |
FROM jenkinsci/blueocean
USER root | {
"content_hash": "e60c32035d70a926e382ebe6e449e8da",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 24,
"avg_line_length": 11.666666666666666,
"alnum_prop": 0.8571428571428571,
"repo_name": "arcyfelix/Courses",
"id": "277900c83d51b831759985bd5a4fadfc976907fb",
"size": "35",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "18-06-21-Docker-from-A-to-Z-Swarm+Jenkins/05 - Docker and Jenkins For Continuous Integration/01 - Jenkins Dockerfile/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "30658"
},
{
"name": "CSS",
"bytes": "68601"
},
{
"name": "Dockerfile",
"bytes": "2012"
},
{
"name": "Elixir",
"bytes": "60760"
},
{
"name": "Groovy",
"bytes": "3605"
},
{
"name": "HTML",
"bytes": "3083919"
},
{
"name": "Java",
"bytes": "561657"
},
{
"name": "JavaScript",
"bytes": "161601"
},
{
"name": "Jupyter Notebook",
"bytes": "95735180"
},
{
"name": "PHP",
"bytes": "82"
},
{
"name": "Python",
"bytes": "185224"
},
{
"name": "Scala",
"bytes": "84149"
},
{
"name": "Shell",
"bytes": "47283"
},
{
"name": "Vue",
"bytes": "90691"
},
{
"name": "XSLT",
"bytes": "88587"
}
],
"symlink_target": ""
} |
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Link: https://leetcode.com/problems/merge-k-sorted-lists/#/description
Example: None
Solution:
The problem is simply to find connected components in the grid.
Source: None
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
import heapq
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
for node in lists:
if node:
heapq.heappush(heap, (node.val, node) )
p = head = ListNode(-1)
while heap:
p.next = p = heapq.heappop(heap)[1]
if p.next:
heapq.heappush( heap, (p.next.val, p.next) )
return head.next
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None | {
"content_hash": "ace0f0fddeff36e203c6b03eacabed87",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 102,
"avg_line_length": 23.681818181818183,
"alnum_prop": 0.5604606525911708,
"repo_name": "supermarkion/Life-Backup",
"id": "9287029f41af0abe2f233cda2df18e30faa84cc4",
"size": "1042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/MergeKSortedLists.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "171862"
},
{
"name": "CSS",
"bytes": "513"
},
{
"name": "HTML",
"bytes": "5272"
},
{
"name": "JavaScript",
"bytes": "10918"
},
{
"name": "Python",
"bytes": "92106"
}
],
"symlink_target": ""
} |
<Record>
<Term>Hypertensive Encephalopathy</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Hypertensive Crisis</ParentTerm>
<ParentTerm>Intracranial Hypertension</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Non-Neoplastic Disorder/Non-Neoplastic Disorder by Site/Non-Neoplastic Nervous System Disorder/Non-Neoplastic Central Nervous System Disorder/Encephalopathy/Hypertensive Encephalopathy,/NCIThesaurus/Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Cardiovascular Disorder/Vascular Disorder/Non-Neoplastic Vascular Disorder/Hypertensive Episode/Hypertensive Crisis/Hypertensive Encephalopathy</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Brain Diseases/Intracranial Hypertension/Hypertensive Encephalopathy</ClassificationPath>
<BroaderTerm>Non-Neoplastic Nervous System Disorder</BroaderTerm>
<BroaderTerm>Hypertensive Crisis</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder by Site</BroaderTerm>
<BroaderTerm>Encephalopathy</BroaderTerm>
<BroaderTerm>Hypertensive Encephalopathy,</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Non-Neoplastic Vascular Disorder</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Cardiovascular Disorder</BroaderTerm>
<BroaderTerm>Intracranial Hypertension</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Central Nervous System Diseases</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Vascular Disorder</BroaderTerm>
<BroaderTerm>Brain Diseases</BroaderTerm>
<BroaderTerm>Non-Neoplastic Central Nervous System Disorder</BroaderTerm>
<BroaderTerm>Hypertensive Episode</BroaderTerm>
<BroaderTerm>Hypertensive Encephalopathy</BroaderTerm>
<ChildTerm>Posterior Leukoencephalopathy Syndrome</ChildTerm>
<Synonym>Hypertensive Encephalopathy</Synonym>
<Description>Brain dysfunction or damage resulting from sustained MALIGNANT HYPERTENSION. When BLOOD PRESSURE exceeds the limits of cerebral autoregulation, cerebral blood flow is impaired (BRAIN ISCHEMIA). Clinical manifestations include HEADACHE; NAUSEA; VOMITING; SEIZURES; altered mental status (in some cases progressing to COMA); PAPILLEDEMA; and RETINAL HEMORRHAGE.</Description>
<Source>NCI Thesaurus</Source>
<Source>MeSH</Source>
</Record>
| {
"content_hash": "e368a9a5c211bc3ed63b7176bcddb331",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 554,
"avg_line_length": 76.76470588235294,
"alnum_prop": 0.839463601532567,
"repo_name": "detnavillus/modular-informatic-designs",
"id": "1e74c5ff9d6b8cdab9f83a3134589cf6e17a4d0b",
"size": "2610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pipeline/src/test/resources/thesaurus/diseaseorsyndrome/hypertensiveencephalopathy.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2069134"
}
],
"symlink_target": ""
} |
/*
* @test
* @bug 7003595
* @summary IncompatibleClassChangeError with unreferenced local class with subclass
*/
public class T7003595b {
public static void main(String... args) throws Exception {
class A {}
class B extends A {}
B.class.getSuperclass().getDeclaringClass();
}
}
| {
"content_hash": "b3016d81fd9ec9a75051aba5064cfbe2",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 84,
"avg_line_length": 21.133333333333333,
"alnum_prop": 0.6561514195583596,
"repo_name": "emil-wcislo/sbql4j8",
"id": "0e0eb2ecc572844b44224ab7036242241d463545",
"size": "1367",
"binary": false,
"copies": "64",
"ref": "refs/heads/master",
"path": "sbql4j8/src/test/openjdk/tools/javac/7003595/T7003595b.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12808"
},
{
"name": "Groff",
"bytes": "47559"
},
{
"name": "HTML",
"bytes": "3458"
},
{
"name": "Java",
"bytes": "17317619"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "Makefile",
"bytes": "16166"
},
{
"name": "Shell",
"bytes": "81061"
},
{
"name": "XSLT",
"bytes": "951"
}
],
"symlink_target": ""
} |
print(__doc__)
from sklearn import svm
from sklearn.datasets import samples_generator
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.pipeline import Pipeline
def loadData():
# generating data
X, y = samples_generator.make_classification(n_features=20, \
n_informative=3, \
n_redundant=0, \
n_classes=4, \
n_clusters_per_class=2)
return X, y
# ANOVA SVM-C
def createANOVASVM():
# anova filter, take 3 best ranked features
anova_filter = SelectKBest(f_regression, k=3)
# svm
clf = svm.SVC(kernel='linear')
anova_svm = Pipeline([('anova', anova_filter), \
('svm', clf)])
return anova_svm
def predict(X, y, anova_svm):
anova_svm.fit(X, y)
target = anova_svm.predict(X)
return target
def test():
X, y = loadData()
anova_svm = createANOVASVM()
target = predict(X, y, anova_svm)
print target
if __name__ == '__main__':
test()
| {
"content_hash": "32cf1cb487e923f26a90c8b19c1cc042",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 72,
"avg_line_length": 23.28,
"alnum_prop": 0.5266323024054983,
"repo_name": "kwailamchan/programming-languages",
"id": "27fbd39a1db9844366bc6be6d3c2510941abe0cc",
"size": "1360",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "python/sklearn/examples/general/pipeline_anova_svm.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2321"
},
{
"name": "Batchfile",
"bytes": "7087"
},
{
"name": "C",
"bytes": "2883116"
},
{
"name": "C++",
"bytes": "12948373"
},
{
"name": "CMake",
"bytes": "128629"
},
{
"name": "CSS",
"bytes": "197791"
},
{
"name": "Cuda",
"bytes": "687316"
},
{
"name": "E",
"bytes": "2914"
},
{
"name": "Eiffel",
"bytes": "1073"
},
{
"name": "Fortran",
"bytes": "1332263"
},
{
"name": "HTML",
"bytes": "257547"
},
{
"name": "Java",
"bytes": "102661"
},
{
"name": "JavaScript",
"bytes": "439019"
},
{
"name": "Jupyter Notebook",
"bytes": "5488542"
},
{
"name": "Makefile",
"bytes": "24949"
},
{
"name": "Matlab",
"bytes": "32307"
},
{
"name": "PHP",
"bytes": "21650"
},
{
"name": "PLpgSQL",
"bytes": "16859"
},
{
"name": "Python",
"bytes": "5424664"
},
{
"name": "QMake",
"bytes": "787"
},
{
"name": "R",
"bytes": "105611"
},
{
"name": "Ruby",
"bytes": "152074"
},
{
"name": "SAS",
"bytes": "4505"
},
{
"name": "Scala",
"bytes": "6121"
},
{
"name": "Shell",
"bytes": "49387"
},
{
"name": "Visual Basic",
"bytes": "1174"
}
],
"symlink_target": ""
} |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Mozu.Api.Contracts.Fulfillment {
/// <summary>
///
/// </summary>
[DataContract]
public class CollectionModelOfManifest {
/// <summary>
/// Gets or Sets Embedded
/// </summary>
[DataMember(Name="_embedded", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "_embedded")]
public Dictionary<string, List<Manifest>> Embedded { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="_links", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "_links")]
public Dictionary<string, Link> Links { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class CollectionModelOfManifest {\n");
sb.Append(" Embedded: ").Append(Embedded).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| {
"content_hash": "db4ceed8680e514719671a859dfd0073",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 68,
"avg_line_length": 28.634615384615383,
"alnum_prop": 0.6447280053727333,
"repo_name": "Mozu/mozu-dotnet",
"id": "37d7aadbb6f957a35d4b76f717c3a666db7c004e",
"size": "1489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Mozu.Api/Contracts/Fulfillment/CollectionModelOfManifest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "279"
},
{
"name": "C#",
"bytes": "8160653"
},
{
"name": "F#",
"bytes": "1750"
},
{
"name": "PowerShell",
"bytes": "3311"
}
],
"symlink_target": ""
} |
/*
* Miscellaneous internetwork
* definitions for kernel.
*/
/*
* Network types.
*
* Internally the system keeps counters in the headers with the bytes
* swapped so that VAX instructions will work on them. It reverses
* the bytes before transmission at each protocol level. The n_ types
* represent the types with the bytes in ``high-ender'' order.
*/
typedef short n_short; /* short as received from the net */
typedef long n_long; /* long as received from the net */
typedef long n_time; /* ms since 00:00 GMT, byte rev */
#ifdef KERNEL
n_time iptime __P((void));
#endif
#ifndef _SA_FAMILY_T
#define _SA_FAMILY_T
typedef unsigned short sa_family_t;
#endif
| {
"content_hash": "55ccad2bb92928b96aebf95250a87c6d",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 70,
"avg_line_length": 24.392857142857142,
"alnum_prop": 0.7027818448023426,
"repo_name": "liuchuang/snort",
"id": "c217d8d24cfb5a2e1268a9246ffd07908ece72fd",
"size": "2563",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "snort-2.9.6.0/src/win32/WIN32-Includes/NETINET/IN_SYSTM.H",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "13492693"
},
{
"name": "C++",
"bytes": "194474"
},
{
"name": "Objective-C",
"bytes": "22299"
},
{
"name": "Perl",
"bytes": "4230"
},
{
"name": "Python",
"bytes": "115154"
},
{
"name": "Shell",
"bytes": "1083939"
},
{
"name": "TeX",
"bytes": "656483"
}
],
"symlink_target": ""
} |
package io.realm.internal;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
/**
* This class is used for holding the reference to the native pointers present in NativeObjects.
* This is required as phantom references cannot access the original objects for this value.
* The phantom references will be stored in a double linked list to avoid the reference itself gets GCed. When the
* referent get GCed, the reference will be added to the ReferenceQueue. Loop in the daemon thread will retrieve the
* phantom reference from the ReferenceQueue then dealloc the referent and remove the reference from the double linked
* list. See {@link FinalizerRunnable} for more implementation details.
*/
final class NativeObjectReference extends PhantomReference<NativeObject> {
// Linked list to keep the reference of the PhantomReference
private static class ReferencePool {
NativeObjectReference head;
synchronized void add(NativeObjectReference ref) {
ref.prev = null;
ref.next = head;
if (head != null) {
head.prev = ref;
}
head = ref;
}
synchronized void remove(NativeObjectReference ref) {
NativeObjectReference next = ref.next;
NativeObjectReference prev = ref.prev;
ref.next = null;
ref.prev = null;
if (prev != null) {
prev.next = next;
} else {
head = next;
}
if (next != null) {
next.prev = prev;
}
}
}
// The pointer to the native object to be handled
private final long nativePtr;
// The pointer to the native finalize function
private final long nativeFinalizerPtr;
private final NativeContext context;
private NativeObjectReference prev;
private NativeObjectReference next;
private static ReferencePool referencePool = new ReferencePool();
NativeObjectReference(NativeContext context,
NativeObject referent,
ReferenceQueue<? super NativeObject> referenceQueue) {
super(referent, referenceQueue);
this.nativePtr = referent.getNativePtr();
this.nativeFinalizerPtr = referent.getNativeFinalizerPtr();
this.context = context;
referencePool.add(this);
}
/**
* To dealloc native resources.
*/
void cleanup() {
synchronized (context) {
nativeCleanUp(nativeFinalizerPtr, nativePtr);
}
// Remove the PhantomReference from the pool to free it.
referencePool.remove(this);
}
/**
* Calls the native finalizer function to free the given native pointer.
*/
static native void nativeCleanUp(long nativeFinalizer, long nativePointer);
}
| {
"content_hash": "0419f392f8deb114f35a9f55cd2eae19",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 118,
"avg_line_length": 34.57831325301205,
"alnum_prop": 0.645993031358885,
"repo_name": "realm/realm-java",
"id": "9e70b7dd5c6ceada781cceec2fbe67c2f7143863",
"size": "3459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "realm/realm-library/src/main/java/io/realm/internal/NativeObjectReference.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "710925"
},
{
"name": "CMake",
"bytes": "10026"
},
{
"name": "Dockerfile",
"bytes": "5298"
},
{
"name": "Groovy",
"bytes": "13369"
},
{
"name": "HTML",
"bytes": "2519"
},
{
"name": "Java",
"bytes": "6254694"
},
{
"name": "JavaScript",
"bytes": "11116"
},
{
"name": "Kotlin",
"bytes": "1958235"
},
{
"name": "Python",
"bytes": "4275"
},
{
"name": "Shell",
"bytes": "39223"
}
],
"symlink_target": ""
} |
layout: defaulten
back_label: "Inicio"
back_path: "/"
class: data
---
<!-- section intro-->
<section class="title">
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h1>LabConDatos</h1>
<h2>Oct 1 - Biblioteca de México 10:00 - 19:00 <br> Oct 2 - Cineteca Nacional 14:00</h2>
</div>
</div>
</div>
</section>
<section class="contenido">
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<p> Within the second Open Data Regional Conference Latin America and the Caribbean, the Office of the President of the Republic,
<a href="http://data4.mx/">Data4</a> and <a href="http://applicate.mx">APPlícate</a> invite you to participate as a volunteer in LabConDatos which will
be held on the Biblioteca de México and the Cineteca Nacional on October 1 and 2.</p>
<p>We are looking for seven programmers, seven designers and seven data analists, that will be working, under the leadership of a mentor, to analize and generate intearctive visualizations using one of seven database released by the mexican federal government this year at <a href="http://datos.gob.mx">datos.gob.mx</a>.</p>
<h3>Prize: $ 40,000 MXN</h3><br>
<p>The visualizations will be realeased at condatos.org/lab.html and at datos.gob.mx/historias and the team members of the best visualization will recieve a $40,000 mexican peso prize.</p>
<h4>If you are interested in participating, send your CV and a paragraph about why you want to participate in LabConDatos to dataton@datos.gob.mx before the 25th of September</h4><br>
<p>If you are chosen to participate you will recieve a message before September 26th</p>
<h2>Requirements:</h2>
<ul>
<li>Programmers: experience in HTML/CSS, JQUERY, D3, MYSQL,
SQLITE or ANGULAR.
</li>
<li>Designers: experience with Adobe Illustrator, Indesign, Fireworks;
web development experience and skills such as HTML5, CSS or WordPress.
</li>
<li>Data Analists: experience in data processing and
knowledge of software like Stata, R, Excel o SPSS.
</li>
</ul>
</div>
</div>
</div>
</section>
<!-- section paralelos-->
<section class="paralelos">
<a name="eventos-paralelos"></a>
<div class="container">
<div class="row">
<h2>Topics and datos</h2>
<p>
<a href="http://catalogo.datos.gob.mx/dataset?organization=salud">
<img src="../img/bootcamp_icon.png" alt="Mortalidad Materna">
Maternal Mortality - GIRE A.C.
</a>
<a href="http://catalogo.datos.gob.mx/dataset?organization=sagarpa">
<img src="../img/bootcamp_icon.png" alt="Subsuduis al Campo"> Agricultural Subsidies - FUNDAR A.C.
</a>
<a href="http://catalogo.datos.gob.mx">
<img src="../img/bootcamp_icon.png" alt="Hambre">Cruzade Against Hunger - México Evalúa</a>
<a href="http://201.175.32.249/dataset/fondo-de-desastres-naturales">
<img src="../img/bootcamp_icon.png" alt="Fonden"> FONDEN - CIDE
</a>
<a href="http://catalogo.datos.gob.mx/dataset?organization=imss">
<img src="../img/bootcamp_icon.png" alt="IMSS">IMSS Beneficiaries - IMCO </a>
<a href="http://catalogo.datos.gob.mx/dataset?organization=sct">
<img src="../img/bootcamp_icon.png" alt="SCT"> SCT - ITDP
</a>
<a href="http://catalogo.datos.gob.mx/dataset?organization=sedesol">
<img src="../img/bootcamp_icon.png" alt="SEDESOL"> SEDESOL - GEOSOC
</a>
</p>
</div>
</div>
</section>
<!-- section aliados-->
<section class="aliados">
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-offset-1 ">
<ul class="row">
<li>
<p>
<a class="logosfooter" href="" target="_blank">
<br><img src="../img/logo_d4.png" alt="Data4" height="60px">
</a>
<a class="logosfooter" href="https://www.google.com/" target="_blank">
<br><img src="../img/google.png" alt="Google" height="40px">
</a>
<a class="logosfooter" href="" target="_blank">
<br><img src="../img/logo_applicate.png" alt="APPlícate" height="60px">
</a>
</p>
</li>
<li>
</li>
</ul>
</div>
</div>
</div>
</section>
| {
"content_hash": "4d0e86444c92d80ce6e227c9a3c43743",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 338,
"avg_line_length": 37.232,
"alnum_prop": 0.5870219166308551,
"repo_name": "ciudadanointeligente/condatos",
"id": "dac1f868c481f905caa8b9587653d114c981c86b",
"size": "4664",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "laben.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "506008"
},
{
"name": "HTML",
"bytes": "265061"
},
{
"name": "JavaScript",
"bytes": "7927"
}
],
"symlink_target": ""
} |
<?php
namespace Katsana\Sdk;
use BadMethodCallException;
/**
* @method $this onTimeZone(string|null $timeZoneCode)
* @method $this includes(array|string $includes)
* @method $this excludes(array $excludes)
* @method $this with(string $name, mixed $value)
* @method $this forPage(int|null $page = null)
* @method $this take(int|null $perPage = null)
*/
class Query
{
/**
* Set requested page.
*
* @var int|null
*/
protected $page;
/**
* Per page limit.
*
* @var int|null
*/
protected $perPage;
/**
* Request data timezone.
*
* @var string|null
*/
protected $timezone;
/**
* Includes data.
*
* @var array
*/
protected $includes = [];
/**
* Excludes data.
*
* @var array
*/
protected $excludes = [];
/**
* Custom data.
*
* @var array
*/
protected $customs = [];
/**
* The methods that should be accessed using magic method.
*
* @var array
*/
protected $passthru = [
'onTimeZone', 'includes', 'excludes', 'with', 'forPage', 'take',
];
/**
* Set timezone for the request input.
*
* @param string|null $timeZoneCode
*
* @return $this
*/
protected function onTimeZone(?string $timeZoneCode)
{
if (\is_null($timeZoneCode)) {
$this->timezone = null;
} elseif (\in_array($timeZoneCode, \timezone_identifiers_list())) {
$this->timezone = $timeZoneCode;
}
return $this;
}
/**
* Set includes data.
*
* @param array $includes
*
* @return $this
*/
protected function includes($includes)
{
$includes = \is_array($includes) ? $includes : \func_get_args();
$this->includes = $includes;
return $this;
}
/**
* Set excludes data.
*
* @param array $excludes
*
* @return $this
*/
protected function excludes($excludes)
{
$excludes = \is_array($excludes) ? $excludes : \func_get_args();
$this->excludes = $excludes;
return $this;
}
/**
* Set custom data.
*
* @param string $name
* @param mixed $value
*
* @return $this
*/
protected function with(string $name, $value)
{
$this->customs[$name] = $value;
return $this;
}
/**
* Set current page.
*
* @param int|null $page
*
* @return $this
*/
protected function forPage(?int $page = null)
{
$this->page = $page;
return $this;
}
/**
* Set per page limit.
*
* @param int|null $perPage
*
* @return $this
*/
protected function take(?int $perPage = null)
{
$this->perPage = $perPage;
return $this;
}
/**
* Build query string.
*
* @return array
*/
public function toArray(): array
{
return $this->build(static function ($data, $customs) {
return \array_merge($customs, $data);
});
}
/**
* Build query string.
*
* @param callable $callback
*
* @return array
*/
public function build(callable $callback): array
{
$data = [];
foreach (['includes', 'excludes'] as $key) {
if (! empty($this->{$key})) {
$data[$key] = \implode(',', $this->{$key});
}
}
if (! \is_null($this->timezone)) {
$data['timezone'] = $this->timezone;
}
if (\is_int($this->page) && $this->page > 0) {
$data['page'] = $this->page;
if (\is_int($this->perPage) && $this->perPage > 5) {
$data['per_page'] = $this->perPage;
}
}
return \call_user_func($callback, $data, $this->customs);
}
/**
* Handle dynamic method calls into the model.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call(string $method, array $parameters)
{
if (\in_array($method, $this->passthru)) {
return $this->$method(...$parameters);
}
throw new BadMethodCallException(__CLASS__."::{$method}() method doesn't exist!");
}
/**
* Handle dynamic static method calls into the method.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public static function __callStatic(string $method, array $parameters)
{
return (new static())->$method(...$parameters);
}
}
| {
"content_hash": "e5fb96bb38ad4fe376425b8c80794546",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 90,
"avg_line_length": 20.012820512820515,
"alnum_prop": 0.497544309203502,
"repo_name": "katsana/katsana-sdk-php",
"id": "7762ba70e8837d60ac2e84f0217dc19ce4ae18f7",
"size": "4683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Query.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "108392"
}
],
"symlink_target": ""
} |
package acc.common.cmdline;
/**
* Defines error codes returned by CmdParser.
*/
public enum CmdExceptionCode {
PARSE_DUPLICATE_DEFAULT_COMMAND,
PARSE_DUPLICATE_COMMAND_NAME,
PARSE_PARAM_NAME_UNDEFINED,
DISPATCH_UNKNOWN_COMMAND,
DISPATCH_NO_COMMAND,
DISPATCH_INVOKE_ERROR,
DISPATCH_MISSING_REQUIRED_PARAMETER,
DISPATCH_UNSUPPORTED_PARAMETER_TYPE,
DISPATCH_EMPTY_PARAMETER,
DISPATCH_UNKNOWN_PARAMETER,
DISPATCH_VALIDATION_ERROR,
}
| {
"content_hash": "7e94471c88e2a4a5052d2c4c808f9aeb",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 45,
"avg_line_length": 26.444444444444443,
"alnum_prop": 0.7394957983193278,
"repo_name": "Guidewire/java-cmd-parser",
"id": "32c78f0df8b55baa83a78c96dbdff7bfb11a2133",
"size": "476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/acc/common/cmdline/CmdExceptionCode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "42190"
}
],
"symlink_target": ""
} |
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace TestMonoDroid
{
public static class OperationExtentions{
public static OperationType GetOperationType(this string operationString) {
if (string.IsNullOrEmpty(operationString))
throw new ArgumentNullException ("operationString");
switch (operationString) {
case "/":
return OperationType.Div;
case "*":
return OperationType.Mul;
case "+":
return OperationType.Add;
case "-":
return OperationType.Sub;
default:
throw new ArgumentOutOfRangeException ("operationString");
}
}
public static decimal ApplyOperation(this OperationType type, decimal lValue, decimal rValue){
switch (type) {
case OperationType.Div:
return lValue / rValue;
case OperationType.Mul:
return lValue * rValue;
case OperationType.Add:
return lValue + rValue;
case OperationType.Sub:
return lValue - rValue;
default:
throw new ArgumentOutOfRangeException ("type");
}
}
}
}
| {
"content_hash": "2a847a23cb76c2a77b0f36cf81a4c0e9",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 96,
"avg_line_length": 23.782608695652176,
"alnum_prop": 0.7193784277879341,
"repo_name": "SKorolchuk/XamarinAndroidProjects",
"id": "313e3adf5d8acd7dbfdce88eb851d8d2ca9f9e68",
"size": "1094",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TestMonoDroid/ProjectTypes/OperationExtentions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "4648"
}
],
"symlink_target": ""
} |
import pytest
from tests.lib import (_create_test_package, _change_test_package_version,
pyversion)
from tests.lib.local_repos import local_checkout
@pytest.mark.network
def test_install_editable_from_git_with_https(script, tmpdir):
"""
Test cloning from Git with https.
"""
result = script.pip(
'install', '-e',
'%s#egg=pip-test-package' %
local_checkout(
'git+https://github.com/pypa/pip-test-package.git',
tmpdir.join("cache"),
),
expect_error=True,
)
result.assert_installed('pip-test-package', with_files=['.git'])
@pytest.mark.network
def test_install_noneditable_git(script, tmpdir):
"""
Test installing from a non-editable git URL with a given tag.
"""
result = script.pip(
'install',
'git+https://github.com/pypa/pip-test-package.git'
'@0.1.1#egg=pip-test-package'
)
egg_info_folder = (
script.site_packages /
'pip_test_package-0.1.1-py%s.egg-info' % pyversion
)
result.assert_installed('piptestpackage',
without_egg_link=True,
editable=False)
assert egg_info_folder in result.files_created, str(result)
@pytest.mark.network
def test_git_with_sha1_revisions(script):
"""
Git backend should be able to install from SHA1 revisions
"""
version_pkg_path = _create_test_package(script)
_change_test_package_version(script, version_pkg_path)
sha1 = script.run(
'git', 'rev-parse', 'HEAD~1',
cwd=version_pkg_path,
).stdout.strip()
script.pip(
'install', '-e',
'%s@%s#egg=version_pkg' %
('git+file://' + version_pkg_path.abspath.replace('\\', '/'), sha1)
)
version = script.run('version_pkg')
assert '0.1' in version.stdout, version.stdout
@pytest.mark.network
def test_git_with_branch_name_as_revision(script):
"""
Git backend should be able to install from branch names
"""
version_pkg_path = _create_test_package(script)
script.run(
'git', 'checkout', '-b', 'test_branch',
expect_stderr=True,
cwd=version_pkg_path,
)
_change_test_package_version(script, version_pkg_path)
script.pip(
'install', '-e', '%s@test_branch#egg=version_pkg' %
('git+file://' + version_pkg_path.abspath.replace('\\', '/'))
)
version = script.run('version_pkg')
assert 'some different version' in version.stdout
@pytest.mark.network
def test_git_with_tag_name_as_revision(script):
"""
Git backend should be able to install from tag names
"""
version_pkg_path = _create_test_package(script)
script.run(
'git', 'tag', 'test_tag',
expect_stderr=True,
cwd=version_pkg_path,
)
_change_test_package_version(script, version_pkg_path)
script.pip(
'install', '-e', '%s@test_tag#egg=version_pkg' %
('git+file://' + version_pkg_path.abspath.replace('\\', '/'))
)
version = script.run('version_pkg')
assert '0.1' in version.stdout
@pytest.mark.network
def test_git_with_tag_name_and_update(script, tmpdir):
"""
Test cloning a git repository and updating to a different version.
"""
result = script.pip(
'install', '-e', '%s#egg=pip-test-package' %
local_checkout(
'git+http://github.com/pypa/pip-test-package.git',
tmpdir.join("cache"),
),
expect_error=True,
)
result.assert_installed('pip-test-package', with_files=['.git'])
result = script.pip(
'install', '--global-option=--version', '-e',
'%s@0.1.2#egg=pip-test-package' %
local_checkout(
'git+http://github.com/pypa/pip-test-package.git',
tmpdir.join("cache"),
),
expect_error=True,
)
assert '0.1.2' in result.stdout
@pytest.mark.network
def test_git_branch_should_not_be_changed(script, tmpdir):
"""
Editable installations should not change branch
related to issue #32 and #161
"""
script.pip(
'install', '-e', '%s#egg=pip-test-package' %
local_checkout(
'git+http://github.com/pypa/pip-test-package.git',
tmpdir.join("cache"),
),
expect_error=True,
)
source_dir = script.venv_path / 'src' / 'pip-test-package'
result = script.run('git', 'branch', cwd=source_dir)
assert '* master' in result.stdout, result.stdout
@pytest.mark.network
def test_git_with_non_editable_unpacking(script, tmpdir):
"""
Test cloning a git repository from a non-editable URL with a given tag.
"""
result = script.pip(
'install', '--global-option=--version',
local_checkout(
'git+http://github.com/pypa/pip-test-package.git@0.1.2'
'#egg=pip-test-package',
tmpdir.join("cache")
),
expect_error=True,
)
assert '0.1.2' in result.stdout
@pytest.mark.network
def test_git_with_editable_where_egg_contains_dev_string(script, tmpdir):
"""
Test cloning a git repository from an editable url which contains "dev"
string
"""
result = script.pip(
'install', '-e',
'%s#egg=django-devserver' %
local_checkout(
'git+git://github.com/dcramer/django-devserver.git',
tmpdir.join("cache")
)
)
result.assert_installed('django-devserver', with_files=['.git'])
@pytest.mark.network
def test_git_with_non_editable_where_egg_contains_dev_string(script, tmpdir):
"""
Test cloning a git repository from a non-editable url which contains "dev"
string
"""
result = script.pip(
'install',
'%s#egg=django-devserver' %
local_checkout(
'git+git://github.com/dcramer/django-devserver.git',
tmpdir.join("cache")
),
)
devserver_folder = script.site_packages / 'devserver'
assert devserver_folder in result.files_created, str(result)
@pytest.mark.network
def test_git_with_ambiguous_revs(script):
"""
Test git with two "names" (tag/branch) pointing to the same commit
"""
version_pkg_path = _create_test_package(script)
package_url = (
'git+file://%s@0.1#egg=version_pkg' %
(version_pkg_path.abspath.replace('\\', '/'))
)
script.run('git', 'tag', '0.1', cwd=version_pkg_path)
result = script.pip('install', '-e', package_url)
assert 'Could not find a tag or branch' not in result.stdout
# it is 'version-pkg' instead of 'version_pkg' because
# egg-link name is version-pkg.egg-link because it is a single .py module
result.assert_installed('version-pkg', with_files=['.git'])
@pytest.mark.network
def test_git_works_with_editable_non_origin_repo(script):
# set up, create a git repo and install it as editable from a local
# directory path
version_pkg_path = _create_test_package(script)
script.pip('install', '-e', version_pkg_path.abspath)
# 'freeze'ing this should not fall over, but should result in stderr output
# warning
result = script.pip('freeze', expect_stderr=True)
assert "Error when trying to get requirement" in result.stderr
assert "Could not determine repository location" in result.stdout
assert "version-pkg==0.1" in result.stdout
| {
"content_hash": "00b319e5bca72176aea789192b8c0b8c",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 79,
"avg_line_length": 31.676724137931036,
"alnum_prop": 0.6113756973737924,
"repo_name": "newsteinking/docker",
"id": "06ca8ffb1b47f6af945f6b7108f13b8cca5e9b22",
"size": "7349",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tests/functional/test_install_vcs.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1835"
},
{
"name": "Python",
"bytes": "3994890"
},
{
"name": "Shell",
"bytes": "2437"
}
],
"symlink_target": ""
} |
namespace EasyHash.Helpers.Extensions
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
internal static class ExpressionExtensions
{
public static Expression ForEach(this Expression collection, ParameterExpression loopVar, params Expression[] loopContent)
{
var elementType = loopVar.Type;
var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType);
var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType);
var breakLabel = Expression.Label("LoopBreak");
var enumeratorVar = Expression.Variable(enumeratorType, "enumerator");
var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod(nameof(IEnumerable.GetEnumerator)));
var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext)));
var assignLoopVar = Expression.Assign(loopVar, Expression.Property(enumeratorVar, nameof(IEnumerator.Current)));
var expressions = new[] { assignLoopVar }.Union(loopContent);
var loop = Expression.Block(new[] { enumeratorVar },
Expression.Assign(enumeratorVar, getEnumeratorCall),
Expression.Loop(
Expression.IfThenElse(
Expression.Equal(moveNextCall, Expression.Constant(true)),
Expression.Block(new[] { loopVar }, expressions),
Expression.Break(breakLabel)
),
breakLabel)
);
return loop;
}
public static string GetMemberName<TObj, TMember>(this Expression<Func<TObj, TMember>> memberSelector)
{
return GetMemberName(memberSelector.Body);
}
internal static string GetDebugView(this Expression exp)
{
if (exp == null)
{
return null;
}
var propertyInfo = typeof(Expression).GetProperty("DebugView", BindingFlags.Instance | BindingFlags.NonPublic);
return propertyInfo.GetValue(exp) as string;
}
private static string GetMemberName(Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Parameter:
return ((ParameterExpression)expression).Name;
case ExpressionType.MemberAccess:
return ((MemberExpression)expression).Member.Name;
case ExpressionType.Call:
return ((MethodCallExpression)expression).Method.Name;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
return GetMemberName(((UnaryExpression)expression).Operand);
case ExpressionType.Invoke:
return GetMemberName(((InvocationExpression)expression).Expression);
case ExpressionType.ArrayLength:
return nameof(Array.Length);
default:
throw new Exception("not a proper member selector");
}
}
}
}
| {
"content_hash": "9aa3d11fe3e59c164f4e89597763348b",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 130,
"avg_line_length": 42.90909090909091,
"alnum_prop": 0.6092615012106537,
"repo_name": "iarovyi/EasyHash",
"id": "ac732f9b5c93bb375c0e62f94c7b439b7cfc476f",
"size": "3306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EasyHash/Helpers/Extensions/ExpressionExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "74"
},
{
"name": "C#",
"bytes": "117203"
},
{
"name": "PowerShell",
"bytes": "9582"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Sun Jun 09 12:16:07 GMT+05:30 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.update.TransactionLog (Solr 4.3.1 API)
</TITLE>
<META NAME="date" CONTENT="2013-06-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.update.TransactionLog (Solr 4.3.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/update/TransactionLog.html" title="class in org.apache.solr.update"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/update//class-useTransactionLog.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionLog.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.solr.update.TransactionLog</B></H2>
</CENTER>
No usage of org.apache.solr.update.TransactionLog
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/update/TransactionLog.html" title="class in org.apache.solr.update"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/update//class-useTransactionLog.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionLog.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
| {
"content_hash": "e3a970278623039013b193d46cfbaa89",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 216,
"avg_line_length": 40.64779874213836,
"alnum_prop": 0.5848677084945072,
"repo_name": "rcr-81/SolrCamper",
"id": "8127ea11d74fbfe4594285a900de844b2ba58f52",
"size": "6463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/solr-core/org/apache/solr/update/class-use/TransactionLog.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "119393"
},
{
"name": "JavaScript",
"bytes": "1120581"
},
{
"name": "Perl",
"bytes": "1008"
},
{
"name": "Shell",
"bytes": "9603"
},
{
"name": "XSLT",
"bytes": "24328"
}
],
"symlink_target": ""
} |
namespace base {
template <typename T>
struct DefaultSingletonTraits;
} // namespace base
namespace query_tiles {
class TileService;
// A factory to create one unique TileService.
class TileServiceFactory : public SimpleKeyedServiceFactory {
public:
static TileServiceFactory* GetInstance();
static TileService* GetForKey(SimpleFactoryKey* key);
TileServiceFactory(const TileServiceFactory&) = delete;
TileServiceFactory& operator=(const TileServiceFactory&) = delete;
private:
friend struct base::DefaultSingletonTraits<TileServiceFactory>;
TileServiceFactory();
~TileServiceFactory() override;
std::unique_ptr<KeyedService> BuildServiceInstanceFor(
SimpleFactoryKey* key) const override;
};
} // namespace query_tiles
#endif // CHROME_BROWSER_QUERY_TILES_TILE_SERVICE_FACTORY_H_
| {
"content_hash": "e076878fb601f6d904b1c1832723da4d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 68,
"avg_line_length": 26.35483870967742,
"alnum_prop": 0.7784577723378213,
"repo_name": "nwjs/chromium.src",
"id": "c893bfdcf81c8bac6fcbf16f744e7d3d1f747a1a",
"size": "1221",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "chrome/browser/query_tiles/tile_service_factory.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"use strict";
import { EC } from "./elliptic";
import { arrayify, hexDataLength, hexlify, hexZeroPad, splitSignature } from "@ethersproject/bytes";
import { defineReadOnly } from "@ethersproject/properties";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
let _curve = null;
function getCurve() {
if (!_curve) {
_curve = new EC("secp256k1");
}
return _curve;
}
export class SigningKey {
constructor(privateKey) {
defineReadOnly(this, "curve", "secp256k1");
defineReadOnly(this, "privateKey", hexlify(privateKey));
if (hexDataLength(this.privateKey) !== 32) {
logger.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]");
}
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
defineReadOnly(this, "publicKey", "0x" + keyPair.getPublic(false, "hex"));
defineReadOnly(this, "compressedPublicKey", "0x" + keyPair.getPublic(true, "hex"));
defineReadOnly(this, "_isSigningKey", true);
}
_addPoint(other) {
const p0 = getCurve().keyFromPublic(arrayify(this.publicKey));
const p1 = getCurve().keyFromPublic(arrayify(other));
return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex");
}
signDigest(digest) {
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
const digestBytes = arrayify(digest);
if (digestBytes.length !== 32) {
logger.throwArgumentError("bad digest length", "digest", digest);
}
const signature = keyPair.sign(digestBytes, { canonical: true });
return splitSignature({
recoveryParam: signature.recoveryParam,
r: hexZeroPad("0x" + signature.r.toString(16), 32),
s: hexZeroPad("0x" + signature.s.toString(16), 32),
});
}
computeSharedSecret(otherKey) {
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey)));
return hexZeroPad("0x" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32);
}
static isSigningKey(value) {
return !!(value && value._isSigningKey);
}
}
export function recoverPublicKey(digest, signature) {
const sig = splitSignature(signature);
const rs = { r: arrayify(sig.r), s: arrayify(sig.s) };
return "0x" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode("hex", false);
}
export function computePublicKey(key, compressed) {
const bytes = arrayify(key);
if (bytes.length === 32) {
const signingKey = new SigningKey(bytes);
if (compressed) {
return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex");
}
return signingKey.publicKey;
}
else if (bytes.length === 33) {
if (compressed) {
return hexlify(bytes);
}
return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex");
}
else if (bytes.length === 65) {
if (!compressed) {
return hexlify(bytes);
}
return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex");
}
return logger.throwArgumentError("invalid public or private key", "key", "[REDACTED]");
}
//# sourceMappingURL=index.js.map | {
"content_hash": "e95f9a50ccf70aa58712943b1f040a80",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 105,
"avg_line_length": 41.53658536585366,
"alnum_prop": 0.6327069876688197,
"repo_name": "ethers-io/ethers.js",
"id": "6a54045d97bc010d81542119e698bf680bdbf0cf",
"size": "3406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/signing-key/lib.esm/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3638"
},
{
"name": "Java",
"bytes": "6255"
},
{
"name": "JavaScript",
"bytes": "400367"
},
{
"name": "Objective-C",
"bytes": "4451"
},
{
"name": "Python",
"bytes": "8828"
},
{
"name": "Ruby",
"bytes": "817"
},
{
"name": "Shell",
"bytes": "840"
},
{
"name": "Solidity",
"bytes": "3691"
},
{
"name": "Starlark",
"bytes": "602"
},
{
"name": "TypeScript",
"bytes": "1208900"
},
{
"name": "Yacc",
"bytes": "6161"
}
],
"symlink_target": ""
} |
package ca.uhn.fhir.rest.client;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum;
import ca.uhn.fhir.util.TestUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicStatusLine;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ClientWithCustomTypeDstu2_1Test {
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ClientWithCustomTypeDstu2_1Test.class);
private HttpClient myHttpClient;
private HttpResponse myHttpResponse;
@AfterAll
public static void afterClassClearContext() {
TestUtil.randomizeLocaleAndTimezone();
}
@BeforeEach
public void before() {
myHttpClient = mock(HttpClient.class, new ReturnsDeepStubs());
ourCtx.getRestfulClientFactory().setHttpClient(myHttpClient);
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
myHttpResponse = mock(HttpResponse.class, new ReturnsDeepStubs());
}
private byte[] extractBodyAsByteArray(ArgumentCaptor<HttpUriRequest> capt) throws IOException {
byte[] body = IOUtils.toByteArray(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(0)).getEntity().getContent());
return body;
}
private String extractBodyAsString(ArgumentCaptor<HttpUriRequest> capt) throws IOException {
String body = IOUtils.toString(((HttpEntityEnclosingRequestBase) capt.getAllValues().get(0)).getEntity().getContent(), "UTF-8");
return body;
}
@Test
public void testReadCustomType() throws Exception {
IParser p = ourCtx.newXmlParser();
MyPatientWithExtensions response = new MyPatientWithExtensions();
response.addName().addFamily("FAMILY");
response.getStringExt().setValue("STRINGVAL");
response.getDateExt().setValueAsString("2011-01-02");
final String respString = p.encodeResourceToString(response);
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
//@formatter:off
MyPatientWithExtensions value = client
.read()
.resource(MyPatientWithExtensions.class)
.withId("123")
.execute();
//@formatter:on
HttpUriRequest request = capt.getAllValues().get(0);
assertEquals("http://example.com/fhir/Patient/123", request.getURI().toASCIIString());
assertEquals("GET", request.getMethod());
assertEquals(1, value.getName().size());
assertEquals("FAMILY", value.getName().get(0).getFamilyAsSingleString());
assertEquals("STRINGVAL", value.getStringExt().getValue());
assertEquals("2011-01-02", value.getDateExt().getValueAsString());
}
@BeforeAll
public static void beforeClass() {
ourCtx = FhirContext.forDstu2_1();
}
}
| {
"content_hash": "7d198f0ecb7065d85c7d692bf6b37629",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 139,
"avg_line_length": 37.78448275862069,
"alnum_prop": 0.7855350216746521,
"repo_name": "aemay2/hapi-fhir",
"id": "1abc8072a1471cf62c5086f8d752aba9b5a29415",
"size": "4383",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hapi-fhir-structures-dstu2.1/src/test/java/ca/uhn/fhir/rest/client/ClientWithCustomTypeDstu2_1Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3861"
},
{
"name": "CSS",
"bytes": "9608"
},
{
"name": "HTML",
"bytes": "213468"
},
{
"name": "Java",
"bytes": "25723741"
},
{
"name": "JavaScript",
"bytes": "31583"
},
{
"name": "Kotlin",
"bytes": "3951"
},
{
"name": "Ruby",
"bytes": "230677"
},
{
"name": "Shell",
"bytes": "46167"
}
],
"symlink_target": ""
} |
var spawned = require('../');
spawned('echo', ['test'])
.then(function(proc) {
console.log("Did it work? " + ((proc.out.match(/test/))? "yes" : "no"));
}).catch(function(err) {
console.log("Boooooom");
console.error(err.err);
}); | {
"content_hash": "f4a09bdfa1c2dc89612b7db68dc0fa98",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 76,
"avg_line_length": 27.555555555555557,
"alnum_prop": 0.5645161290322581,
"repo_name": "mariocasciaro/spawned",
"id": "e6917efa4b055e1697d57dc92605b5135120e114",
"size": "249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/echo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3219"
}
],
"symlink_target": ""
} |
Edit the file form sub branch
| {
"content_hash": "a1567a7cb68cc6eeacd79dc129a83e91",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 29,
"avg_line_length": 30,
"alnum_prop": 0.8,
"repo_name": "bzaman-tk/hello-world",
"id": "981cb351083545e5f62c623427d5812501349c39",
"size": "44",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef _DT_BINDINGS_PINCTRL_TEGRA_H
#define _DT_BINDINGS_PINCTRL_TEGRA_H
/*
* Enable/disable for diffeent dt properties. This is applicable for
* properties nvidia,enable-input, nvidia,tristate, nvidia,open-drain,
* nvidia,lock, nvidia,rcv-sel, nvidia,high-speed-mode, nvidia,schmitt.
*/
#define TEGRA_PIN_DISABLE 0
#define TEGRA_PIN_ENABLE 1
#define TEGRA_PIN_PULL_NONE 0
#define TEGRA_PIN_PULL_DOWN 1
#define TEGRA_PIN_PULL_UP 2
/* Low power mode driver */
#define TEGRA_PIN_LP_DRIVE_DIV_8 0
#define TEGRA_PIN_LP_DRIVE_DIV_4 1
#define TEGRA_PIN_LP_DRIVE_DIV_2 2
#define TEGRA_PIN_LP_DRIVE_DIV_1 3
/* Rising/Falling slew rate */
#define TEGRA_PIN_SLEW_RATE_FASTEST 0
#define TEGRA_PIN_SLEW_RATE_FAST 1
#define TEGRA_PIN_SLEW_RATE_SLOW 2
#define TEGRA_PIN_SLEW_RATE_SLOWEST 3
#endif
| {
"content_hash": "f06067687fd28443b2fc6479ce25dc5d",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 71,
"avg_line_length": 27.533333333333335,
"alnum_prop": 0.7203389830508474,
"repo_name": "mikedlowis-prototypes/albase",
"id": "ebafa498be0ff7425eb13d68f173d1b228f0a346",
"size": "1466",
"binary": false,
"copies": "2525",
"ref": "refs/heads/master",
"path": "source/kernel/include/dt-bindings/pinctrl/pinctrl-tegra.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "10263145"
},
{
"name": "Awk",
"bytes": "55187"
},
{
"name": "Batchfile",
"bytes": "31438"
},
{
"name": "C",
"bytes": "551654518"
},
{
"name": "C++",
"bytes": "11818066"
},
{
"name": "CMake",
"bytes": "122998"
},
{
"name": "Clojure",
"bytes": "945"
},
{
"name": "DIGITAL Command Language",
"bytes": "232099"
},
{
"name": "GDB",
"bytes": "18113"
},
{
"name": "Gherkin",
"bytes": "5110"
},
{
"name": "HTML",
"bytes": "18291"
},
{
"name": "Lex",
"bytes": "58937"
},
{
"name": "M4",
"bytes": "561745"
},
{
"name": "Makefile",
"bytes": "7082768"
},
{
"name": "Objective-C",
"bytes": "634652"
},
{
"name": "POV-Ray SDL",
"bytes": "546"
},
{
"name": "Perl",
"bytes": "1229221"
},
{
"name": "Perl6",
"bytes": "11648"
},
{
"name": "Python",
"bytes": "316536"
},
{
"name": "Roff",
"bytes": "4201130"
},
{
"name": "Shell",
"bytes": "2436879"
},
{
"name": "SourcePawn",
"bytes": "2711"
},
{
"name": "TeX",
"bytes": "182745"
},
{
"name": "UnrealScript",
"bytes": "12824"
},
{
"name": "Visual Basic",
"bytes": "11568"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "146537"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.