text:
set -e -x

# Logger
exec > >(tee /var/log/user-data_3rd-bootstrap.log || logger -t user-data -s 2> /dev/console) 2>&1

#-------------------------------------------------------------------------------
# Set UserData Parameter
#-------------------------------------------------------------------------------

if [ -f /tmp/userdata-parameter ]; then
    source /tmp/userdata-parameter
fi

if [[ -z "${Language}" || -z "${Timezone}" || -z "${VpcNetwork}" ]]; then
    # Default Language
	Language="en_US.UTF-8"
    # Default Timezone
	Timezone="Asia/Tokyo"
	# Default VPC Network
	VpcNetwork="IPv4"
fi

# echo
echo $Language
echo $Timezone
echo $VpcNetwork

#-------------------------------------------------------------------------------
# Parameter Settings
#-------------------------------------------------------------------------------

# Parameter Settings
CWAgentConfig="https://raw.githubusercontent.com/usui-tk/amazon-ec2-userdata/master/Config_AmazonCloudWatchAgent/AmazonCloudWatchAgent_OracleLinux-v8-HVM.json"

#-------------------------------------------------------------------------------
# Acquire unique information of Linux distribution
#  - Oracle Linux v8
#    https://www.oracle.com/technetwork/server-storage/linux/documentation/index.html
#    https://docs.oracle.com/en/operating-systems/oracle-linux/8/
#    http://yum.oracle.com/oracle-linux-8.html
#    https://github.com/oracle/oracle-linux
#
#-------------------------------------------------------------------------------

# Cleanup repository information
dnf --enablerepo="*" --verbose clean all

# Show Linux Distribution/Distro information
if [ $(command -v lsb_release) ]; then
    lsb_release -a
fi

# Show Linux System Information
uname -a

# Show Linux distribution release Information
cat /etc/os-release

cat /etc/redhat-release

# Default installation package [rpm command]
rpm -qa --qf="%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" | sort > /tmp/command-log_rpm_installed-package.txt

# Default installation package [dnf command]
dnf list installed > /tmp/command-log_dnf_installed-package.txt

# Default repository package [dnf command]
dnf list all > /tmp/command-log_dnf_repository-package-list.txt

# Default repository package group [dnf command]
dnf group list -v > /tmp/command-log_dnf_repository-package-group-list.txt

# Default repository list [dnf command]
dnf repolist all > /tmp/command-log_dnf_repository-list.txt

# Default repository module [dnf command]
dnf module list > /tmp/command-log_dnf_module-list.txt

# systemd unit files
systemctl list-unit-files --all --no-pager > /tmp/command-log_systemctl_list-unit-files.txt

# systemd service config
systemctl list-units --type=service --all --no-pager > /tmp/command-log_systemctl_list-service-config.txt

#-------------------------------------------------------------------------------
# Default Package Update
#-------------------------------------------------------------------------------
# Yum Repositories (Oracle Linux v8)
#  http://yum.oracle.com/oracle-linux-8.html
#-------------------------------------------------------------------------------

# Cleanup repository information and Update dnf tools
dnf --enablerepo="*" --verbose clean all
dnf update -y dnf dnf-data

# Checking repository information
dnf repolist all
dnf module list

# Package Install Oracle Linux yum repository Files (from Oracle Linux Repository)
find /etc/yum.repos.d/

dnf list *release-el8

dnf install -y oraclelinux-release-el8 oracle-epel-release-el8 oraclelinux-automation-manager-release-el8 oracle-instantclient-release-el8 oracle-olcne-release-el8 oracle-software-release-el8 oraclelinux-developer-release-el8
dnf --enablerepo="*" --verbose clean all

find /etc/yum.repos.d/

# Check the OCI variables to be used in YUM
if [ -f /etc/yum/vars/ociregion ]; then
	cat /etc/yum/vars/ociregion
fi

if [ -f /etc/yum/vars/ocidomain ]; then
	cat /etc/yum/vars/ocidomain
fi

# Cleanup repository information
dnf --enablerepo="*" --verbose clean all

# Checking repository information
dnf repolist all
dnf module list

# Enable Yum Repository Data from Oracle Linux YUM repository (yum.oracle.com)
dnf config-manager --set-enabled ol8_baseos_latest
dnf config-manager --set-enabled ol8_UEKR7
dnf config-manager --set-enabled ol8_appstream
dnf config-manager --set-enabled ol8_addons
dnf config-manager --set-enabled ol8_codeready_builder
dnf config-manager --set-enabled ol8_automation
dnf config-manager --set-enabled ol8_oracle_software
dnf config-manager --set-enabled ol8_oracle_instantclient21
dnf config-manager --set-enabled ol8_developer
dnf config-manager --set-enabled ol8_olcne15

# Disable Yum Repository Data from Oracle Linux YUM repository (yum.oracle.com)
dnf config-manager --set-disabled ol8_UEKR6
dnf config-manager --set-disabled ol8_olcne12
dnf config-manager --set-disabled ol8_olcne13
dnf config-manager --set-disabled ol8_olcne14
dnf config-manager --set-disabled ol8_kvm_appstream
dnf config-manager --set-disabled ol8_developer_EPEL
dnf config-manager --set-disabled ol8_developer_EPEL_modular
dnf config-manager --set-disabled ol8_developer_UEKR6
dnf config-manager --set-disabled ol8_distro_builder

# Cleanup repository information
dnf --enablerepo="*" --verbose clean all

# Checking repository information
dnf repolist all
dnf module list

# Get Dnf/Yum Repository List (Exclude Dnf/Yum repository related to "BaseOS GA (x86_64), BaseOS (x86_64)")
repolist=$(dnf repolist all --quiet | grep -ie "enabled" -ie "disabled" | grep -ve "BaseOS GA (x86_64)" -ve "BaseOS (x86_64)" | awk '{print $1}' | awk '{ sub("/.*$",""); print $0; }' | sort)

# Oracle Linux YUM repository package [dnf command]
for repo in $repolist
do
	echo "[Target repository Name (Collect dnf/yum repository package list)] :" $repo
	dnf repository-packages ${repo} list > /tmp/command-log_dnf_repository-package-list_${repo}.txt
	sleep 3
done

# Default Package Update
dnf update -y

# Switching Linux-kernel packages (Switch from RHEL compatible kernel to Unbreakable Enterprise Kernel)
# https://docs.oracle.com/en/operating-systems/uek/7/relnotes7.0/index.html

if [ $(grubby --default-kernel | grep -ie "el8uek") ]; then
	echo "Linux Kernel Package Name : kernel-uek"
else
	echo "Linux Kernel Package Name : kernel"
	dnf install -y kernel-uek kernel-uek-devel
fi

#-------------------------------------------------------------------------------
# Custom Package Installation
#-------------------------------------------------------------------------------

# Package Install Oracle Linux Linux-Kernel Modules (from Oracle Linux Repository)
if [ $(grubby --default-kernel | grep -ie "el8uek") ]; then
	echo "Linux Kernel Package Name : kernel-uek"
	dnf install -y kernel-uek-modules kernel-uek-modules-extra
else
	echo "Linux Kernel Package Name : kernel"
	dnf install -y kernel-modules kernel-modules-extra
fi

# Package Install Oracle Linux System Administration Tools (from Oracle Linux Repository)
dnf install -y abrt abrt-cli acpid arptables bash-completion bc bcc bcc-tools bind-utils blktrace bpftool bpftrace crash-trace-command crypto-policies curl dnf-data dnf-plugins-core dnf-utils dstat ebtables ethtool expect fio gdisk git gnutls-utils hdparm intltool iotop ipcalc iperf3 iproute-tc ipset iptraf-ng jq kexec-tools libicu linuxptp lsof lvm2 lzop man-pages mc mcelog mdadm mlocate mtr nc ncompress net-snmp-utils net-tools nftables nmap nmap-ncat nmstate numactl nvme-cli nvmetcli parted patchutils pmempool psacct psmisc python3-dnf-plugin-versionlock rsync smartmontools sos sos-audit stalld strace symlinks sysfsutils sysstat tcpdump time tlog tmpwatch traceroute tree tzdata unzip usermode util-linux util-linux-user vdo vim-enhanced wget wireshark-cli xfsdump xfsprogs yum-utils zip zsh zstd
dnf install -y cifs-utils nfs-utils nfs4-acl-tools
dnf install -y iscsi-initiator-utils lsscsi sg3_utils stratisd stratis-cli
dnf install -y "selinux-policy*" checkpolicy policycoreutils policycoreutils-python-utils policycoreutils-restorecond setools-console setools-console-analyses setroubleshoot-server udica
dnf install -y pcp pcp-export-pcp2json pcp-manager "pcp-pmda*" pcp-selinux pcp-system-tools pcp-zeroconf

# Package Install Oracle Linux support tools (from Oracle Linux Repository)
dnf install -y redhat-lsb-core

# Package Install Oracle Linux Cleanup tools (from Oracle Linux Repository)
# dnf install -y ovm-template-config*

# Package Install Oracle Linux Cloud Native Environment (from Oracle Linux Repository)
dnf install -y olcne-selinux olcne-utils olcnectl yq

#-------------------------------------------------------------------------------
# Custom Package Installation [kernel live-patching tools]
# https://access.redhat.com/solutions/2206511
# https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/managing_monitoring_and_updating_the_kernel/applying-patches-with-kernel-live-patching_managing-monitoring-and-updating-the-kernel
#-------------------------------------------------------------------------------

# Package Install Oracle Linux kernel live-patching tools (from Oracle Linux Repository)
# dnf install -y kpatch kpatch-dnf

# rpm -qi kpatch

# systemctl daemon-reload

# systemctl restart kpatch

# systemctl status -l kpatch

# Configure kpatch software (Start Daemon kpatch)
# if [ $(systemctl is-enabled kpatch) = "disabled" ]; then
# 	systemctl enable kpatch
# 	systemctl is-enabled kpatch
# fi

# kpatch information
# kpatch list

# Package List (kernel live-patch)
# dnf list installed | grep kpatch

#-------------------------------------------------------------------------------
# Custom Package Installation [Cockpit]
# https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/managing_systems_using_the_rhel_8_web_console/index
#-------------------------------------------------------------------------------

# Package Install Oracle Linux Web-Based support tools (from Oracle Linux Repository)
dnf install -y cockpit cockpit-dashboard cockpit-packagekit cockpit-session-recording cockpit-storaged cockpit-system cockpit-ws

rpm -qi cockpit

systemctl daemon-reload

systemctl restart cockpit

systemctl status -l cockpit

# Configure cockpit.socket
if [ $(systemctl is-enabled cockpit.socket) = "disabled" ]; then
	systemctl enable --now cockpit.socket
	systemctl is-enabled cockpit.socket
fi

#-------------------------------------------------------------------------------
# Custom Package Installation [Python 3.6]
#-------------------------------------------------------------------------------

# DNF-Module Enable Python 3.6 Runtime (from Oracle Linux Repository)
dnf module list | grep python3
dnf install -y @python36
dnf module list | grep python3

# Package Install Python 3.6 Runtime (from Oracle Linux Repository)
dnf install -y python3 python3-pip python3-rpm-generators python3-rpm-macros python3-setuptools python3-test python3-virtualenv python3-wheel
dnf install -y python3-asn1crypto python3-dateutil python3-docutils python3-humanize python3-jmespath python3-pyasn1 python3-pyasn1-modules python3-pyyaml python3-six python3-urllib3
dnf install -y python3-argcomplete

# Version Information (Python 3.6)
python3 -V
pip3 -V

# Python package introduction and setting
alternatives --list
alternatives --set python "/usr/bin/python3"
alternatives --list

which python
python --version

# Python package setting (python3-argcomplete)
activate-global-python-argcomplete

#-------------------------------------------------------------------------------
# Custom Package Installation [Python 3.9]
#-------------------------------------------------------------------------------

# DNF-Module Enable Python 3.9 Runtime (from Oracle Linux Repository)
# dnf module list | grep python3
# dnf install -y @python39
# dnf module list | grep python3

# Package Install Python 3.9 Runtime (from Oracle Linux Repository)
# dnf install -y python39 python39-devel python39-pip python39-rpm-macros python39-setuptools python39-test python39-wheel
# dnf install -y python39-pyyaml python39-six python39-urllib3

# Version Information (Python 3.9)
# python3.9 -V
# pip3.9 -V

#-------------------------------------------------------------------------------
# Custom Package Installation [EPEL]
#-------------------------------------------------------------------------------

# Package Install EPEL(Extra Packages for Enterprise Linux) Repository Package
# dnf localinstall -y "https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm"

# Cleanup repository information
dnf --enablerepo="*" --verbose clean all

# EPEL repository package [dnf command]
dnf repository-packages "ol8_developer_EPEL" list > /tmp/command-log_dnf_repository-package-list_ol8_developer_EPEL.txt
dnf repository-packages "ol8_developer_EPEL_modular" list > /tmp/command-log_dnf_repository-package-list_ol8_developer_EPEL_modular.txt

# Package Install Oracle Linux System Administration Tools (from EPEL Repository)
dnf --enablerepo="ol8_developer_EPEL","ol8_developer_EPEL_modular" install -y atop bcftools bpytop byobu collectd collectd-utils colordiff dateutils fping glances htop httping iftop inotify-tools inxi ipv6calc moreutils moreutils-parallel ncdu nload screen srm stressapptest tcping unicornscan wdiff yamllint

# Package Install EC2 instance optimization tools (from EPEL Repository)
dnf --enablerepo="ol8_developer_EPEL","ol8_developer_EPEL_modular" install -y ec2-hibinit-agent

# Package Install Oracle Linux System Administration Tools (from EPEL-Playground Repository)
# dnf --enablerepo="ol8_developer_EPEL" install -y jnettop wdiff

#-------------------------------------------------------------------------------
# Custom Package Installation [Oracle Software Product]
#-------------------------------------------------------------------------------

# Package Install Oracle Database Utility (from Oracle Linux Repository)
# dnf install -y kmod-redhat-oracleasm oracleasm-support ocfs2-tools
dnf install -y oracleasm-support ocfs2-tools
dnf install -y pcp-oracle-conf

# Package Install Oracle Database Developer Tool (from Oracle Linux Repository)
# yum install -y ords sqlcl

# Package Install Oracle Database Pre-Installation Tools (from Oracle Linux Repository)
# dnf install -y oracle-database-preinstall-19c
dnf install -y oracle-database-preinstall-21c

# Package Install Oracle E-Business Suite Pre-Installation Tools (from Oracle Linux Repository)
# dnf install -y oracle-ebs-server-R12-preinstall

# Package Install Oracle Instant Client (from Oracle Linux Repository)
# https://yum.oracle.com/oracle-instant-client.html
dnf --disablerepo="*" --enablerepo="ol8_oracle_instantclient21" install -y oracle-instantclient-basic oracle-instantclient-devel oracle-instantclient-jdbc oracle-instantclient-sqlplus oracle-instantclient-tools

#-------------------------------------------------------------------------------
# Get AWS Instance MetaData Service (IMDS v1, v2)
# https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
# https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
#-------------------------------------------------------------------------------

# Getting an Instance Metadata Service v2 (IMDS v2) token
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`

if [ -n "$TOKEN" ]; then
	#-----------------------------------------------------------------------
	# Retrieving Metadata Using the Instance Metadata Service v2 (IMDS v2)
	#-----------------------------------------------------------------------

	# Instance MetaData
	Az=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/placement/availability-zone")
	AzId=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/placement/availability-zone-id")
	Region=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/placement/region")
	InstanceId=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/instance-id")
	InstanceType=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/instance-type")
	PrivateIp=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/local-ipv4")
	AmiId=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/ami-id")

	# IAM Role & STS Information
	if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
		RoleArn=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/iam/info" | jq -r '.InstanceProfileArn')
		RoleName=$(echo $RoleArn | cut -d '/' -f 2)
	fi

	if [ -n "$RoleName" ]; then
		StsCredential=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/meta-data/iam/security-credentials/$RoleName")
		if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
			StsAccessKeyId=$(echo $StsCredential | jq -r '.AccessKeyId')
			StsSecretAccessKey=$(echo $StsCredential | jq -r '.SecretAccessKey')
			StsToken=$(echo $StsCredential | jq -r '.Token')
		fi
	fi

	# AWS Account ID
	if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
		AwsAccountId=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s "http://169.254.169.254/latest/dynamic/instance-identity/document" | jq -r '.accountId')
	fi

else
	#-----------------------------------------------------------------------
	# Retrieving Metadata Using the Instance Metadata Service v1 (IMDS v1)
	#-----------------------------------------------------------------------

	# Instance MetaData
	Az=$(curl -s "http://169.254.169.254/latest/meta-data/placement/availability-zone")
	AzId=$(curl -s "http://169.254.169.254/latest/meta-data/placement/availability-zone-id")
	Region=$(curl -s "http://169.254.169.254/latest/meta-data/placement/region")
	InstanceId=$(curl -s "http://169.254.169.254/latest/meta-data/instance-id")
	InstanceType=$(curl -s "http://169.254.169.254/latest/meta-data/instance-type")
	PrivateIp=$(curl -s "http://169.254.169.254/latest/meta-data/local-ipv4")
	AmiId=$(curl -s "http://169.254.169.254/latest/meta-data/ami-id")

	# IAM Role & STS Information
	if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
		RoleArn=$(curl -s "http://169.254.169.254/latest/meta-data/iam/info" | jq -r '.InstanceProfileArn')
		RoleName=$(echo $RoleArn | cut -d '/' -f 2)
	fi

	if [ -n "$RoleName" ]; then
		StsCredential=$(curl -s "http://169.254.169.254/latest/meta-data/iam/security-credentials/$RoleName")
		if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
			StsAccessKeyId=$(echo $StsCredential | jq -r '.AccessKeyId')
			StsSecretAccessKey=$(echo $StsCredential | jq -r '.SecretAccessKey')
			StsToken=$(echo $StsCredential | jq -r '.Token')
		fi
	fi

	# AWS Account ID
	if [ $(compgen -ac | sort | uniq | grep -x jq) ]; then
		AwsAccountId=$(curl -s "http://169.254.169.254/latest/dynamic/instance-identity/document" | jq -r '.accountId')
	fi

fi

#-------------------------------------------------------------------------------
# Custom Package Installation [AWS-CLI v2]
# https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html
#-------------------------------------------------------------------------------

# Package download AWS-CLI v2 Tools (from Bundle Installer)
curl -sS "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "/tmp/awscliv2.zip"
unzip -oq "/tmp/awscliv2.zip" -d /tmp/

# Package Install AWS-CLI v2 Tools (from Bundle Installer)
/tmp/aws/install -i "/opt/aws/awscli" -b "/usr/bin" --update

aws --version

# Configuration AWS-CLI tools
cat > /etc/bash_completion.d/aws_bash_completer << __EOF__
# Typically that would be added under one of the following paths:
# - /etc/bash_completion.d
# - /usr/local/etc/bash_completion.d
# - /usr/share/bash-completion/completions

complete -C aws_completer aws
__EOF__

# Setting AWS-CLI default Region & Output format
aws configure << __EOF__

${Region}
json

__EOF__

# Setting AWS-CLI Logging
aws configure set cli_history enabled

# Setting AWS-CLI Pager settings
aws configure set cli_pager ''

# Getting AWS-CLI default Region & Output format
aws configure list
cat ~/.aws/config

# Get AWS Region Information
if [ -n "$RoleName" ]; then
	echo "# Get AWS Region Infomation"
	aws ec2 describe-regions --region ${Region}
fi

# Get AMI information of this EC2 instance
if [ -n "$RoleName" ]; then
	echo "# Get AMI information of this EC2 instance"
	aws ec2 describe-images --image-ids ${AmiId} --output json --region ${Region}
fi

# Get the latest AMI information of the OS type of this EC2 instance from Public AMI
if [ -n "$RoleName" ]; then
	echo "# Get Newest AMI Information from Public AMI"
	NewestAmiInfo=$(aws ec2 describe-images --owner "131827586825" --filter "Name=name,Values=OL8.*" "Name=virtualization-type,Values=hvm" "Name=architecture,Values=x86_64" --query 'sort_by(Images[].{YMD:CreationDate,Name:Name,ImageId:ImageId},&YMD)|reverse(@)|[0]' --output json --region ${Region})
	NewestAmiId=$(echo $NewestAmiInfo| jq -r '.ImageId')
	aws ec2 describe-images --image-ids ${NewestAmiId} --output json --region ${Region}
fi

# Get EC2 Instance Information
if [ -n "$RoleName" ]; then
	echo "# Get EC2 Instance Information"
	aws ec2 describe-instances --instance-ids ${InstanceId} --output json --region ${Region}
fi

# Get EC2 Instance attached EBS Volume Information
if [ -n "$RoleName" ]; then
	echo "# Get EC2 Instance attached EBS Volume Information"
	aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=${InstanceId} --output json --region ${Region}
fi

# Get EC2 Instance attached VPC Security Group Information
if [ -n "$RoleName" ]; then
	echo "# Get EC2 Instance attached VPC Security Group Information"
	aws ec2 describe-security-groups --group-ids $(aws ec2 describe-instances --instance-id ${InstanceId} --query "Reservations[].Instances[].SecurityGroups[].GroupId[]" --output text --region ${Region}) --output json --region ${Region}
fi

# Get EC2 Instance Attribute[Network Interface Performance Attribute]
#
# - Summary of Networking and Storage Features
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#instance-type-summary-table
# - ENA (Elastic Network Adapter)
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html
# - SR-IOV
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sriov-networking.html
#
if [ -n "$RoleName" ]; then
	if [[ "$InstanceType" =~ ^(a1.*|c5.*|c5a.*|c5ad.*|c5adn.*|c5an.*|c5d.*|c5n.*|e3.*|f1.*|g3.*|g3s.*|g4dn.*|h1.*|i3.*|i3en.*|i3p.*|m5.*|m5a.*|m5ad.*|m5d.*|m5dn.*|m5n.*|p2.*|p3.*|p3dn.*|r4.*|r5.*|r5a.*|r5ad.*|r5d.*|r5dn.*|r5n.*|t3.*|t3a.*|x1.*|x1e.*|z1d.*|m4.16xlarge|u-*tb1.metal)$ ]]; then
		# Get EC2 Instance Attribute(Elastic Network Adapter Status)
		echo "# Get EC2 Instance Attribute(Elastic Network Adapter Status)"
		aws ec2 describe-instances --instance-id ${InstanceId} --query Reservations[].Instances[].EnaSupport --output json --region ${Region}

		# Get Linux Kernel Module(modinfo ena)
		echo "# Get Linux Kernel Module(modinfo ena)"
		if [ $(lsmod | awk '{print $1}' | grep -x ena) ]; then
			modinfo ena
		fi
	elif [[ "$InstanceType" =~ ^(c3.*|c4.*|d2.*|i2.*|r3.*|m4.*)$ ]]; then
		# Get EC2 Instance Attribute(Single Root I/O Virtualization Status)
		echo "# Get EC2 Instance Attribute(Single Root I/O Virtualization Status)"
		aws ec2 describe-instance-attribute --instance-id ${InstanceId} --attribute sriovNetSupport --output json --region ${Region}

		# Get Linux Kernel Module(modinfo ixgbevf)
		echo "# Get Linux Kernel Module(modinfo ixgbevf)"
		if [ $(lsmod | awk '{print $1}' | grep -x ixgbevf) ]; then
			modinfo ixgbevf
		fi
	else
		echo "# Not Target Instance Type :" $InstanceType
	fi
fi

# Get EC2 Instance Attribute[Storage Interface Performance Attribute]
#
# - Summary of Networking and Storage Features
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#instance-type-summary-table
# - EBS Optimized Instance
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSPerformance.html
#
if [ -n "$RoleName" ]; then
	if [[ "$InstanceType" =~ ^(a1.*|c1.*|c3.*|c4.*|c5.*|c5a.*|c5ad.*|c5adn.*|c5an.*|c5d.*|c5n.*|d2.*|e3.*|f1.*|g2.*|g3.*|g3s.*|g4dn.*|h1.*|i2.*|i3.*|i3en.*|i3p.*|m1.*|m2.*|m3.*|m4.*|m5.*|m5a.*|m5ad.*|m5d.*|m5dn.*|m5n.*|p2.*|p3.*|p3dn.*|r3.*|r4.*|r5.*|r5a.*|r5ad.*|r5d.*|r5dn.*|r5n.*|t3.*|t3a.*|x1.*|x1e.*|z1d.*|u-*tb1.metal)$ ]]; then
		# Get EC2 Instance Attribute(EBS-optimized instance Status)
		echo "# Get EC2 Instance Attribute(EBS-optimized instance Status)"
		aws ec2 describe-instance-attribute --instance-id ${InstanceId} --attribute ebsOptimized --output json --region ${Region}

		# Get Linux Block Device Read-Ahead Value(blockdev --report)
		echo "# Get Linux Block Device Read-Ahead Value(blockdev --report)"
		blockdev --report
	else
		# Get Linux Block Device Read-Ahead Value(blockdev --report)
		echo "# Get Linux Block Device Read-Ahead Value(blockdev --report)"
		blockdev --report
	fi
fi

# Get EC2 Instance attached NVMe Device Information
#
# - Summary of Networking and Storage Features
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#instance-type-summary-table
#
# - Nitro-based Instances
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances
# - Amazon EBS and NVMe Volumes
#   http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nvme-ebs-volumes.html
# - SSD Instance Store Volumes
#   https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ssd-instance-store.html
#
if [ -n "$RoleName" ]; then
	if [[ "$InstanceType" =~ ^(a1.*|c5.*|c5a.*|c5ad.*|c5adn.*|c5an.*|c5d.*|c5n.*|f1.*|g4dn.*|i3.*|i3en.*|i3p.*|m5.*|m5a.*|m5ad.*|m5d.*|m5dn.*|m5n.*|p3dn.*|r5.*|r5a.*|r5ad.*|r5d.*|r5dn.*|r5n.*|t3.*|t3a.*|z1d.*|u-*tb1.metal)$ ]]; then

		# Get Linux Kernel Module(modinfo nvme)
		echo "# Get Linux Kernel Module(modinfo nvme)"
		if [ $(lsmod | awk '{print $1}' | grep -x nvme) ]; then
			modinfo nvme
		fi

		# Get NVMe Device(nvme list)
		# http://www.spdk.io/doc/nvme-cli.html
		# https://github.com/linux-nvme/nvme-cli
		if [ $(lsmod | awk '{print $1}' | grep -x nvme) ]; then
			if [ $(command -v nvme) ]; then
				echo "# Get NVMe Device(nvme list)"
				nvme list
			fi
		fi

		# Get PCI-Express Device(lspci -v)
		if [ $(command -v lspci) ]; then
			echo "# Get PCI-Express Device(lspci -v)"
			lspci -v
		fi

		# Get Disk[MountPoint] Information (lsblk -a)
		if [ $(command -v lsblk) ]; then
			echo "# Get Disk[MountPoint] Information (lsblk -a)"
			lsblk -a
		fi

	else
		echo "# Not Target Instance Type :" $InstanceType
	fi
fi

#-------------------------------------------------------------------------------
# Custom Package Installation [AWS Systems Manager agent (aka SSM agent)]
# http://docs.aws.amazon.com/ja_jp/systems-manager/latest/userguide/sysman-install-ssm-agent.html
# https://github.com/aws/amazon-ssm-agent
#-------------------------------------------------------------------------------

dnf install --nogpgcheck -y "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm"

rpm -qi amazon-ssm-agent

systemctl daemon-reload

systemctl restart amazon-ssm-agent

systemctl status -l amazon-ssm-agent

# Configure AWS Systems Manager Agent software (Start Daemon awsagent)
if [ $(systemctl is-enabled amazon-ssm-agent) = "disabled" ]; then
	systemctl enable amazon-ssm-agent
	systemctl is-enabled amazon-ssm-agent
fi

ssm-cli get-instance-information

#-------------------------------------------------------------------------------
# Custom Package Install [Amazon CloudWatch Agent]
# https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/download-cloudwatch-agent-commandline.html
# https://github.com/aws/amazon-cloudwatch-agent
#-------------------------------------------------------------------------------

dnf install --nogpgcheck -y "https://s3.amazonaws.com/amazoncloudwatch-agent/oracle_linux/amd64/latest/amazon-cloudwatch-agent.rpm"

rpm -qi amazon-cloudwatch-agent

cat /opt/aws/amazon-cloudwatch-agent/bin/CWAGENT_VERSION

cat /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml

systemctl daemon-reload

# Configure Amazon CloudWatch Agent software (Start Daemon awsagent)
if [ $(systemctl is-enabled amazon-cloudwatch-agent) = "disabled" ]; then
	systemctl enable amazon-cloudwatch-agent
	systemctl is-enabled amazon-cloudwatch-agent
fi

# Configure Amazon CloudWatch Agent software (Monitor settings)
curl -sS ${CWAgentConfig} -o "/tmp/config.json"
cat "/tmp/config.json"

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/tmp/config.json -s

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a stop
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a start

systemctl status -l amazon-cloudwatch-agent

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status

# Configure Amazon CloudWatch Agent software (OpenTelemetry Collector settings)
/usr/bin/amazon-cloudwatch-agent-ctl -a fetch-config -o default -s

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status

# View Amazon CloudWatch Agent config files
cat /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml

cat /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml

#-------------------------------------------------------------------------------
# Custom Package Installation [Amazon EC2 Rescue for Linux (ec2rl)]
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Linux-Server-EC2Rescue.html
# https://github.com/awslabs/aws-ec2rescue-linux
#-------------------------------------------------------------------------------

# Package Amazon EC2 Administration Tools (from S3 Bucket)
curl -sS "https://s3.amazonaws.com/ec2rescuelinux/ec2rl-bundled.tgz" -o "/tmp/ec2rl-bundled.tgz"

mkdir -p "/opt/aws"

rm -rf /opt/aws/ec2rl*

tar -xzf "/tmp/ec2rl-bundled.tgz" -C "/opt/aws"

mv --force /opt/aws/ec2rl* "/opt/aws/ec2rl"

cat > /etc/profile.d/ec2rl.sh << __EOF__
export PATH=\$PATH:/opt/aws/ec2rl
__EOF__

source /etc/profile.d/ec2rl.sh

# Check Version
/opt/aws/ec2rl/ec2rl version

/opt/aws/ec2rl/ec2rl list

# Required Software Package
# /opt/aws/ec2rl/ec2rl software-check

# Diagnosis [dig modules]
# /opt/aws/ec2rl/ec2rl run --only-modules=dig --domain=amazon.com

#-------------------------------------------------------------------------------
# Custom Package Installation [Ansible]
#-------------------------------------------------------------------------------

# Package Install Ansible (from Oracle Linux Repository)
dnf --disablerepo="*" --enablerepo="ol8_automation*, ol8_developer" install -y ansible oci-ansible-collection
# dnf --enablerepo="ol8_developer*" install -y ansible ansible-doc oci-ansible-collection

ansible --version

ansible localhost -m setup

#-------------------------------------------------------------------------------
# Custom Package Installation [fluentd]
# https://docs.fluentd.org/installation/install-by-rpm
#-------------------------------------------------------------------------------

curl -fsSL "https://toolbelt.treasuredata.com/sh/install-redhat-td-agent4.sh" | sh

rpm -qi td-agent

systemctl daemon-reload

systemctl restart td-agent

systemctl status -l td-agent

# Configure fluentd software (Start Daemon td-agent)
if [ $(systemctl is-enabled td-agent) = "disabled" ]; then
	systemctl enable td-agent
	systemctl is-enabled td-agent
fi

# Package bundled ruby gem package information
/opt/td-agent/bin/fluent-gem list

#-------------------------------------------------------------------------------
# Custom Package Installation [Terraform]
# http://yum.oracle.com/repo/OracleLinux/OL8/developer/x86_64/index.html
#-------------------------------------------------------------------------------

# Package Install Infrastructure as Code (IaC) Tools (from Oracle Linux Repository)
dnf --enablerepo="ol8_developer" -y install terraform terraform-bundle terraform-provider-oci

rpm -qi terraform

terraform version

# Configure terraform software

## terraform -install-autocomplete
cat > /etc/profile.d/terraform.sh << __EOF__
if [ -n "\$BASH_VERSION" ]; then
   complete -C /usr/bin/terraform terraform
fi
__EOF__

source /etc/profile.d/terraform.sh

#-------------------------------------------------------------------------------
# Custom Package Clean up
#-------------------------------------------------------------------------------
dnf clean all

#-------------------------------------------------------------------------------
# System information collection
#-------------------------------------------------------------------------------

# CPU Information [cat /proc/cpuinfo]
cat /proc/cpuinfo

# CPU Information [lscpu]
lscpu

lscpu --extended

# Memory Information [cat /proc/meminfo]
cat /proc/meminfo

# Memory Information [free]
free

# Disk Information(Partition) [parted -l]
parted -l

# Disk Information(MountPoint) [lsblk -f]
lsblk -f

# Disk Information(File System) [df -khT]
df -khT

# Network Information(Network Interface) [ip addr show]
ip addr show

# Network Information(Routing Table) [ip route show]
ip route show

# Network Information(Firewall Service) [firewalld]
if [ $(command -v firewall-cmd) ]; then
    # Network Information(Firewall Service) [systemctl status -l firewalld]
    systemctl status -l firewalld
    # Network Information(Firewall Service) [firewall-cmd --list-all]
    # firewall-cmd --list-all
fi

# Linux Security Information(SELinux) [getenforce] [sestatus]
getenforce

sestatus

#-------------------------------------------------------------------------------
# Configure Amazon Time Sync Service
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html
#-------------------------------------------------------------------------------

# Configure NTP Client software (Install chrony Package)
dnf install -y chrony

rpm -qi chrony

if [ $(systemctl is-active chronyd) = "active" ]; then
	systemctl daemon-reload
	systemctl restart chronyd
	sleep 3
	systemctl status -l chronyd
else
	systemctl daemon-reload
	systemctl start chronyd
	sleep 3
	systemctl status -l chronyd
fi

# Configure NTP Client software (Start Daemon chronyd)
if [ $(systemctl is-enabled chronyd) = "disabled" ]; then
	systemctl enable chronyd
	systemctl is-enabled chronyd
fi

# Contents of the configuration file
ChronyConfigFile="/etc/chrony.conf"
cat ${ChronyConfigFile}

# Configure NTP Client software (Enable log settings in Chrony configuration file)
sed -i 's/#log measurements statistics tracking/log measurements statistics tracking/g' ${ChronyConfigFile}

# Configure NTP Client software (Activate Amazon Time Sync Service settings in the Chrony configuration file)
if [ $(cat ${ChronyConfigFile} | grep -ie "169.254.169.123" | wc -l) = "0" ]; then
	echo "NTP server (169.254.169.123) for Amazon Time Sync Service is not configured in the configuration file."

	# Configure the NTP server (169.254.169.123) for Amazon Time Sync Service in the configuration file.
	if [ $(cat ${ChronyConfigFile} | grep -ie ".pool.ntp.org" | wc -l) = "0" ]; then
		# Variables (for editing the Chrony configuration file)
		VAR_CHRONY_NUM="1"

		# Change settings (Chrony configuration file)
		sed -i "${VAR_CHRONY_NUM}"'s/^/# Use the Amazon Time Sync Service.\nserver 169.254.169.123 prefer iburst minpoll 4 maxpoll 4\n\n/' ${ChronyConfigFile}
	else
		# Variables (for editing the Chrony configuration file)
		VAR_CHRONY_STR=$(cat ${ChronyConfigFile} | grep -ie "pool" -ie "server" | tail -n 1)
		VAR_CHRONY_NUM=`expr $(grep -e "$VAR_CHRONY_STR" -n ${ChronyConfigFile} | sed -e 's/:.*//g') + 1`

		# Change settings (Chrony configuration file)
		sed -i "${VAR_CHRONY_NUM}"'s/^/\n# Use the Amazon Time Sync Service.\nserver 169.254.169.123 prefer iburst minpoll 4 maxpoll 4\n\n/' ${ChronyConfigFile}
	fi

	# Contents of the configuration file
	cat ${ChronyConfigFile}
fi

# Configure NTP Client software (Check the status of time synchronization by Chrony)
if [ $(systemctl is-active chronyd) = "active" ]; then
	systemctl daemon-reload
	systemctl restart chronyd
else
	systemctl daemon-reload
	systemctl start chronyd
fi

if [ $(command -v chronyc) ]; then
	sleep 3
	chronyc tracking
	sleep 3
	chronyc sources -v
	sleep 3
	chronyc sourcestats -v
fi

#-------------------------------------------------------------------------------
# Configure Tuned
#-------------------------------------------------------------------------------

# Package Install Tuned (from Oracle Linux Repository)
dnf install -y tuned tuned-utils tuned-profiles-oracle tuned-profiles-mssql

rpm -qi tuned

systemctl daemon-reload

systemctl restart tuned

systemctl status -l tuned

# Configure Tuned software (Start Daemon tuned)
if [ $(systemctl is-enabled tuned) = "disabled" ]; then
	systemctl enable tuned
	systemctl is-enabled tuned
fi

# Configure Tuned software (select profile - throughput-performance)
tuned-adm list

tuned-adm active
tuned-adm profile throughput-performance
tuned-adm active

#-------------------------------------------------------------------------------
# Configure ACPI daemon (Advanced Configuration and Power Interface)
#-------------------------------------------------------------------------------

# Configure ACPI daemon software (Install acpid Package)
dnf install -y acpid

rpm -qi acpid

systemctl daemon-reload

systemctl restart acpid

systemctl status -l acpid

# Configure NTP Client software (Start Daemon chronyd)
if [ $(systemctl is-enabled acpid) = "disabled" ]; then
	systemctl enable acpid
	systemctl is-enabled acpid
fi

#-------------------------------------------------------------------------------
# System Setting
#-------------------------------------------------------------------------------

# Setting SELinux permissive mode
getenforce
sestatus

cat /etc/selinux/config
sed -i 's/^SELINUX=.*/SELINUX=permissive/' /etc/selinux/config
cat /etc/selinux/config

if [ $(getenforce) = "Enforcing" ]; then
	setenforce 0
	getenforce
fi

# Setting System crypto policy (Default -> FUTURE)
update-crypto-policies --show
# update-crypto-policies --set FUTURE
# update-crypto-policies --is-applied

# Setting SystemClock and Timezone
if [ "${Timezone}" = "Asia/Tokyo" ]; then
	echo "# Setting SystemClock and Timezone -> $Timezone"
	date
	timedatectl status --all --no-pager
	timedatectl set-timezone Asia/Tokyo
	timedatectl status --all --no-pager
	date
elif [ "${Timezone}" = "UTC" ]; then
	echo "# Setting SystemClock and Timezone -> $Timezone"
	date
	timedatectl status --all --no-pager
	timedatectl set-timezone UTC
	timedatectl status --all --no-pager
	date
else
	echo "# Default SystemClock and Timezone"
	timedatectl status --all --no-pager
	date
fi

# Setting System Language
if [ "${Language}" = "ja_JP.UTF-8" ]; then
	# Custom Package Installation
	dnf install -y langpacks-ja glibc-langpack-ja google-noto-sans-cjk-ttc-fonts google-noto-serif-cjk-ttc-fonts

	echo "# Setting System Language -> $Language"
	locale
	localectl status --no-pager
	localectl list-locales --no-pager | grep ja_
	localectl set-locale LANG=ja_JP.utf8
	localectl status --no-pager
	locale
	strings /etc/locale.conf
	source /etc/locale.conf
elif [ "${Language}" = "en_US.UTF-8" ]; then
	echo "# Setting System Language -> $Language"
	locale
	localectl status --no-pager
	localectl list-locales --no-pager | grep en_
	localectl set-locale LANG=en_US.utf8
	localectl status --no-pager
	locale
	strings /etc/locale.conf
	source /etc/locale.conf
else
	echo "# Default Language"
	locale
	localectl status --no-pager
	strings /etc/locale.conf
fi

# Setting IP Protocol Stack (IPv4 Only) or (IPv4/IPv6 Dual stack)
if [ "${VpcNetwork}" = "IPv4" ]; then
	echo "# Setting IP Protocol Stack -> $VpcNetwork"

	# Disable IPv6 Kernel Module
	echo "options ipv6 disable=1" >> /etc/modprobe.d/ipv6.conf

	# Disable IPv6 Kernel Parameter
	sysctl -a

	DisableIPv6Conf="/etc/sysctl.d/90-ipv6-disable.conf"

	cat /dev/null > $DisableIPv6Conf
	echo '# Custom sysctl Parameter for ipv6 disable' >> $DisableIPv6Conf
	echo 'net.ipv6.conf.all.disable_ipv6 = 1' >> $DisableIPv6Conf
	echo 'net.ipv6.conf.default.disable_ipv6 = 1' >> $DisableIPv6Conf

	sysctl --system
	sysctl -p

	sysctl -a | grep -ie "local_port" -ie "ipv6" | sort
elif [ "${VpcNetwork}" = "IPv6" ]; then
	echo "# Show IP Protocol Stack -> $VpcNetwork"
	echo "# Show IPv6 Network Interface Address"
	ifconfig
	echo "# Show IPv6 Kernel Module"
	lsmod | awk '{print $1}' | grep ipv6
	echo "# Show Network Listen Address and report"
	netstat -an -A inet6
	echo "# Show Network Routing Table"
	netstat -r -A inet6
else
	echo "# Default IP Protocol Stack"
	echo "# Show IPv6 Network Interface Address"
	ifconfig
	echo "# Show IPv6 Kernel Module"
	lsmod | awk '{print $1}' | grep ipv6
	echo "# Show Network Listen Address and report"
	netstat -an -A inet6
	echo "# Show Network Routing Table"
	netstat -r -A inet6
fi

#-------------------------------------------------------------------------------
# Reboot
#-------------------------------------------------------------------------------

# Instance Reboot
reboot


text:
Network::Network(std::vector<unsigned> &topology) {
	std::size_t numberOfLayers = topology.size();

	//The number of layers has to be at least three
	if (numberOfLayers < 3)
		throw "Network::Network: The number of layers has to be at least three!";

	this->m_Layers.push_back(Layer(topology[0]));

	//Iterate through the topology and create one layer after another
	for (unsigned i = 1; i < numberOfLayers; i++) {
		this->m_Layers.push_back(Layer(topology[i], this->m_Layers.back()));
	}

	this->m_Alpha = 0.7;
	this->m_Eta = 0.05;
}

void Network::setInputValues(std::vector<double> &inputValues) {
	Layer& inputLayer = this->m_Layers.front();

	inputLayer.setValues(inputValues);
}

void Network::getOutputValues(std::vector<double> &outputValues) {

	for (unsigned i = 1; i < this->m_Layers.size(); i++) {
		this->m_Layers[i].feedForward(this->m_Layers[i - 1]);
	}

	Layer& outputLayer = this->m_Layers.back();
	outputLayer.getValues(outputValues, false);
}

void Network::getValuesFromLayer(std::vector<double> &outputValues, unsigned index) {

	Layer& outputLayer = this->m_Layers[index];
	outputLayer.getValues(outputValues);
}

void Network::backPropagation(std::vector<double> &targetValues) {
	unsigned i;

	//Overall net error
	this->m_Error = 0.0;

	Layer& outputLayer = this->m_Layers.back();

	for (i = 0; i <  outputLayer.getNeuronCount() -1; i++) {
		double delta = targetValues[i] - outputLayer.getNeuron(i).Value();
		this->m_Error += delta * delta;
	}

	this->m_Error /= outputLayer.getNeuronCount();
	this->m_Error = sqrt(this->m_Error); //RMS (Root mean square)

	//Recent average measurement
	this->m_RecentAverageError = (this->m_RecentAverageError * this->m_RecentAverageSmoothingFactor + this->m_Error)
		/ (this->m_RecentAverageSmoothingFactor + 1);

	//Output layer gradients
	outputLayer.calculateGradients(targetValues);

	//Calculate gradients on hidden layers
	for (i = (unsigned)this->m_Layers.size() - 2; i > 0; i--) {
		Layer& hiddenLayer = this->m_Layers[i];
		Layer& nextLayer = this->m_Layers[i + 1];

		hiddenLayer.calculateGradients(nextLayer);

	}

	//Update weights
	for (i = (unsigned)this->m_Layers.size() - 1; i > 0; i--) {
		Layer& hiddenLayer = this->m_Layers[i];
		Layer& previousLayer = this->m_Layers[i - 1];

		hiddenLayer.updateInputWeights(previousLayer, this->m_Eta, this->m_Alpha);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package routeros

import (
	"bytes"
	"crypto/md5"
	"crypto/tls"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"net"
	"strings"
	"sync"

	"joi.com.br/mikrotik-go/proto"
)

var (
	ErrKeyNotFound = errors.New("key not found")
)

// Reply has all lines from a reply. They must all have the same .tag value.
type Reply struct {
	Re   []*proto.Sentence
	Done *proto.Sentence
}

func (r *Reply) String() string {
	b := &bytes.Buffer{}
	for _, re := range r.Re {
		fmt.Fprintf(b, "%s\n", re)
	}
	fmt.Fprintf(b, "%s", r.Done)
	return b.String()
}

type AsyncReply struct {
	*Reply
	Tag string
	Err error
	C   chan struct{}
}

// Client is a RouterOS API client.
type Client struct {
	Address   string
	Username  string
	Password  string
	TLSConfig *tls.Config
	conn      net.Conn
	r         proto.Reader
	w         *proto.Writer
	async     bool
	nextTag   int64
	tags      map[string]*AsyncReply
	sync.Mutex
}

// Pair is a Key-Value pair for RouterOS Attribute, Query, and Reply words
// use slices of pairs instead of map because we care about order
type Pair struct {
	Key   string
	Value string
	// Op is used for Query words to signify logical operations
	// valid operators are -, =, <, >
	// see http://wiki.mikrotik.com/wiki/Manual:API#Queries for details.
	Op string
}

type Query struct {
	Pairs    []Pair
	Op       string
	Proplist []string
}

func (c *Client) Close() {
	c.conn.Close()
}

func (c *Client) Connect() error {
	var err error
	if c.TLSConfig != nil {
		c.conn, err = tls.Dial("tcp", c.Address, c.TLSConfig)
	} else {
		c.conn, err = net.Dial("tcp", c.Address)
	}
	if err != nil {
		return err
	}
	c.r = proto.NewReader(c.conn)
	c.w = proto.NewWriter(c.conn)

	// try to log in
	res, err := c.Call("/login", nil)
	if err != nil {
		return err
	}

	// handle challenge/response
	challengeEnc, ok := res.Done.Map["ret"]
	if !ok {
		return errors.New("Didn't get challenge from ROS")
	}
	challenge, err := hex.DecodeString(challengeEnc)
	if err != nil {
		return err
	}
	h := md5.New()
	io.WriteString(h, "\000")
	io.WriteString(h, c.Password)
	h.Write(challenge)
	resp := fmt.Sprintf("00%x", h.Sum(nil))

	// try to log in again with challenge/response
	res, err = c.Call("/login", []Pair{
		{Key: "name", Value: c.Username},
		{Key: "response", Value: resp},
	})
	if err != nil {
		return err
	}

	if len(res.Done.List) > 0 {
		return fmt.Errorf("Unexpected result on login: %#q", res.Done.List)
	}

	return nil
}

func (c *Client) Query(command string, q Query) (*Reply, error) {
	c.w.BeginSentence()
	c.w.WriteWord(command)

	// Set property list if present
	if len(q.Proplist) > 0 {
		c.w.Printf("=.proplist=%s", strings.Join(q.Proplist, ","))
	}

	// send params if we got them
	if len(q.Pairs) > 0 {
		for _, v := range q.Pairs {
			c.w.Printf("?%s%s=%s", v.Op, v.Key, v.Value)
		}

		if q.Op != "" {
			c.w.Printf("?#%s", q.Op)
		}
	}

	return c.endCommand()
}

func (c *Client) Call(command string, params []Pair) (*Reply, error) {
	c.w.BeginSentence()
	c.w.WriteWord(command)

	// send params if we got them
	if len(params) > 0 {
		for _, v := range params {
			c.w.Printf("=%s=%s", v.Key, v.Value)
		}
	}

	return c.endCommand()
}

func (c *Client) endCommand() (*Reply, error) {
	if c.async {
		return c.endCommandAsync()
	}
	return c.endCommandSync()
}

func (c *Client) endCommandSync() (*Reply, error) {
	err := c.w.EndSentence()
	if err != nil {
		return nil, err
	}
	return c.readReply()
}

func (c *Client) endCommandAsync() (*Reply, error) {
	a := c.newAsyncReply()
	c.w.Printf(".tag=%s", a.Tag)

	c.Lock()
	err := c.w.EndSentence()
	if err != nil {
		c.Unlock()
		return nil, err
	}
	c.tags[a.Tag] = a
	c.Unlock()

	<-a.C

	c.Lock()
	delete(c.tags, a.Tag)
	c.Unlock()

	return a.Reply, a.Err
}

func (c *Client) newAsyncReply() *AsyncReply {
	c.nextTag++
	return &AsyncReply{
		Reply: &Reply{},
		Tag:   fmt.Sprintf("%d", c.nextTag),
		C:     make(chan struct{}),
	}
}


text:
var Code = require('code');   // assertion library
var Lab = require('lab');
var lab = exports.lab = Lab.script();

var describe = lab.describe;
var it = lab.it;
//var before = lab.before;
//var after = lab.after;
var expect = Code.expect;

var DNSRecord = require('../lib/dnsrecord');
var BufferWriter = require('../lib/bufferwriter');
//var helper = require('./helper');

describe('DNSRecord (Create)', function () {

  it('create query', function (done) {
    var bw = new BufferWriter();
    var r = new DNSRecord('_services._dns-sd._udp.local',
      DNSRecord.Type.PTR, 1);
    expect(r).to.include(['name', 'type', 'class', 'ttl']);
    expect(r.ttl).to.equal(DNSRecord.TTL);
    var b = DNSRecord.write(bw, r).dump();
    expect(b.toString('hex')).to.equal(
      '095f7365727669636573075f646e732d7364045f756470056c6f63616c00000c0001');

    //roundtrip
    var pr = DNSRecord.parseQuestion(b);
    expect(pr).to.deep.include(r);

    done();
  });

  it('SRV', function (done) {
    var bw = new BufferWriter();
    var alias = 'regin [30:46:9a:b2:b8:b2]._workstation._tcp.local';

    var r = {
      name: alias,
      type: DNSRecord.Type.SRV,
      class: DNSRecord.Class.IN,
      ttl: 10,
      priority: 1,
      weight: 2,
      port: 9,
      target: 'regin.local'
    };

    var b = DNSRecord.write(bw, r, true).dump();
    var recStr = b.toString('hex');

    expect(recStr, 'type, class, ttl').to.include('002100010000000a');
    expect(recStr, 'srv data').to.include('00010002000905726567696e');
                             //002100010000000a0013000000010002000905726567696e056c6f63616c00
    //roundtrip
    var pr = DNSRecord.parse(b);
    expect(pr).to.include(['port', 'target', 'weight', 'priority']);

    //expect(pr.priority, 'priority').to.equal(priority);
    expect(pr.port, 'port').to.equal(r.port);
    expect(pr.weight, 'weight').to.equal(r.weight);
    expect(pr.target, 'target').to.equal(r.target);
    //expect(pr).to.deep.equal(r);

    done();
  });

  it('PTR', function (done) {
    var writer = new BufferWriter();
    var r = new DNSRecord(
      '_services._dns-sd._udp.local',
      DNSRecord.Type.PTR,
      1,
      10);
    r.data = '_workstation._tcp.local';
    DNSRecord.write(writer, r, true);
    done();
  });

});


text:
<bill session="115" type="h" number="443" updated="2017-06-19T20:30:10Z">
  <state datetime="2017-01-11">REFERRED</state>
  <status>
    <introduced datetime="2017-01-11"/>
  </status>
  <introduced datetime="2017-01-11"/>
  <titles>
    <title type="short" as="introduced">James K. Polk Presidential Home Study Act</title>
    <title type="short" as="introduced">James K. Polk Presidential Home Study Act</title>
    <title type="official" as="introduced">To direct the Secretary of the Interior to study the suitability and feasibility of designating the James K. Polk Home in Columbia, Tennessee, as a unit of the National Park System, and for other purposes.</title>
    <title type="display">James K. Polk Presidential Home Study Act</title>
  </titles>
  <sponsor bioguide_id="D000616"/>
  <cosponsors>
    <cosponsor bioguide_id="B001243" joined="2017-01-11"/>
  </cosponsors>
  <actions>
    <action datetime="2017-01-11">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-01-11" state="REFERRED">
      <text>Referred to the House Committee on Natural Resources.</text>
    </action>
    <action datetime="2017-02-10">
      <text>Referred to the Subcommittee on Federal Lands.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSII" name="House Natural Resources" activity="Referral"/>
    <committee subcommittee="Federal Lands" code="HSII10" name="House Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="s" session="115" relation="unknown" number="99"/>
  </relatedbills>
  <subjects>
    <term name="Public lands and natural resources"/>
    <term name="Government studies and investigations"/>
    <term name="Historic sites and heritage areas"/>
    <term name="Parks, recreation areas, trails"/>
    <term name="Presidents and presidential powers, Vice Presidents"/>
    <term name="Tennessee"/>
  </subjects>
  <amendments/>
  <summary date="2017-01-11T05:00:00Z" status="Introduced in House">James K. Polk Presidential Home Study Act

 This bill directs the Department of the Interior to conduct a special resource study of the James K. Polk Home and adjacent property in Columbia, Tennessee.

In conducting this study, Interior shall evaluate the national significance of the site and determine the suitability and feasibility of designating it as a unit of the National Park System.</summary>
  <committee-reports/>
</bill>


text:
<?php

/*
 * Yampee Components
 * Open source web development components for PHP 5.
 *
 * @package Yampee Components
 * @author Titouan Galopin <galopintitouan@gmail.com>
 * @link http://titouangalopin.com
 */

/**
 * @author Titouan Galopin <galopintitouan@gmail.com>
 */
class Yampee_Form_Validator_Ip extends Yampee_Form_Validator_Abstract
{
	/**
	 * @param $value
	 * @return boolean
	 */
	public function validate($value)
	{
		return filter_var($value, FILTER_VALIDATE_IP) !== false;
	}

	/**
	 * @return string
	 */
	public function getName()
	{
		return 'ip';
	}
}


text:
"""
Qemu-img Command Wrapper
========================

The qemu img command is wrapped for specific functions

:depends: qemu-img
"""

import os

import salt.utils.path

def __virtual__():
    """
    Only load if qemu-img is installed
    """
    if salt.utils.path.which("qemu-img"):
        return "qemu_img"
    return (
        False,
        "The qemu_img execution module cannot be loaded: the qemu-img binary is not in"
        " the path.",
    )

def make_image(location, size, fmt):
    """
    Create a blank virtual machine image file of the specified size in
    megabytes. The image can be created in any format supported by qemu

    CLI Example:

    .. code-block:: bash

        salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2
        salt '*' qemu_img.make_image /tmp/image.raw 10240 raw
    """
    if not os.path.isabs(location):
        return ""
    if not os.path.isdir(os.path.dirname(location)):
        return ""
    if not __salt__["cmd.retcode"](
        "qemu-img create -f {} {} {}M".format(fmt, location, size),
        python_shell=False,
    ):
        return location
    return ""

def convert(orig, dest, fmt):
    """
    Convert an existing disk image to another format using qemu-img

    CLI Example:

    .. code-block:: bash

        salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2
    """
    cmd = ("qemu-img", "convert", "-O", fmt, orig, dest)
    ret = __salt__["cmd.run_all"](cmd, python_shell=False)
    if ret["retcode"] == 0:
        return True
    else:
        return ret["stderr"]


text:
package com.baofeng.mobile.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import org.lee.java.util.ArrayUtils;

import java.util.List;

public abstract class BaseHeaderPagerAdapter<T> extends PagerAdapter {

    public interface OnItemClickListener{
        void onItemClick(ViewPager pager, View view, int position);
    }

	protected Context context;
    protected List<T> mData;
    private int mChildCount = 0;

    private boolean isInfiniteLoop; // 循环滑动

    protected OnItemClickListener mListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

	public BaseHeaderPagerAdapter(Context context, List<T> data) {
		this.context = context;
		this.mData = data;
        this.isInfiniteLoop = false;
	}

	public BaseHeaderPagerAdapter(Context context, List<T> data, boolean isInfiniteLoop) {
        this(context, data);
        this.isInfiniteLoop = isInfiniteLoop;
	}

    public boolean isInfiniteLoop() {
        return isInfiniteLoop;
    }

    public void setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
    }

    public void clear() {
        if (mData != null) {
            mData.clear();
        }
    }

    public void setData(List<T> data) {
        mData = data;
        notifyDataSetChanged();
    }

    public int getDataSize() {
        return ArrayUtils.count(mData);
    }

    @Override
    public int getCount() {
        return isInfiniteLoop ? (getDataSize() > 1 ? Integer.MAX_VALUE : getDataSize()) : getDataSize();
    }

    public int getPosition(int position) {
        return isInfiniteLoop ? position % getDataSize() : position;
    }

    public T getItem(int position) {
        return mData == null ? null : mData.get(getPosition(position));
    }

    @Override
    public void notifyDataSetChanged() {
        mChildCount = getDataSize();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object)   {
        if ( mChildCount > 0) {
            mChildCount --;
            return POSITION_NONE;
        }
        return super.getItemPosition(object);
    }

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = getView(container, position);
        container.addView(view);
        return view;
    }

    protected abstract View getView(ViewGroup container, int position);

}


text:
.class Lcom/mediatek/hdmi/MtkHdmiManagerService$3;
.super Ljava/lang/Object;
.source "MtkHdmiManagerService.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/mediatek/hdmi/MtkHdmiManagerService;->handleMultiChannel()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService;

# direct methods
.method constructor <init>(Lcom/mediatek/hdmi/MtkHdmiManagerService;)V
    .locals 0

    .prologue
    .line 302
    iput-object p1, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$3;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 3
    .param p1, "dialog"    # Landroid/content/DialogInterface;
    .param p2, "which"    # I

    .prologue
    .line 305
    iget-object v0, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$3;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService;

    # setter for: Lcom/mediatek/hdmi/MtkHdmiManagerService;->mAudioOutputMode:I
    invoke-static {v0, p2}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$1202(Lcom/mediatek/hdmi/MtkHdmiManagerService;I)I

    .line 306
    const-string v0, "MtkHdmiService"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "mAudioOutputDialog clicked.. which: "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->log(Ljava/lang/String;Ljava/lang/Object;)V
    invoke-static {v0, v1}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$000(Ljava/lang/String;Ljava/lang/Object;)V

    .line 307
    iget-object v1, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$3;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService;

    if-nez p2, :cond_0

    const/4 v0, 0x1

    :goto_0
    # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->setAudioParameters(Z)V
    invoke-static {v1, v0}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$1300(Lcom/mediatek/hdmi/MtkHdmiManagerService;Z)V

    .line 308
    invoke-interface {p1}, Landroid/content/DialogInterface;->dismiss()V

    .line 309
    iget-object v0, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$3;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService;

    const/4 v1, 0x0

    # setter for: Lcom/mediatek/hdmi/MtkHdmiManagerService;->mAudioOutputDialog:Landroid/app/AlertDialog;
    invoke-static {v0, v1}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$1402(Lcom/mediatek/hdmi/MtkHdmiManagerService;Landroid/app/AlertDialog;)Landroid/app/AlertDialog;

    .line 310
    return-void

    .line 307
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
import angular from 'angular';

angular
    .module('ignite-console.states.settings', [
        'ui.router'
    ])
    .config(['$stateProvider', /** @param {import('@uirouter/angularjs').StateProvider} $stateProvider */ function($stateProvider) {
        // Set up the states.
        $stateProvider
            .state('base.settings', {
                url: '/settings',
                abstract: true,
                template: '<ui-view></ui-view>'
            });
    }]);


text:
package com.threerings.s3.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * A representation of an S3Object whose contents are unavailable
 * (eg, retrieved via a HEAD request). The returned InputStream
 * will always throw an IOException.
 */
class S3EmptyObject extends S3Object {
	/**
	 * A simple stream that always returns an IOException.
	 */
	private static class NullInputStream extends InputStream {
		@Override
		public int read() throws IOException {
			throw new IOException("No stream available");
		}
	}

    /**
     * Instantiate an S3 object with the given key.
     */
    public S3EmptyObject (String key, String mimeType, long length, byte[] digest,
        Map<String,String> metadata, long lastModified)
    {
        super(key, mimeType, metadata);
        _lastModified = lastModified;
        _length = length;
        _md5digest = digest;
    }

	@Override
	public InputStream getInputStream() throws S3ClientException {
		return new NullInputStream();
	}

	@Override
	public long lastModified () {
	    return _lastModified;
	}

	@Override
	public byte[] getMD5() throws S3ClientException {
		return _md5digest;
	}

	@Override
	public long length() {
		return _length;
	}

	/** Last modified timestamp. */
	private final long _lastModified;

    /** Data length in bytes. */
    private final long _length;

    /** MD5 digest. */
    private final byte[] _md5digest;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Y!LDA: Testing_Execution_Strategy Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

Testing_Execution_Strategy Class Reference

#include <Testing_Execution_Strategy.h>

Inheritance diagram for Testing_Execution_Strategy:

  <map id="Testing_Execution_Strategy_map" name="Testing_Execution_Strategy_map">
<area href="class_execution___strategy.html" alt="Execution_Strategy" shape="rect" coords="0,0,168,24"/>
</map>

List of all members.

Public Member Functions

 	Testing_Execution_Strategy (Pipeline &, Model &)

virtual 	~Testing_Execution_Strategy ()

void 	execute ()

Detailed Description

This is a default implementation for the Execution_Strategy interface for testing using a model.

Constructor & Destructor Documentation

          Testing_Execution_Strategy::Testing_Execution_Strategy
          (
          Pipeline &
           pipeline,

          Model &
           model

          )

          Testing_Execution_Strategy::~Testing_Execution_Strategy
          (

           )
           [virtual]

Member Function Documentation

          void Testing_Execution_Strategy::execute
          (

           )
           [virtual]

Define what filters need to added and when Runs the assembled pipeline once

Implements Execution_Strategy.

The documentation for this class was generated from the following files:

src/commons/TopicLearner/Testing_Execution_Strategy.h

src/commons/TopicLearner/Testing_Execution_Strategy.cpp

<address style="text-align: right;">Generated on Tue Jul 19 11:45:28 2011 for Y!LDA by

 1.6.3 </address>


text:
An AngularJS seed based on Angular Material Design, RequireJS and Grunt

## Installation
1. Clone the project
2. Cd into the project folder
3. Npm install to install dependent node modules
4. Type 'grunt' in Node CMD to run the project

## Usage
This is an AngularJS seed based on Angular Material Design. This project would serve as a immediate solution for Angular web development.

## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request

## History

## Notes
Meantime, the testing scripts would not be working. Test scripts will be added as soon as possible.

## Credits
1. AngularJS Seed - Pete Bacon Darwin (https://github.com/petebacondarwin)
2. Angular Material Design - Robert Messerle (https://github.com/robertmesserle)

## License
MIT


text:
#ifndef TORRENT_PEER_HPP_INCLUDED
#define TORRENT_PEER_HPP_INCLUDED

#include <string>

#include "libtorrent/peer_id.hpp"

namespace libtorrent
{

	struct TORRENT_EXTRA_EXPORT peer_entry
	{
		std::string hostname;
		peer_id pid;
		boost::uint16_t port;

		bool operator==(const peer_entry& p) const
		{ return pid == p.pid; }

		bool operator<(const peer_entry& p) const
		{ return pid < p.pid; }
	};

	struct ipv4_peer_entry
	{
		address_v4::bytes_type ip;
		boost::uint16_t port;
	};

#if TORRENT_USE_IPV6
	struct ipv6_peer_entry
	{
		address_v6::bytes_type ip;
		boost::uint16_t port;
	};
#endif

}

#endif // TORRENT_PEER_HPP_INCLUDED


text:
'use strict';

module.exports = function(app) {
  app.controller('GithubController', ['Github', function(Github) {
    this.loading = false;
    this.toggleText = 'Recent Github Repos';
    this.toggleRepo = false;
    this.toggleInProgress = true;

    if (Github.allRepos.length === 0) {
      this.loading = true;
      Github.requestRepos();
      this.loading = false;
    }

    this.getCurrentRepos = function() {
      Github.requestRepos().then((res) => {
        this.currentRepos = res.data;
      });
    };

    this.filterReposWithAttr = function(attr) {
      this.filteredCurrentRepos = Github.filterReposWithAttr(attr);
    };

    this.toggleView = function() {
      if (this.toggleText === 'Recent Github Repos') {
        this.toggleRepo = true;
        this.toggleInProgress = false;
        this.toggleText = 'In Progress';
      }

      if (this.toggleText === 'In Progress') {
        this.toggleInProgress = true;
        this.toggleRepo = false;
        this.toggleText = 'Recent Github Repos';
      }
    };

    this.allRepos = Github.allRepos;

  }]);
};


text:
using System;
using System.Data.Entity.Validation;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.TestBase.SampleApplication.People;
using Shouldly;
using Xunit;

namespace Abp.TestBase.SampleApplication.Tests.Uow
{
    public class UnitOfWork_Event_Tests : SampleApplicationTestBase
    {
        private readonly IRepository<Person> _personRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public UnitOfWork_Event_Tests()
        {
            _personRepository = Resolve<IRepository<Person>>();
            _unitOfWorkManager = Resolve<IUnitOfWorkManager>();
        }

        [Fact]
        public void Should_Trigger_Completed_When_Uow_Succeed()
        {
            var completeCount = 0;
            var disposeCount = 0;

            using (var uow = _unitOfWorkManager.Begin())
            {
                _personRepository.Insert(new Person { ContactListId = 1, Name = "john" });

                _unitOfWorkManager.Current.Completed += (sender, args) =>
                                                        {
                                                            _unitOfWorkManager.Current.ShouldBe(null);
                                                            completeCount++;
                                                        };

                _unitOfWorkManager.Current.Disposed += (sender, args) =>
                                                       {
                                                           _unitOfWorkManager.Current.ShouldBe(null);
                                                           completeCount.ShouldBe(1);
                                                           disposeCount++;
                                                       };

                uow.Complete();
            }

            UsingDbContext(context => context.People.Any(p => p.Name == "john").ShouldBe(true));

            completeCount.ShouldBe(1);
            disposeCount.ShouldBe(1);
        }

        [Fact]
        public void Should_Trigger_Failed_When_Throw_Exception_In_Uow()
        {
            var failedCount = 0;
            var disposeCount = 0;

            Assert.Throws<ApplicationException>(
                new Action(() =>
                {
                    using (var uow = _unitOfWorkManager.Begin())
                    {
                        _personRepository.Insert(new Person()); //Name is intentionally not set to cause exception

                        _unitOfWorkManager.Current.ShouldNotBe(null);

                        _unitOfWorkManager.Current.Failed += (sender, args) =>
                        {
                            _unitOfWorkManager.Current.ShouldBe(null);
                            args.Exception.ShouldBe(null); //Can not set it!
                            failedCount++;
                        };

                        _unitOfWorkManager.Current.Disposed += (sender, args) =>
                        {
                            _unitOfWorkManager.Current.ShouldBe(null);
                            failedCount.ShouldBe(1);
                            disposeCount++;
                        };

                        throw new ApplicationException("This is throwed to make uow failed");
                    }
                }));

            failedCount.ShouldBe(1);
            disposeCount.ShouldBe(1);
        }

        [Fact]
        public void Should_Trigger_Failed_When_SaveChanges_Fails()
        {
            var failedCount = 0;
            var disposeCount = 0;

            using (var uow = _unitOfWorkManager.Begin())
            {
                _personRepository.Insert(new Person()); //Name is intentionally not set to cause exception

                _unitOfWorkManager.Current.Failed += (sender, args) =>
                {
                    _unitOfWorkManager.Current.ShouldBe(null);
                    args.Exception.ShouldNotBe(null);
                    args.Exception.ShouldBeOfType(typeof(DbEntityValidationException));
                    failedCount++;
                };

                _unitOfWorkManager.Current.Disposed += (sender, args) =>
                {
                    _unitOfWorkManager.Current.ShouldBe(null);
                    failedCount.ShouldBe(1);
                    disposeCount++;
                };

                Assert.Throws<DbEntityValidationException>(() => uow.Complete());
            }

            failedCount.ShouldBe(1);
            disposeCount.ShouldBe(1);
        }

        [Fact]
        public async Task Should_Return_Back_To_Outer_Uow_On_Nested_Uows()
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                var outerUow = _unitOfWorkManager.Current;

                outerUow.Completed += (sender, args) =>
                {
                    _unitOfWorkManager.Current.ShouldBe(null);
                };

                using (var uowInner = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
                {
                    var innerUow = _unitOfWorkManager.Current;

                    innerUow.Completed += (sender, args) =>
                    {
                        _unitOfWorkManager.Current.ShouldBe(outerUow);
                    };

                    await uowInner.CompleteAsync();
                }

                await uow.CompleteAsync();
            }
        }
    }
}


text:
<?php

namespace Yansongda\Pay\Tests\Plugin\Wechat\Fund\Transfer;

use GuzzleHttp\Psr7\Uri;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Plugin\Wechat\Fund\Transfer\CreatePlugin;
use Yansongda\Pay\Provider\Wechat;
use Yansongda\Pay\Rocket;
use Yansongda\Pay\Tests\TestCase;
use Yansongda\Supports\Collection;

class CreatePluginTest extends TestCase
{
    /**
     * @var CreatePlugin
     */
    protected $plugin;

    protected function setUp(): void
    {
        parent::setUp();

        $this->plugin = new CreatePlugin();
    }

    public function testNormal()
    {
        $rocket = new Rocket();
        $rocket->setParams([])->setPayload(new Collection());

        $result = $this->plugin->assembly($rocket, function ($rocket) { return $rocket; });

        $radar = $result->getRadar();
        $payload = $result->getPayload();

        self::assertEquals(new Uri(Wechat::URL[Pay::MODE_NORMAL].'v3/transfer/batches'), $radar->getUri());
        self::assertEquals('wx55955316af4ef13', $payload->get('appid'));
    }

    public function testPartner()
    {
        $rocket = new Rocket();
        $rocket->setParams(['_config' => 'service_provider'])->setPayload(new Collection());

        $result = $this->plugin->assembly($rocket, function ($rocket) { return $rocket; });

        $radar = $result->getRadar();
        $payload = $result->getPayload();

        self::assertEquals(new Uri(Wechat::URL[Pay::MODE_NORMAL].'v3/partner-transfer/batches'), $radar->getUri());
        self::assertEquals('1600314070', $payload->get('sub_mchid'));
        self::assertNull($payload->get('appid'));
    }

    public function testUsername()
    {
        // 不传证书
        $params = [
            'transfer_detail_list' => [
                [
                    'out_detail_no' => time().'-1',
                    'transfer_amount' => 1,
                    'transfer_remark' => 'test',
                    'openid' => 'MYE42l80oelYMDE34nYD456Xoy',
                    'user_name' => 'yansongda'  // 明文传参即可,sdk 会自动加密
                ]
            ],
        ];

        $rocket = new Rocket();
        $rocket->setParams($params)->setPayload(new Collection());
        $result = $this->plugin->assembly($rocket, function ($rocket) { return $rocket; });

        $userName = $result->getPayload()->get('transfer_detail_list')[0]['user_name'];

        self::assertTrue(in_array($result->getParams()['_serial_no'], ['45F59D4DABF31918AFCEC556D5D2C6E376675D57', 'yansongda']));
        self::assertNotEquals('yansongda', $userName);
        self::assertStringContainsString('==', $userName);

        // 传证书
        $params = [
            '_serial_no' => 'yansongda',
            'transfer_detail_list' => [
                [
                    'out_detail_no' => time().'-1',
                    'transfer_amount' => 1,
                    'transfer_remark' => 'test',
                    'openid' => 'MYE42l80oelYMDE34nYD456Xoy',
                    'user_name' => 'yansongda'  // 明文传参即可,sdk 会自动加密
                ]
            ],
        ];

        $rocket = new Rocket();
        $rocket->setParams($params)->setPayload(new Collection());
        $result = $this->plugin->assembly($rocket, function ($rocket) { return $rocket; });

        $userName = $result->getPayload()->get('transfer_detail_list')[0]['user_name'];

        self::assertEquals('yansongda', $result->getParams()['_serial_no']);
        self::assertStringContainsString('==', $userName);
    }

    public function testNormalOtherType()
    {
        $rocket = new Rocket();
        $rocket->setParams(['_type' => 'mini'])->setPayload(new Collection());

        $result = $this->plugin->assembly($rocket, function ($rocket) { return $rocket; });

        $radar = $result->getRadar();
        $payload = $result->getPayload();

        self::assertEquals(new Uri(Wechat::URL[Pay::MODE_NORMAL].'v3/transfer/batches'), $radar->getUri());
        self::assertEquals('wx55955316af4ef14', $payload->get('appid'));
    }
}


text:
package com.google.android.exoplayer.extractor.flv;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.extractor.Extractor;
import com.google.android.exoplayer.extractor.ExtractorInput;
import com.google.android.exoplayer.extractor.ExtractorOutput;
import com.google.android.exoplayer.extractor.PositionHolder;
import com.google.android.exoplayer.extractor.SeekMap;
import com.google.android.exoplayer.util.ParsableByteArray;
import com.google.android.exoplayer.util.Util;
import java.io.IOException;

/**
 * Facilitates the extraction of data from the FLV container format.
 */
public final class FlvExtractor implements Extractor, SeekMap {

  // Header sizes.
  private static final int FLV_HEADER_SIZE = 9;
  private static final int FLV_TAG_HEADER_SIZE = 11;

  // Parser states.
  private static final int STATE_READING_FLV_HEADER = 1;
  private static final int STATE_SKIPPING_TO_TAG_HEADER = 2;
  private static final int STATE_READING_TAG_HEADER = 3;
  private static final int STATE_READING_TAG_DATA = 4;

  // Tag types.
  private static final int TAG_TYPE_AUDIO = 8;
  private static final int TAG_TYPE_VIDEO = 9;
  private static final int TAG_TYPE_SCRIPT_DATA = 18;

  // FLV container identifier.
  private static final int FLV_TAG = Util.getIntegerCodeForString("FLV");

  // Temporary buffers.
  private final ParsableByteArray scratch;
  private final ParsableByteArray headerBuffer;
  private final ParsableByteArray tagHeaderBuffer;
  private final ParsableByteArray tagData;

  // Extractor outputs.
  private ExtractorOutput extractorOutput;

  // State variables.
  private int parserState;
  private int bytesToNextTagHeader;
  public int tagType;
  public int tagDataSize;
  public long tagTimestampUs;

  // Tags readers.
  private AudioTagPayloadReader audioReader;
  private VideoTagPayloadReader videoReader;
  private ScriptTagPayloadReader metadataReader;

  public FlvExtractor() {
    scratch = new ParsableByteArray(4);
    headerBuffer = new ParsableByteArray(FLV_HEADER_SIZE);
    tagHeaderBuffer = new ParsableByteArray(FLV_TAG_HEADER_SIZE);
    tagData = new ParsableByteArray();
    parserState = STATE_READING_FLV_HEADER;
  }

  @Override
  public boolean sniff(ExtractorInput input) throws IOException, InterruptedException {
    // Check if file starts with "FLV" tag
    input.peekFully(scratch.data, 0, 3);
    scratch.setPosition(0);
    if (scratch.readUnsignedInt24() != FLV_TAG) {
      return false;
    }

    // Checking reserved flags are set to 0
    input.peekFully(scratch.data, 0, 2);
    scratch.setPosition(0);
    if ((scratch.readUnsignedShort() & 0xFA) != 0) {
      return false;
    }

    // Read data offset
    input.peekFully(scratch.data, 0, 4);
    scratch.setPosition(0);
    int dataOffset = scratch.readInt();

    input.resetPeekPosition();
    input.advancePeekPosition(dataOffset);

    // Checking first "previous tag size" is set to 0
    input.peekFully(scratch.data, 0, 4);
    scratch.setPosition(0);

    return scratch.readInt() == 0;
  }

  @Override
  public void init(ExtractorOutput output) {
    this.extractorOutput = output;
  }

  @Override
  public void seek() {
    parserState = STATE_READING_FLV_HEADER;
    bytesToNextTagHeader = 0;
  }

  @Override
  public void release() {
    // Do nothing
  }

  @Override
  public int read(ExtractorInput input, PositionHolder seekPosition) throws IOException,
      InterruptedException {
    while (true) {
      switch (parserState) {
        case STATE_READING_FLV_HEADER:
          if (!readFlvHeader(input)) {
            return RESULT_END_OF_INPUT;
          }
          break;
        case STATE_SKIPPING_TO_TAG_HEADER:
          skipToTagHeader(input);
          break;
        case STATE_READING_TAG_HEADER:
          if (!readTagHeader(input)) {
            return RESULT_END_OF_INPUT;
          }
          break;
        case STATE_READING_TAG_DATA:
          if (readTagData(input)) {
            return RESULT_CONTINUE;
          }
          break;
      }
    }
  }

  /**
   * Reads an FLV container header from the provided {@link ExtractorInput}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @return True if header was read successfully. False if the end of stream was reached.
   * @throws IOException If an error occurred reading or parsing data from the source.
   * @throws InterruptedException If the thread was interrupted.
   */
  private boolean readFlvHeader(ExtractorInput input) throws IOException, InterruptedException {
    if (!input.readFully(headerBuffer.data, 0, FLV_HEADER_SIZE, true)) {
      // We've reached the end of the stream.
      return false;
    }

    headerBuffer.setPosition(0);
    headerBuffer.skipBytes(4);
    int flags = headerBuffer.readUnsignedByte();
    boolean hasAudio = (flags & 0x04) != 0;
    boolean hasVideo = (flags & 0x01) != 0;
    if (hasAudio && audioReader == null) {
      audioReader = new AudioTagPayloadReader(extractorOutput.track(TAG_TYPE_AUDIO));
    }
    if (hasVideo && videoReader == null) {
      videoReader = new VideoTagPayloadReader(extractorOutput.track(TAG_TYPE_VIDEO));
    }
    if (metadataReader == null) {
      metadataReader = new ScriptTagPayloadReader(null);
    }
    extractorOutput.endTracks();
    extractorOutput.seekMap(this);

    // We need to skip any additional content in the FLV header, plus the 4 byte previous tag size.
    bytesToNextTagHeader = headerBuffer.readInt() - FLV_HEADER_SIZE + 4;
    parserState = STATE_SKIPPING_TO_TAG_HEADER;
    return true;
  }

  /**
   * Skips over data to reach the next tag header.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @throws IOException If an error occurred skipping data from the source.
   * @throws InterruptedException If the thread was interrupted.
   */
  private void skipToTagHeader(ExtractorInput input) throws IOException, InterruptedException {
    input.skipFully(bytesToNextTagHeader);
    bytesToNextTagHeader = 0;
    parserState = STATE_READING_TAG_HEADER;
  }

  /**
   * Reads a tag header from the provided {@link ExtractorInput}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @return True if tag header was read successfully. Otherwise, false.
   * @throws IOException If an error occurred reading or parsing data from the source.
   * @throws InterruptedException If the thread was interrupted.
   */
  private boolean readTagHeader(ExtractorInput input) throws IOException, InterruptedException {
    if (!input.readFully(tagHeaderBuffer.data, 0, FLV_TAG_HEADER_SIZE, true)) {
      // We've reached the end of the stream.
      return false;
    }

    tagHeaderBuffer.setPosition(0);
    tagType = tagHeaderBuffer.readUnsignedByte();
    tagDataSize = tagHeaderBuffer.readUnsignedInt24();
    tagTimestampUs = tagHeaderBuffer.readUnsignedInt24();
    tagTimestampUs = ((tagHeaderBuffer.readUnsignedByte() << 24) | tagTimestampUs) * 1000L;
    tagHeaderBuffer.skipBytes(3); // streamId
    parserState = STATE_READING_TAG_DATA;
    return true;
  }

  /**
   * Reads the body of a tag from the provided {@link ExtractorInput}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @return True if the data was consumed by a reader. False if it was skipped.
   * @throws IOException If an error occurred reading or parsing data from the source.
   * @throws InterruptedException If the thread was interrupted.
   */
  private boolean readTagData(ExtractorInput input) throws IOException, InterruptedException {
    boolean wasConsumed = true;
    if (tagType == TAG_TYPE_AUDIO && audioReader != null) {
      audioReader.consume(prepareTagData(input), tagTimestampUs);
    } else if (tagType == TAG_TYPE_VIDEO && videoReader != null) {
      videoReader.consume(prepareTagData(input), tagTimestampUs);
    } else if (tagType == TAG_TYPE_SCRIPT_DATA && metadataReader != null) {
      metadataReader.consume(prepareTagData(input), tagTimestampUs);
      if (metadataReader.getDurationUs() != C.UNKNOWN_TIME_US) {
        if (audioReader != null) {
          audioReader.setDurationUs(metadataReader.getDurationUs());
        }
        if (videoReader != null) {
          videoReader.setDurationUs(metadataReader.getDurationUs());
        }
      }
    } else {
      input.skipFully(tagDataSize);
      wasConsumed = false;
    }
    bytesToNextTagHeader = 4; // There's a 4 byte previous tag size before the next header.
    parserState = STATE_SKIPPING_TO_TAG_HEADER;
    return wasConsumed;
  }

  private ParsableByteArray prepareTagData(ExtractorInput input) throws IOException,
      InterruptedException {
    if (tagDataSize > tagData.capacity()) {
      tagData.reset(new byte[Math.max(tagData.capacity() * 2, tagDataSize)], 0);
    } else {
      tagData.setPosition(0);
    }
    tagData.setLimit(tagDataSize);
    input.readFully(tagData.data, 0, tagDataSize);
    return tagData;
  }

  // SeekMap implementation.

  @Override
  public boolean isSeekable() {
    return false;
  }

  @Override
  public long getPosition(long timeUs) {
    return 0;
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aspicilia esculenta f. ferruginea Savicz

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:\Users\Chrilieb\.cargo\registry\src\github.com-1ecc6299db9ec823\rand-0.3.15\src\distributions\range.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>range.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="https://www.rust-lang.org/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Generating numbers between two others.

// this is surprisingly complicated to be both generic & correct

use std::num::Wrapping as w;

use Rng;
use distributions::{Sample, IndependentSample};

/// Sample values uniformly between two bounds.
///
/// This gives a uniform distribution (assuming the RNG used to sample
/// it is itself uniform & the `SampleRange` implementation for the
/// given type is correct), even for edge cases like `low = 0u8`,
/// `high = 170u8`, for which a naive modulo operation would return
/// numbers less than 85 with double the probability to those greater
/// than 85.
///
/// Types should attempt to sample in `[low, high)`, i.e., not
/// including `high`, but this may be very difficult. All the
/// primitive integer types satisfy this property, and the float types
/// normally satisfy it, but rounding may mean `high` can occur.
///
/// # Example
///
/// ```rust</span>
<span class="doccomment">/// use rand::distributions::{IndependentSample, Range};</span>
<span class="doccomment">///</span>
<span class="doccomment">/// fn main() {</span>
<span class="doccomment">///     let between = Range::new(10, 10000);</span>
<span class="doccomment">///     let mut rng = rand::thread_rng();</span>
<span class="doccomment">///     let mut sum = 0;</span>
<span class="doccomment">///     for _ in 0..1000 {</span>
<span class="doccomment">///         sum += between.ind_sample(&mut rng);</span>
<span class="doccomment">///     }</span>
<span class="doccomment">///     println!("{}", sum);</span>
<span class="doccomment">/// }</span>
<span class="doccomment">/// ```
#[derive(Clone, Copy)]
pub struct Range<X> {
    low: X,
    range: X,
    accept_zone: X
}

impl<X: SampleRange + PartialOrd> Range<X> {
    /// Create a new `Range` instance that samples uniformly from
    /// `[low, high)`. Panics if `low >= high`.
    pub fn new(low: X, high: X) -> Range<X> {
        assert!(low < high, "Range::new called with `low >= high`");
        SampleRange::construct_range(low, high)
    }
}

impl<Sup: SampleRange> Sample<Sup> for Range<Sup> {
    #[inline]
    fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) }
}
impl<Sup: SampleRange> IndependentSample<Sup> for Range<Sup> {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup {
        SampleRange::sample_range(self, rng)
    }
}

/// The helper trait for types that have a sensible way to sample
/// uniformly between two values. This should not be used directly,
/// and is only to facilitate `Range`.
pub trait SampleRange : Sized {
    /// Construct the `Range` object that `sample_range`
    /// requires. This should not ever be called directly, only via
    /// `Range::new`, which will check that `low < high`, so this
    /// function doesn't have to repeat the check.
    fn construct_range(low: Self, high: Self) -> Range<Self>;

    /// Sample a value from the given `Range` with the given `Rng` as
    /// a source of randomness.
    fn sample_range<R: Rng>(r: &Range<Self>, rng: &mut R) -> Self;
}

macro_rules! integer_impl {
    ($ty:ty, $unsigned:ident) => {
        impl SampleRange for $ty {
            // we play free and fast with unsigned vs signed here
            // (when $ty is signed), but that's fine, since the
            // contract of this macro is for $ty and $unsigned to be
            // "bit-equal", so casting between them is a no-op & a
            // bijection.

            fn construct_range(low: $ty, high: $ty) -> Range<$ty> {
                let range = (w(high as $unsigned) - w(low as $unsigned)).0;
                let unsigned_max: $unsigned = ::std::$unsigned::MAX;

                // this is the largest number that fits into $unsigned
                // that `range` divides evenly, so, if we've sampled
                // `n` uniformly from this region, then `n % range` is
                // uniform in [0, range)
                let zone = unsigned_max - unsigned_max % range;

                Range {
                    low: low,
                    range: range as $ty,
                    accept_zone: zone as $ty
                }
            }
            #[inline]
            fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty {
                loop {
                    // rejection sample
                    let v = rng.gen::<$unsigned>();
                    // until we find something that fits into the
                    // region which r.range evenly divides (this will
                    // be uniformly distributed)
                    if v < r.accept_zone as $unsigned {
                        // and return it, with some adjustments
                        return (w(r.low) + w((v % r.range as $unsigned) as $ty)).0;
                    }
                }
            }
        }
    }
}

integer_impl! { i8, u8 }
integer_impl! { i16, u16 }
integer_impl! { i32, u32 }
integer_impl! { i64, u64 }
integer_impl! { isize, usize }
integer_impl! { u8, u8 }
integer_impl! { u16, u16 }
integer_impl! { u32, u32 }
integer_impl! { u64, u64 }
integer_impl! { usize, usize }

macro_rules! float_impl {
    ($ty:ty) => {
        impl SampleRange for $ty {
            fn construct_range(low: $ty, high: $ty) -> Range<$ty> {
                Range {
                    low: low,
                    range: high - low,
                    accept_zone: 0.0 // unused
                }
            }
            fn sample_range<R: Rng>(r: &Range<$ty>, rng: &mut R) -> $ty {
                r.low + r.range * rng.gen::<$ty>()
            }
        }
    }
}

float_impl! { f32 }
float_impl! { f64 }

#[cfg(test)]
mod tests {
    use distributions::{Sample, IndependentSample};
    use super::Range as Range;

    #[should_panic]
    #[test]
    fn test_range_bad_limits_equal() {
        Range::new(10, 10);
    }
    #[should_panic]
    #[test]
    fn test_range_bad_limits_flipped() {
        Range::new(10, 5);
    }

    #[test]
    fn test_integers() {
        let mut rng = ::test::rng();
        macro_rules! t {
            ($($ty:ident),*) => {{
                $(
                   let v: &[($ty, $ty)] = &[(0, 10),
                                            (10, 127),
                                            (::std::$ty::MIN, ::std::$ty::MAX)];
                   for &(low, high) in v.iter() {
                        let mut sampler: Range<$ty> = Range::new(low, high);
                        for _ in 0..1000 {
                            let v = sampler.sample(&mut rng);
                            assert!(low <= v && v < high);
                            let v = sampler.ind_sample(&mut rng);
                            assert!(low <= v && v < high);
                        }
                    }
                 )*
            }}
        }
        t!(i8, i16, i32, i64, isize,
           u8, u16, u32, u64, usize)
    }

    #[test]
    fn test_floats() {
        let mut rng = ::test::rng();
        macro_rules! t {
            ($($ty:ty),*) => {{
                $(
                   let v: &[($ty, $ty)] = &[(0.0, 100.0),
                                            (-1e35, -1e25),
                                            (1e-35, 1e-25),
                                            (-1e35, 1e35)];
                   for &(low, high) in v.iter() {
                        let mut sampler: Range<$ty> = Range::new(low, high);
                        for _ in 0..1000 {
                            let v = sampler.sample(&mut rng);
                            assert!(low <= v && v < high);
                            let v = sampler.ind_sample(&mut rng);
                            assert!(low <= v && v < high);
                        }
                    }
                 )*
            }}
        }

        t!(f32, f64)
    }

}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)