text:
IFCONFIG=$(ifconfig)
IP="/sbin/ip"
IFACE=$($IP -o link show | awk '{print $2,$9}' | grep "UP" | cut -d ":" -f 1)
INTERFACES="/etc/network/interfaces"
ADDRESS=$($IP route get 1 | awk '{print $NF;exit}')
NETMASK=$(ifconfig $IFACE | grep Mask | sed s/^.*Mask://)
GATEWAY=$($IP route | awk '/default/ { print $3 }')
SCRIPTS="/var/scripts"
REPO="https://github.com/ezraholm50/MultiInstaller/raw/master"
INTERACTIVE=True
DIR='/etc/update-motd.d'
ASK_TO_REBOOT=0
WHOAMI=$(whoami)
mkdir -p $SCRIPTS
VBOX=
VBOXEXT=
#########################################Root check########################################################
# Check if root
if [ "$(whoami)" != "root" ]; then
        whiptail --msgbox "Sorry you are not root. You must type: sudo bash /var/scripts/MultiInstaller.sh" 20 60 1
        exit
fi
#########################################Whiptail check########################################################
	if [ $(dpkg-query -W -f='${Status}' whiptail 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        sleep 0

else
	apt-get install whiptail -y
fi
#########################################Update########################################################
# Run apt-get update, saves time. Instead of for every install running apt-get update
    {
    i=1
    while read -r line; do
        i=$(( $i + 1 ))
        echo $i
    done < <(apt-get update)
    } | whiptail --title "Progress" --gauge "Please wait while updating repo's" 6 60 0
#########################################Screen size########################################################
calc_wt_size() {
  # NOTE: it's tempting to redirect stderr to /dev/null, so supress error
  # output from tput. However in this case, tput detects neither stdout or
  # stderr is a tty and so only gives default 80, 24 values
  WT_HEIGHT=17
  WT_WIDTH=$(tput cols)

  if [ -z "$WT_WIDTH" ] || [ "$WT_WIDTH" -lt 60 ]; then
    WT_WIDTH=80
  fi
  if [ "$WT_WIDTH" -gt 178 ]; then
    WT_WIDTH=120
  fi
  WT_MENU_HEIGHT=$(($WT_HEIGHT-7))
}
#########################################About########################################################
do_about() {
  whiptail --msgbox "\
This tool is created by techandme.se for less skilled linux terminal users.
It makes your life very easy by just browsing the menu and installing or setting
config value's to your needs. Please post requests or suggestions here:
https://github.com/ezraholm50/MediaCenter/issues/1
Please visit https://www.techandme.se for awsome free virtual machines,
ownCloud, Teamspeak, Wordpress etc.\
" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
#########################################tools menu########################################################
do_tools() {
  FUN=$(whiptail --title "Multi Installer - https://www.techandme.se" --menu "System tools" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT \
    "T1 Show LAN IP, Gateway, Netmask" "Ifconfig" \
    "T2 Show WAN IP" "External IP address" \
    "T3 Change Hostname" "Change your network name" \
    "T4 Internationalisation Options" "Change language, time, date and keyboard layout" \
    "T5 Do distribution upgrade" "Tested on ubuntu, debian might work" \
    "T6 Change current users password" "Current user = $WHOAMI" \
    "T7 Set swappiness to 1" "Avoid swapping when there's much RAM left" \
    "T8 Set DNS" "We will use Comodo secure DNS" \
    "T9 Change Repo's" "under construction" \
    "T10 Set static IP" "DOES NOT WORK, BREAKS CONNECTION, WILL BE FIXED" \
    "T11 Blkid" "Show connected devices" \
    "T12 Df -h" "Show disk space" \
    "T13 Connect to WLAN" "Wifi" \
    "T14 Boot to terminal by default" "Only if you use a GUI/desktop now" \
    "T15 Boot to GUI/desktop by default" "Only if you have a GUI installed" \
    "T16 Show System info" "Package Landscape-common needs to be installed" \
    "T17 Add progress bar" "To apt / apt-get update/install/upgrade" \
    "T18 Current users" "Show current users logged in" \
    "T19 Backup with rsync" "Lets you choose dir/file and dest" \
    "T20 List directory" "Files and permissions" \
    "T21 Disable IPV6" "In grub" \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 1 ]; then
    return 0
  elif [ $RET -eq 0 ]; then
    case "$FUN" in
      T1\ *) do_ifconfig ;;
      T2\ *) do_wan_ip ;;
      T3\ *) do_change_hostname ;;
      T4\ *) do_internationalisation_menu ;;
      T5\ *) do_dist_upgrade ;;
      T6\ *) do_change_pass ;;
      T7\ *) do_swappiness;;
      T8\ *) do_comodo_dns ;;
      T9\ *) do_country_repo ;;
      T10\ *) do_static_ip ;;
      T11\ *) do_blkid ;;
      T12\ *) do_df ;;
      T13\ *) do_wlan ;;
      T14\ *) do_boot_text ;;
      T15\ *) do_boot_gui ;;
      T16\ *) do_landscape ;;
      T17\ *) do_fancy ;;
      T18\ *) do_currentusers ;;
      T19\ *) do_backup ;;
      T20\ *) do_listdir ;;
      T21\ *) do_disableipv6 ;;
      *) whiptail --msgbox "Programmer error: unrecognized option" 20 60 1 ;;
    esac || whiptail --msgbox "There was an error running option $FUN" 20 60 1
  fi
}
#########################################tools menu########################################################
do_disableipv6() {
	sed -i 's|GRUB_CMDLINE_LINUX=""|GRUB_CMDLINE_LINUX="ipv6.disable=1"|g' /etc/default/grub
	update-grub
}

do_listdir() {
	LISTDIR=$(whiptail --title "Directory to list? Eg. /mnt/yourfolder" --inputbox "Navigate with TAB to hit ok to enter input" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT 3>&1 1>&2 2>&3)
	LISTDIR1=$(ls -la $LISTDIR)
	whiptail --msgbox "$LISTDIR1" 30 $WT_WIDTH $WT_MENU_HEIGHT

}
######Tools variable's#######
do_backup() {
	BACKUPDIR=$(whiptail --title "Backup directory? Eg. /mnt/yourfolder" --inputbox "Navigate with TAB to hit ok to enter input" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT 3>&1 1>&2 2>&3)
	BACKUPDEST=$(whiptail --title "Backup destination? Eg. /mnt/yourfolder" --inputbox "Navigate with TAB to hit ok to enter input" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT 3>&1 1>&2 2>&3)
	if [ $(dpkg-query -W -f='${Status}' rsync 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        echo "Rsync is already installed!"

else
	apt-get install rsync -y
fi
	rsync -aAXv $BACKUPDIR $BACKUPDEST
}
######Tools variable's#######
do_currentusers() {
   	USERLIST=$(userlist)
   	if [ $(dpkg-query -W -f='${Status}' cfingerd 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        echo "Cfingerd is already installed!"

else
	apt-get install cfingerd -y
fi
   	whiptail --msgbox "$USERLIST" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_landscape() {
	SYSINFO=$($DIR/50-landscape-sysinfo)
	HEADER=$($DIR/00-header)
	UPDATES=$($DIR/90-updates-available)
	RELEASE=$($DIR/91-release-upgrade)
	FSCK=$($DIR/98-fsck-at-reboot)
	REBOOT=$($DIR/98-reboot-required)
	whiptail --msgbox "\
$HEADER
$SYSINFO
$UPDATES
$RELEASE
$FSCK
$REBOOT\
" 40 80
}
######Tools variable's#######
do_fancy() {
	echo "Dpkg::Progress-Fancy "1";" > /etc/apt/apt.conf.d/99progressbar
	whiptail --msgbox "You now have a fancy progress bar in green, outside this installer run apt or apt-get install <package>" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_boot_text() {
	sed -i 's|GRUB_CMDLINE_LINUX_DEFAULT=""|GRUB_CMDLINE_LINUX_DEFAULT="text"|g' /etc/default/grub
	update-grub
}
######Tools variable's#######
do_boot_gui() {
	sed -i 's|GRUB_CMDLINE_LINUX_DEFAULT="text"|GRUB_CMDLINE_LINUX_DEFAULT=""|g' /etc/default/grub
	update-grub
}
######Tools variable's#######
do_wlan() {
	IWLIST=$(iwlist wlan0 scanning|grep -i 'essid')
	whiptail --msgbox "Next you will be shown a list with wireless access points, copy yours.." $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
	whiptail --msgbox "$IWLIST" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
	WLAN=$(whiptail --title "SSID, network name? (case sensetive)" --inputbox "Navigate with TAB to hit ok to enter input" 10 60 3>&1 1>&2 2>&3)
	WLANPASS=$(whiptail --title "Wlan password? (case sensetive)" --passwordbox "Navigate with TAB to hit ok to enter input" 10 60 3>&1 1>&2 2>&3)
	if [ $exitstatus = 0 ]; then

	if [ $(dpkg-query -W -f='${Status}' linux-firmware 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        echo "Linux-firmware is already installed!"

else
	apt-get install linux-firmware -y
fi

	if [ $(dpkg-query -W -f='${Status}' wpasupplicant 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        echo "Wpasupplicant is already installed!"

else
	apt-get install wpasupplicant -y
fi

	ifup wlan0
	iwconfig wlan0 essid $WLAN key s:$WLANPASS
	ifdown wlan0
	ifup wlan0
	dhcpcd -r
	dhcpcd wlan0
	else
    	echo "You chose Cancel."
	fi
}
######Tools variable's#######
do_df() {
  DF=$(df -h)
  whiptail --msgbox "$DF" 20 $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_blkid() {
  BLKID=$(blkid)
  whiptail --msgbox "$BLKID" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_ifconfig() {
whiptail --msgbox "\
Interface:$IFACE
LAN IP: $ADDRESS
Netmask: $NETMASK
Gateway: $GATEWAY\
" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_wan_ip() {
  WAN=$(wget -qO- http://ipecho.net/plain ; echo)
  whiptail --msgbox "WAN IP: $WAN" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
######Tools variable's#######
do_change_pass() {
	USERPASS=$(whiptail --title "User to change pass for? (case sensetive)" --inputbox "Navigate with TAB to hit ok to enter input" 10 60)
  	passwd $USERPASS &&
  	whiptail --msgbox "Password changed successfully" 20 60 1
}
######Tools variable's#######
do_internationalisation_menu() {
  FUN=$(whiptail --title "Multi Installer - https://www.techandme.se" --menu "Internationalisation Options" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT --cancel-button Back --ok-button Select \
    "I1 Change Locale" "Set up language and regional settings to match your location" \
    "I2 Change Timezone" "Set up timezone to match your location" \
    "I3 Change Keyboard Layout" "Set the keyboard layout to match your keyboard" \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 1 ]; then
    return 0
  elif [ $RET -eq 0 ]; then
    case "$FUN" in
      I1\ *) do_change_locale ;;
      I2\ *) do_change_timezone ;;
      I3\ *) do_configure_keyboard ;;
      *) whiptail --msgbox "Programmer error: unrecognized option" 20 60 1 ;;
    esac || whiptail --msgbox "There was an error running option $FUN" 20 60 1
  fi
}
######Tools variable's#######
do_configure_keyboard() {
  dpkg-reconfigure keyboard-configuration &&
  printf "Reloading keymap. This may take a short while\n" &&
  invoke-rc.d keyboard-setup start
}
######Tools variable's#######
do_change_locale() {
  dpkg-reconfigure locales
}
######Tools variable's#######
do_change_timezone() {
  dpkg-reconfigure tzdata
}
######Tools variable's#######
do_change_hostname() {
  whiptail --msgbox "\
Please note: RFCs mandate that a hostname's labels \
may contain only the ASCII letters 'a' through 'z' (case-insensitive),
the digits '0' through '9', and the hyphen.
Hostname labels cannot begin or end with a hyphen.
No other symbols, punctuation characters, or blank spaces are permitted.\
" 20 70 1

  CURRENT_HOSTNAME=`cat /etc/hostname | tr -d " \t\n\r"`
  NEW_HOSTNAME=$(whiptail --inputbox "Please enter a hostname" 20 60 "$CURRENT_HOSTNAME" 3>&1 1>&2 2>&3)
  if [ $? -eq 0 ]; then
    echo $NEW_HOSTNAME > /etc/hostname
    sed -i "s/127.0.1.1.*$CURRENT_HOSTNAME/127.0.1.1\t$NEW_HOSTNAME/g" /etc/hosts
    ASK_TO_REBOOT=1
  fi
}
######Tools variable's#######
do_dist_upgrade() {
	do-release-upgrade -y
}
######Tools variable's#######
do_swappiness() {
	sed -i 's|vm.swappiness = |#vm.swappiness = |g' /etc/sysctl.conf
	echo "vm.swappiness = 1" >> /etc/sysctl.conf
	sysctl vm.swappiness=1
}
######Tools variable's#######
do_comodo_dns() {
	cat /dev/null > /etc/resolvconf/resolv.conf.d/base
	echo "nameserver 8.26.56.26" >> /etc/resolvconf/resolv.conf.d/base
	echo "nameserver 8.20.247.20" >> /etc/resolvconf/resolv.conf.d/base
	resolvconf -u
}
######Tools variable's#######
do_country_repo() {
	SHOWCOUNT=$(cat /etc/apt/sources.list)
	whiptail --msgbox "Notice your current country code (2 letters eg. NL, US)" 20 70
	COUNTRYCUR=$(whiptail --title "What is the current country code? (2 letters eg. NL, US)" --inputbox "Navigate with TAB to hit ok to enter input" 10 60)
	COUNTRY=$(whiptail --title "What is your country code? (2 letters eg. NL, US)" --inputbox "Navigate with TAB to hit ok to enter input" 10 60)
	sed -i "s|$COUNTRYCUR|$COUNTRY|" /etc/apt/sources.list
	apt-get update
}
######Tools variable's#######
do_static_ip() {
wget https://raw.githubusercontent.com/enoch85/ownCloud-VM/master/static/test_connection.sh -P $SCRIPTS
echo -e "\e[0m"
echo "The script will now configure your IP to be static."
echo -e "\e[36m"
echo -e "\e[1m"
echo "Your internal IP is: $ADDRESS"
echo -e "\e[0m"
echo -e "Write this down, you will need it to set static IP"
echo -e "\e[32m"
read -p "Press any key to set static IP..." -n1 -s
clear
echo -e "\e[0m"
ifdown $IFACE
sleep 2
ifup $IFACE
sleep 2

cat <<-IPCONFIG > "$INTERFACES"
        auto lo $IFACE
        iface lo inet loopback
        iface $IFACE inet static
                address $ADDRESS
                netmask $NETMASK
                gateway $GATEWAY
# Exit and save:	[CTRL+X] + [Y] + [ENTER]
# Exit without saving:	[CTRL+X]
IPCONFIG

ifdown $IFACE
sleep 2
ifup $IFACE
sleep 2
echo
echo "Testing if network is OK..."
sleep 1
echo
bash /var/scripts/test_connection.sh
sleep 2
echo
echo -e "\e[0mIf the output is \e[32mConnected! \o/\e[0m everything is working."
echo -e "\e[0mIf the output is \e[31mNot Connected!\e[0m you should change\nyour settings manually in the next step."
echo -e "\e[32m"
read -p "Press any key to open /etc/network/interfaces..." -n1 -s
echo -e "\e[0m"
nano /etc/network/interfaces
clear &&
echo "Testing if network is OK..."
ifdown $IFACE
sleep 2
ifup $IFACE
sleep 2
echo
bash /var/scripts/test_connection.sh
sleep 2
clear
}
#########################################Firewall menu########################################################
do_firewall() {
  FUN=$(whiptail --title "Multi Installer - https://www.techandme.se" --menu "Firewall options" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT --cancel-button Back --ok-button Select \
    "A1 Enable Firewall" "" \
    "A2 Disable Firewall" "" \
    "A3 Allow port Multiple" "Teamspeak" \
    "A4 Allow port 32400" "Plex" \
    "A5 Allow port 8989" "Sonarr" \
    "A6 Allow port 5050" "Couchpotato" \
    "A7 Allow port 8181" "Headphones" \
    "A8 Allow port 8085" "HTPC Manager" \
    "A9 Allow port 8080" "Mylar" \
    "A10 Allow port 10000" "Webmin" \
    "A11 Allow port 8080" "Sabnzbdplus" \
    "A12 Allow port 9090" "Sabnzbdplus https" \
    "A13 Allow port 2049" "NFS" \
    "A14 Deny port Multiple" "Teamspeak" \
    "A15 Deny port 32400" "Plex" \
    "A16 Deny port 8989" "Sonarr" \
    "A17 Deny port 5050" "Couchpotato" \
    "A18 Deny port 8181" "Headphones" \
    "A19 Deny port 8085" "HTPC Manager" \
    "A20 Deny port 8080" "Mylar" \
    "A21 Deny port 10000" "Webmin" \
    "A22 Deny port 8080" "Sabnzbdplus" \
    "A23 Deny port 9090" "Sabnzbdplus https" \
    "A24 Deny port 2049" "NFS" \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 1 ]; then
    return 0
  elif [ $RET -eq 0 ]; then
    case "$FUN" in
      A1\ *) do_ufw_enable ;;
      A2\ *) do_ufw_disable ;;
      A3\ *) do_allow_teamspeak ;;
      A4\ *) do_allow_32400 ;;
      A5\ *) do_allow_8989 ;;
      A6\ *) do_allow_5050 ;;
      A7\ *) do_allow_8181 ;;
      A8\ *) do_allow_8085 ;;
      A9\ *) do_allow_mylar ;;
      A10\ *) do_allow_10000 ;;
      A11\ *) do_allow_8080 ;;
      A12\ *) do_allow_9090 ;;
      A13\ *) do_allow_2049 ;;
      A14\ *) do_deny_teamspeak ;;
      A15\ *) do_deny_32400 ;;
      A16\ *) do_deny_8989 ;;
      A17\ *) do_deny_5050 ;;
      A18\ *) do_deny_8181 ;;
      A19\ *) do_deny_8085 ;;
      A20\ *) do_deny_mylar ;;
      A21\ *) do_deny_10000 ;;
      A22\ *) do_deny_8080 ;;
      A23\ *) do_deny_9090 ;;
      A24\ *) do_deny_2049 ;;
      *) whiptail --msgbox "Programmer error: unrecognized option" 20 60 1 ;;
    esac || whiptail --msgbox "There was an error running option $FUN" 20 60 1
  fi
}
#########################################Firewall menu########################################################

######Firewall variable's#######
do_ufw_enable() {
sudo ufw enable
}
######Firewall variable's#######
do_ufw_disable() {
sudo ufw disable
}
######Firewall variable's#######
do_allow_32400() {
sudo ufw allow 32400
}
######Firewall variable's#######
do_allow_10000() {
sudo ufw allow 10000
}
######Firewall variable's#######
do_allow_5050() {
sudo ufw allow 5050
}
######Firewall variable's#######
do_allow_9090() {
sudo ufw allow 9090
}
######Firewall variable's#######
do_allow_8080() {
sudo ufw allow 8080
}
######Firewall variable's#######
do_allow_8989() {
sudo ufw allow 8989
}
######Firewall variable's#######
do_allow_8181() {
sudo ufw allow 8181
}
######Firewall variable's#######
do_allow_8085() {
sudo ufw allow 8085
}
######Firewall variable's#######
do_allow_mylar() {
sudo ufw allow 8080
}
######Firewall variable's#######
do_allow_2049() {
sudo ufw allow 2049
}
######Firewall variable's#######
do_allow_teamspeak() {
sudo ufw allow 9987
sudo ufw allow 10011
sudo ufw allow 30033
}
######Firewall variable's#######
do_deny_32400() {
sudo ufw deny 32400
}
######Firewall variable's#######
do_deny_10000() {
sudo ufw deny 10000
}
######Firewall variable's#######
do_deny_5050() {
sudo ufw deny 5050
}
######Firewall variable's#######
do_deny_9090() {
sudo ufw deny 9090
}
######Firewall variable's#######
do_deny_8080() {
sudo ufw deny 8080
}
######Firewall variable's#######
do_deny_8989() {
sudo ufw deny 8989
}
######Firewall variable's#######
do_deny_8181() {
sudo ufw deny 8181
}
######Firewall variable's#######
do_deny_8085() {
sudo ufw deny 8085
}
######Firewall variable's#######
do_deny_mylar() {
sudo ufw deny 8080
}
######Firewall variable's#######
do_deny_2049() {
sudo ufw deny 2049
}
######Firewall variable's#######
do_deny_teamspeak() {
sudo ufw deny 9987
sudo ufw deny 10011
sudo ufw deny 30033
}
#########################################Upgrade and update system and tool########################################################
do_update_full() {
  apt-get autoclean -y
  apt-get autoremove -y
  apt-get update
  apt-get upgrade -y
  apt-get -f install -y
  dpkg --configure --pending
  rm $SCRIPTS/MultiInstaller.sh
  mkdir -p $SCRIPTS
  wget $REPO/MultiInstaller.sh -P $SCRIPTS/
  printf "Sleeping 5 seconds before reloading the Multi Installer\n"
  sleep 5
  bash $SCRIPTS/MultiInstaller.sh
}
#########################################Finish and reboot?########################################################
do_finish() {
  if [ $ASK_TO_REBOOT -eq 1 ]; then
    whiptail --yesno "Would you like to reboot now?" 20 60 2
    if [ $? -eq 0 ]; then # yes
      sync
      reboot
    fi
  fi
  exit 0
}
#########################################Install menu########################################################
do_install_menu() {
  FUN=$(whiptail --title "Multi Installer - https://www.techandme.se" --menu "Package list" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT --cancel-button Back --ok-button Select \
    "I1 Install Package" "User defined" \
    "I2 Install Webmin" "Graphical interface to manage headless systems" \
    "I3 Install SSH Server" "Needed by a remote machine to be accessable via SSH" \
    "I4 Install SSH Client" "Needed by the local machine to connect to a remote machine" \
    "I5 Change SSH-server port" "Change SSH-server port to 8822" \
    "I6 Install ClamAV" "Antivirus, set daily scans, infected will be moved to /infected" \
    "I7 Install Fail2Ban" "Install a failed login monitor, needs jails for apps!!!!" \
    "I8 Install Nginx" "Install Nginx webserver" \
    "I9 Install Teamspeak" "Install Teamspeak 3 server to do voice chat" \
    "I10 Install NFS Client" "Install NFS client to be able to mount NFS shares" \
    "I11 Install NFS Server" "Install NFS server to be able to broadcast NFS shares" \
    "I12 Install DDClient" "Update Dynamic Dns with WAN IP, dyndns.com, easydns.com etc." \
    "I13 Install Letsencrypt" "Install free valid SSL certificates with your domain name" \
    "I14 Install Rsync" "Install a sync package to backup/copy filesystems/folders/files" \
    "I15 Install Samba" "Under construction" \
    "I16 Install Landscape-common" "System monitoring" \
    "I17 Install Htop" "Graphical tool to see current mem usage/cpu etc." \
    "I18 Install Network manager" "Advanced network tools" \
    "I19 Install ownCloud" "Your own Dropbox/google drive" \
    "I20 Install OpenVpn" "Connect to a VPN server" \
    "I21 Install Plex" "Media server, Public release no plexpass. Auto updates are set." \
    "I22 Install Vnc server" "With LXDE minimal/core desktop, only use with SSH." \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 1 ]; then
    return 0
  elif [ $RET -eq 0 ]; then
    case "$FUN" in
      I1\ *) do_install_package ;;
      I2\ *) do_install_webmin ;;
      I3\ *) do_install_SSH_server ;;
      I4\ *) do_install_SSH_client ;;
      I5\ *) do_ssh ;;
      I6\ *) do_clamav ;;
      I7\ *) do_fail2ban ;;
      I8\ *) do_nginx ;;
      I9\ *) do_teamspeak ;;
      I10\ *) do_install_nfs_client ;;
      I11\ *) do_install_nfs_server ;;
      I12\ *) do_install_ddclient ;;
      I13\ *) do_install_letsencrypt ;;
      I14\ *) do_install_rsync ;;
      I15\ *) do_install_samba ;;
      I16\ *) do_install_landscape ;;
      I17\ *) do_install_htop ;;
      I18\ *) do_install_networkmanager ;;
      I19\ *) do_install_owncloud ;;
      I20\ *) do_install_openvpn ;;
      I21\ *) do_install_plex ;;
      I22\ *) do_install_vnc ;;
      *) whiptail --msgbox "Programmer error: unrecognized option" 20 60 1 ;;
    esac || whiptail --msgbox "There was an error running option $FUN" 20 60 1
  fi
}
#########################################Install menu########################################################
do_install_vnc() {
apt-get install xorg lxde-core tightvncserver -y
tightvncserver :1
tightvncserver -kill :1
echo 'lxterminal &' >> ~/.vnc/xstartup
echo '/usr/bin/lxsession -s LXDE &' >> ~/.vnc/xstartup
/usr/bin/lxsession -s LXDE &
tightvncserver :1
ufw allow 5901
whiptail --msgbox "Firewall port updated (5901). Start: tightvncserver :1 - Stop tightvncserver -kill :1" 20 60 1
}
########Install variable's########
do_install_package() {
	PACKAGE=$(whiptail --title "Package name?" --inputbox "Navigate with TAB to hit ok to enter input" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT)

	if [ $(dpkg-query -W -f='${Status}' $PACKAGE 2>/dev/null | grep -c "ok installed") -eq 1 ];
then
        echo "$PACKAGE is already installed!"

else
	apt-get install $PACKAGE -y
fi
}
########Install variable's########
do_install_openvpn() {
	apt-get install openvpn -y
}
########Install variable's########
do_install_owncloud() {
	apt-get install libreoffice -y
	wget https://github.com/enoch85/ownCloud-VM/raw/master/production/owncloud_install_production.sh -P /var/scripts/
	bash /var/scripts/owncloud_install_production.sh
	#whiptail --msgbox "We will now reboot and start the ownCloud installation" 20 60 1
	reboot
}
########Install variable's########
do_install_networkmanager() {
	apt-get install network-manager -y
}
########Install variable's########
do_install_landscape() {
	apt-get install landscape-common -y
}
########Install variable's########
do_install_htop() {
	apt-get install htop -y
}
########Install variable's########
do_install_samba() {
	apt-get install samba smbfs -y
	sed -i 's|;  security = user|security = user|g' /etc/samba/smb.conf
	echo "username map = /etc/samba/smbusers" > /etc/samba/smb.conf
	USRS=$(whiptail --title "Samba username, create one please" --inputbox "Navigate with TAB to hit ok to enter input" 10 60 3>&1 1>&2 2>&3)
	USRU=$(whiptail --title "Ubuntu username? Should not be root!" --inputbox "Navigate with TAB to hit ok to enter input" 10 60 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus = 0 ]; then
    	echo "$USRU = '$USRS'" > /tmp/smbusers
	else
    	echo "You chose Cancel."
	fi

	PASSWORD=$(whiptail --title "Samba user password" --passwordbox "Navigate with TAB to hit ok to enter input" 10 60 3>&1 1>&2 2>&3)
 	exitstatus=$?
	if [ $exitstatus = 0 ]; then
     	smbpasswd -a  $USRS
	$PASSWORD
	else
    	echo "You chose Cancel."
	fi
}
########Install variable's########
do_install_plex() {
  apt-get install wget git -y
  wget https://downloads.plex.tv/plex-media-server/0.9.16.6.1993-5089475/plexmediaserver_0.9.16.6.1993-5089475_amd64.deb -P /tmp/
	dpkg -i /tmp/plexmediaserver_0.9.16.6.1993-5089475_amd64.deb
	cd /root

if 		[ -d /root/plexupdate ];
then
	rm -r /root/plexupdate
fi

	git clone https://github.com/mrworf/plexupdate.git
	touch /root/.plexupdate
	cat <<-PLEX > "/root/.plexupdate"
	DOWNLOADDIR="/tmp"
	RELEASE="64"
	KEEP=no
	FORCE=no
	PUBLIC=yes
	AUTOINSTALL=yes
	AUTODELETE=yes
	AUTOUPDATE=yes
  AUTOSTART=yes
	PLEX
if 		[ -f /etc/cron.daily/plex.sh ];
then
	sleep 1
else
	echo "bash /root/plexupdate/plexupdate.sh" >> /etc/cron.daily/plex.sh
	chmod 754 /etc/cron.daily/plex.sh
fi
}
########Install variable's########
do_install_webmin() {
  	apt-get install perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions python -y
	echo 'deb http://download.webmin.com/download/repository sarge contrib' >> /etc/apt/sources.list
	cd /root
	wget http://www.webmin.com/jcameron-key.asc
	apt-key add jcameron-key.asc
	cd
	apt-get update
	apt-get install webmin -y
	ufw allow 10000
	whiptail --msgbox "Webmin is installed https://$ADDRESS:10000" 20 60 1
}
########Install variable's########
do_install_SSH_server() {
	apt-get install openssh-server -y
  	sed -i 's|PermitEmptyPasswords yes|PermitEmptyPasswords no|g' /etc/ssh/sshd_config
}
########Install variable's########
do_install_SSH_client() {
  	apt-get install openssh-client -y
}
########Install variable's########
do_ssh() {
  	ufw allow 8822
  	ufw deny 22
  	sed -i 's|22|8822|g' /etc/ssh/sshd_config
  	echo
  	echo "After the reboot you can use port 8822 for SSH"
}
########Install variable's########
do_clamav() {
  	apt-get install clamav -y
  	mkdir -p /infected
  	chmod -R nobody:nogroup /infected
  	chown -R 000 /infected
  	echo "freshclam && clamscan -r --move=/infected / && chown -R nodbody:nogroup /infected && chmod -R 000 /infected " >> /etc/cron.daily/clamscan.sh
  	chmod 754 /etc/cron.daily/clamscan.sh
}
########Install variable's########
do_fail2ban() {
  	apt-get install fail2ban -y
}
########Install variable's########
do_nginx() {
  	apt-get install nginx -y
  	ufw allow 443
  	ufw allow 80
}
########Install variable's########
do_teamspeak() {
# Add user
useradd teamspeak3
sed -i 's|:/home/teamspeak3:|:/home/teamspeak3:/usr/sbin/nologin|g' /etc/passwd

# Get Teamspeak
wget http://ftp.4players.de/pub/hosted/ts3/releases/3.0.10.3/teamspeak3-server_linux-amd64-3.0.10.3.tar.gz -P /tmp

# Unpack Teamspeak
tar xzf /tmp/teamspeak3-server_linux-amd64-3.0.10.3.tar.gz

# Move to right directory
mv /tmp/teamspeak3-server_linux-amd64 /usr/local/teamspeak3

# Set ownership
chown -R teamspeak3 /usr/local/teamspeak3

# Add to upstart
ln -s /usr/local/teamspeak3/ts3server_startscript.sh /etc/init.d/teamspeak3
update-rc.d teamspeak3 defaults

# Warning
echo -e "\e[32m"
echo    "+--------------------------------------------------------------------+"
echo    "| Next you will need to copy/paste 3 things to a safe location       |"
echo    "|                                                                    |"
echo -e "|         \e[0mLOGIN, PASSWORD, SECURITY TOKEN\e[32m                            |"
echo    "|                                                                    |"
echo -e "|         \e[0mIF YOU FAIL TO DO SO, YOU HAVE TO REINSTALL YOUR SYSTEM\e[32m    |"
echo -e "|         \e[0mIn 30 Sec the script will continue, so be quick!/e[32m           |"
echo    "+--------------------------------------------------------------------+"
echo
read -p "Press any key to start copying the important stuff to a safe location..." -n1 -s
echo -e "\e[0m"
echo

# Start service
service teamspeak3 start && sleep 30
echo
function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}
if [[ "yes" == $(ask_yes_or_no "Did you copy all the details?") ]]
then
	sleep 1
	echo
else
      sleep 30
      echo "I will give you another 30 seconds, please hurry!"
      echo
fi
}
########Install variable's########
do_install_nfs_client() {
	apt-get install nfs-common -y
  	ufw allow 2049
  	whiptail --msgbox 'auto mount like this: echo "<nfs-server-IP>:/   /mount_point   nfs    auto  0  0" >> /etc/fstab' $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
########Install variable's########
do_install_nfs_server() {
  	apt-get install nfs-kernel-server -y
  	ufw allow 2049
  	whiptail --msgbox "You can broadcast your NFS server and set it up in webmin (when installed): https://$ADDRESS:10000" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT
}
########Install variable's########
do_install_ddclient() {
function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}
if [[ "yes" == $(ask_yes_or_no "Do you have a DynDns service purchased at DynDns.com or Easydns etc?") ]]
then
	echo
    	echo "If the script asks for a network device fill in this: $IFACE"
    	echo -e "\e[32m"
    	read -p "Press any key to continue... " -n1 -s
    	echo -e "\e[0m"
	sudo apt-get install ddclient -y
	echo "ddclient" >> /etc/cron.daily/dns-update.sh
	chmod 755 /etc/cron.daily/dns-update.sh
else
sleep 1
fi
}
########Install variable's########
do_install_letsencrypt() {
function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}
if [[ "yes" == $(ask_yes_or_no "Do you want to install a real certificate from Letsencrypt to secure your WAN access to the server.?") ]]
then
	wget $REPO/letsencrypt.sh -P $SCRIPTS/
	wget $REPO/echo_letsencrypt.sh -P $SCRIPTS/
	bash $SCRIPTS/echo_letsencrypt.sh

	function ask_yes_or_no() {
    	read -p "$1 ([y]es or [N]o): "
    	case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}
if [[ "no" == $(ask_yes_or_no "Are you sure you want to continue?") ]]
then
	echo
    	echo "OK, but if you want to run this script later, just type: sudo bash /var/scripts/letsencrypt.sh"
    	echo -e "\e[32m"
    	read -p "Press any key to continue... " -n1 -s
    	echo -e "\e[0m"
fi

        function ask_yes_or_no() {
        read -p "$1 ([y]es or [N]o): "
        case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}
if [[ "no" == $(ask_yes_or_no "Have you forwarded port 443 in your router?") ]]
then
        echo
        echo "OK, but if you want to run this script later, just type: sudo bash /var/scripts/letsencrypt.sh"
        echo -e "\e[32m"
        read -p "Press any key to continue... " -n1 -s
        echo -e "\e[0m"
fi

    	function ask_yes_or_no() {
    	read -p "$1 ([y]es or [N]o): "
    	case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
	*)     echo "no" ;;
	esac
}
if [[ "yes" == $(ask_yes_or_no "Do you have a domian that you will use?") ]]
then
        sleep 1
else
	echo
    	echo "OK, but if you want to run this script later, just type: sudo bash /var/scripts/letsencrypt.sh"
    	echo -e "\e[32m"
    	read -p "Press any key to continue... " -n1 -s
    	echo -e "\e[0m"
fi

# Install git
	git --version 2>&1 >/dev/null
	GIT_IS_AVAILABLE=$?
# ...
	if [ $GIT_IS_AVAILABLE -eq 1 ]; then
        sleep 1
else
        apt-get install git -y -q
fi

	cd /var
	git clone https://github.com/letsencrypt/letsencrypt
	cd letsencrypt
	./letsencrypt-auto certonly --agree-tos
	cd
else
	echo
    	echo "OK, but if you want to run this script later, just type: sudo bash /var/scripts/letsencrypt.sh"
    	echo -e "\e[32m"
    	read -p "Press any key to continue... " -n1 -s
    	echo -e "\e[0m"
    	wget $REPO/letsencrypt.sh -P $SCRIPTS/
fi
}
########Install variable's########
do_install_rsync() {
  	apt-get install rsync -y
}
#########################################Update tool########################################################
do_update() {
  	apt-get autoclean
  	apt-get autoremove
  	apt-get update
  	apt-get upgrade -y
  	apt-get -f install
  	dpkg --configure --pending
}
#########################################Atomic toolkit########################################################
do_atomic() {
  	apt-get -y install git-core
	if 		[ -d /root/AtoMiC-ToolKit ];
  	then
	sleep 1
  	else
  	cd /root
  	git clone https://github.com/htpcBeginner/AtoMiC-ToolKit ~/AtoMiC-ToolKit
  	cd
  	fi

	cd ~/AtoMiC-ToolKit
  	bash setup.sh
  	cd
}
#########################################Multi Installer########################################################
# Interactive use loop
calc_wt_size
while true; do
  FUN=$(whiptail --title "https://www.techandme.se" --menu "Multi Installer" $WT_HEIGHT $WT_WIDTH $WT_MENU_HEIGHT --cancel-button Finish --ok-button Select \
    "1 System tools" "Show LAN, WAN ip, change hostname and more" \
    "2 Firewall options" "Enable/disable firewall and allow or deny certain ports" \
    "3 Update system & tool" "Updates and upgrades packages and get the latest version of this tool" \
    "4 Install packages" "ClamAV, Teamspeak, Webmin, NFS, SSH etc." \
    "5 Atomic-Toolkit" "Use the tool to install Sonarr, Couchpotato, Sabnzbd etc."\
    "6 About Multi Installer" "Information about this tool" \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 1 ]; then
    do_finish
  elif [ $RET -eq 0 ]; then
    case "$FUN" in
      1\ *) do_tools ;;
      2\ *) do_firewall;;
      3\ *) do_update_full ;;
      4\ *) do_install_menu ;;
      5\ *) do_atomic ;;
      6\ *) do_about ;;
      *) whiptail --msgbox "Programmer error: unrecognized option" 20 60 1 ;;
    esac || whiptail --msgbox "There was an error running option $FUN" 20 60 1
  else
    exit 1
  fi
done


text:
select  cast(amc as decimal(15,4))/cast(pmc as decimal(15,4)) am_pm_ratio
 from ( select count(*) amc
       from web_sales, household_demographics , time_dim, web_page
       where ws_sold_time_sk = time_dim.t_time_sk
         and ws_ship_hdemo_sk = household_demographics.hd_demo_sk
         and ws_web_page_sk = web_page.wp_web_page_sk
         and time_dim.t_hour between 6 and 6+1
         and household_demographics.hd_dep_count = 8
         and web_page.wp_char_count between 5000 and 5200) `at`,
      ( select count(*) pmc
       from web_sales, household_demographics , time_dim, web_page
       where ws_sold_time_sk = time_dim.t_time_sk
         and ws_ship_hdemo_sk = household_demographics.hd_demo_sk
         and ws_web_page_sk = web_page.wp_web_page_sk
         and time_dim.t_hour between 14 and 14+1
         and household_demographics.hd_dep_count = 8
         and web_page.wp_char_count between 5000 and 5200) pt
 order by am_pm_ratio
 limit 100;

-- end query 1 in stream 0 using template query90.tpl

redpajama_set_name: RedPajamaGithub


text:
<?php
return array (
  'We've sent you an email containing a link that will allow you to reset your password.' => 'Мы отправили вам письмо, содержащее ссылку, которая позволит вам сбросить пароль.',
  'Password recovery!' => 'Восстановление пароля!',
  'back to home' => 'вернуться на главную',
);


text:
I have done some experiments on this. Random thoughts:

## Questions

* Is plugin writing synchronous or asynchronous programming? Or could it be both?

## Ideas to Test

* Put a .beam file somewhere
* Put a .erl file somewhere and Couch compiles it

## Minimal Ceremony

After a hiatus, I've gotten back into Erlang projects again. The obvious, glaring problem is the ceremony.

Goals

1. Suitable as a first Erlang project
2. Hello world in 60 seconds
3. A CouchDB plugin is a plain old .erl file
3. Making a CouchDB plugin does not require the CouchDB source code

## Plugin ideas

Auto refresh views upon doc update
Send an email
Authentication
 * No more org.couchdb.user:*
 * Just general other authentication, LDAP, PAM, whatever

## couch_plugin branch

Why is the plugin_dir user-serviceable? Why not somewhere in priv/ and the admin interface
adds and removes files to that location?

Also let's talk about the minimum viable product. I think the Futon interface is not minimum. To merge this to master, an HTTP interface should be sufficient.

What is this idea of requiring plugins to come from apache.org? It seems restrictive and out of scope for an MVP. Was it removed from the roadmap?

I am not convinced about the installation process. Why can't I simply upload an Erlang release into CouchDB?

Why do the .ini files have to be in `default.d`? That is not a meaningful name to plugin providers. That directory will not go in /etc or anything. Why not config/ or something intuitive?

## Current idea

How to completely streamline the CouchDB plugin story? How to bring in developers as easily as possible? My idea:

1. We bundle the Rebar source in the CouchDB source
2. We build rebar with couch_plugin extensions
3. You fetch rebar over http
4. You run `./rebar create couchdb_plugin` and you get a working, no-op plugin.
6. It is a standard Erlang project. `rebar clean`, `rebar get-deps`, `rebar compile`, etc. CouchDB source *not* needed.
7. There is a `rebar publish` where you can send it back to CouchDB.

To an Erlang or CouchDB developer, the plugin looks like this:

* A standard application tree: app config, supervisor, gen_server
* A `rebar.config` to get you started
* An `include/couchdb.hrl` to work with Couch's records (request, db, user_ctx, etc.)
* A dedicated .ini file for default config values. The .ini also starts the plugin supervisor under couch_secondary_services.
* A priv/ directory for general data files
* An Erlang appliction config file in case your dependencies use `application:get_env()` (e.g. estatsd, zeta, lager, etc.)

To a novice Erlang developer, the plugin looks like this:

* Basically every file you open says *Plugin authors NEED NOT edit this file*
* There is one plain Erlang module, (no behaviours, just a standard module) called `your_plugin_name.erl` it has a very JavaScript-friendly style, `on(Event) -> do_stuff().`

With the "easy" style, you say what event to handle, and write the code to do that. It is suitable for typical plugin tasks: logging, send an email when somebody signs up, stuff like that.

I want to convert all of the Iris changes to plugins. That is a plausible test of the minimum viable product. For my workflow (typical of sysadmins) I want to build plugins when I build CouchDB, and install plugins when I install CouchDB. If I do change plugins, which is rare, I am willing to restart CouchDB. Sure, there is Erlang code updating and maybe it is easy; but for the MVP can restart.

Question about architecture. My idea, at least for "asynchronous" plugins is event notifications. But every plugin does the same thing: forward all events to the plugin gen_server. So every event goes through fan-out, defeating some benefits of Erlang events. On the other hand, (1) event handlers forwarding to their gen_server is a decently correct fan-out implementation; and (2) How many plugins could CouchDB possibly have? A couple? A dozen? It's probably moot.

## This plugin itself

There is the question of keeping state in this module. How to balance simplicity
with the fact that there is no way to keep state at all? I am thinking use the process
dictionary.

Maybe have all plugins register an HTTP handler by default, /_plugins/$name/_debug and the on-rails code lets you define `on(debug) -> {any, term};` And that will be sent to the client as text/plain.


text:
package com.mykumi.designpattern.decorator;

public class WrapperClass extends Decorator {

	public WrapperClass(){
		super();
	}

	public WrapperClass(IComponent iComponent) {
		super(iComponent);
	}

	public String getWelcomeMessage() {
		String result = "Hi! Nice to meet You. ";
		result = result + this.iComponent.getWelcomeMessage();
		return result;
	}
}


text:
<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
 * @Annotation
 *
 * @author Colin O'Dell <colinodell@gmail.com>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Uuid extends Constraint
{
    const TOO_SHORT_ERROR = 'aa314679-dac9-4f54-bf97-b2049df8f2a3';
    const TOO_LONG_ERROR = '494897dd-36f8-4d31-8923-71a8d5f3000d';
    const INVALID_CHARACTERS_ERROR = '51120b12-a2bc-41bf-aa53-cd73daf330d0';
    const INVALID_HYPHEN_PLACEMENT_ERROR = '98469c83-0309-4f5d-bf95-a496dcaa869c';
    const INVALID_VERSION_ERROR = '21ba13b4-b185-4882-ac6f-d147355987eb';
    const INVALID_VARIANT_ERROR = '164ef693-2b9d-46de-ad7f-836201f0c2db';

    protected static $errorNames = [
        self::TOO_SHORT_ERROR => 'TOO_SHORT_ERROR',
        self::TOO_LONG_ERROR => 'TOO_LONG_ERROR',
        self::INVALID_CHARACTERS_ERROR => 'INVALID_CHARACTERS_ERROR',
        self::INVALID_HYPHEN_PLACEMENT_ERROR => 'INVALID_HYPHEN_PLACEMENT_ERROR',
        self::INVALID_VERSION_ERROR => 'INVALID_VERSION_ERROR',
        self::INVALID_VARIANT_ERROR => 'INVALID_VARIANT_ERROR',
    ];

    // Possible versions defined by RFC 4122
    const V1_MAC = 1;
    const V2_DCE = 2;
    const V3_MD5 = 3;
    const V4_RANDOM = 4;
    const V5_SHA1 = 5;
    const V6_SORTABLE = 6;

    const ALL_VERSIONS = [
        self::V1_MAC,
        self::V2_DCE,
        self::V3_MD5,
        self::V4_RANDOM,
        self::V5_SHA1,
        self::V6_SORTABLE,
    ];

    /**
     * Message to display when validation fails.
     *
     * @var string
     */
    public $message = 'This is not a valid UUID.';

    /**
     * Strict mode only allows UUIDs that meet the formal definition and formatting per RFC 4122.
     *
     * Set this to `false` to allow legacy formats with different dash positioning or wrapping characters
     *
     * @var bool
     */
    public $strict = true;

    /**
     * Array of allowed versions (see version constants above).
     *
     * All UUID versions are allowed by default
     *
     * @var int[]
     */
    public $versions = self::ALL_VERSIONS;

    public $normalizer;

    /**
     * {@inheritdoc}
     *
     * @param int[]|null $versions
     */
    public function __construct(
        array $options = null,
        string $message = null,
        array $versions = null,
        bool $strict = null,
        callable $normalizer = null,
        array $groups = null,
        $payload = null
    ) {
        parent::__construct($options, $groups, $payload);

        $this->message = $message ?? $this->message;
        $this->versions = $versions ?? $this->versions;
        $this->strict = $strict ?? $this->strict;
        $this->normalizer = $normalizer ?? $this->normalizer;

        if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
            throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', get_debug_type($this->normalizer)));
        }
    }
}


text:
from django.conf import settings

import os

def get_template_dir(relative_path):
	"""Get the absolute path to the directory from which the given relative path is served.

	Arguments:
	relative_path -- the relative path to a template directory or file

	Returns: the absolute path to the resource's directory

	"""
	full_path = None
	for template_dir in settings.TEMPLATE_DIRS:
		temp_path = os.path.join(template_dir, relative_path)
		if os.path.exists(temp_path):
			full_path = temp_path
			break
	if full_path:
		if os.path.isfile(full_path):
			full_path = os.path.dirname(full_path)
	return full_path


text:
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
require __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'SendGrid.php';
?>


text:
class ApplicationController < ActionController::Base
  include ActionView::Helpers::DateHelper

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def build_profile_path(user)
    profile_path(id: user.id)
  end
  helper_method :build_profile_path

  def build_subphez_path(subphez)
    view_subphez_path(path: subphez.path)
  end
  helper_method :build_subphez_path

  def build_post_path(post)
    view_post_path(path: post.subphez.path, post_id: post.id, guid: post.guid)
  end
  helper_method :build_post_path

  def require_admin!
    unless current_user.is_admin
      redirect_to root_path, alert: "You can't do that."
    end
  end

  def disallow_non_premium(subphez)
    return true unless subphez.is_premium_only
    unless current_user and current_user.is_premium
      redirect_to root_path, alert: 'You must be a premium user to access that content. Please consider buying some Phez Premium.'
      return false
    end
  end

  def after_sign_in_path_for(_resource)
    session[:previous_url] || root_path
  end

  def throttle
    return true unless current_user
    return true if current_user.is_admin || current_user.throttle_exempt
    if current_user.throttled_until
      if current_user.throttled_until > DateTime.now
        throttle_message = "Woah there cowboy! You seem to be doing that awfully fast. Are you some kind of super-human ninja wizard?!?! Please wait #{time_ago_in_words(current_user.throttled_until)} from now before trying that again."
        redirect_to root_path, alert: throttle_message and return false
      else
        current_user.update_attribute(:throttled_until, nil) and return true
      end
    else
      @last_five_minutes_post_count = current_user.posts.last_five_minutes.count
      @last_five_minutes_comment_count = current_user.comments.last_five_minutes.count
      if (@last_five_minutes_post_count >= 5) || (@last_five_minutes_comment_count >= 5)
        current_user.update_attribute(:throttled_until, 30.minutes.from_now)
        throttle_message = "Woah there cowboy! You seem to be doing that awfully fast. Are you some kind of super-human ninja wizard?!?! Please wait #{time_ago_in_words(current_user.throttled_until)} from now before trying that again."
        redirect_to root_path, alert: throttle_message and return false
      end
    end
  end

  def frozen_check!
    return true unless current_user
    if current_user.is_frozen
      redirect_to root_path, alert: 'Your account has been frozen due to suspicious activity or attempting to game the system.'
      return false
    end
    true
  end

end


text:
/*!
 * Custom Headline
 */

(function () {
    'use-strict';

    class Headline {
        constructor ($el) {
            this.$el = $el;
        }

        isEmpty () {
            return this.$el.length === 0;
        }

        isExternal () {
            return this.$el.hasClass('external');
        }

        onClick () {
            if (this.isExternal()) {
                window.open(this.$el.data('href'), '_blank');
            } else {
                window.location.href = this.$el.data('href');
            }
        }
    }

    const $document = $(document);
    $document.ready(() => {
        $document.on('click', '.card', e => {
            const headline = new Headline($(e.currentTarget).find('.headline-cnt'));

            if (!headline.isEmpty()) {
                headline.onClick();
            }
        });
    });
})();


text:
package com.siqisoft.stone.develop.model;

public class Column {

	/**
	 * 列标题
	 */
	private String label = "";

	/**
	 * 注释
	 */
	private String comment = "";

	/**
	 * 列名
	 */
	private String name;

	/**
	 * 属性名
	 */
	private String property;

	/**
	 * 大写属性名
	 */
	private String upperProperty;

	/**
	 * 是否主键
	 */
	private Boolean primaryKey;

	/**
	 * 列类型
	 */
	private Integer dataType;

	/**
	 * 列类型
	 */
	private String typeName;

	/**
	 * java类型
	 */
	private String javaType;

	/**
	 * jdbc类型
	 */
	private String jdbcType;

	/**
	 * 长度
	 */
	private int size;

	/**
	 * 小数部分的位数
	 */
	private int decimalDigits;

	/**
	 * 是否自增长
	 */
	private Boolean autoIncrement = false;

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getUpperProperty() {
		return upperProperty;
	}

	public void setUpperProperty(String upperProperty) {
		this.upperProperty = upperProperty;
	}

	public Boolean getPrimaryKey() {
		return primaryKey;
	}

	public void setPrimaryKey(Boolean primaryKey) {
		this.primaryKey = primaryKey;
	}

	public String getJavaType() {
		return javaType;
	}

	public void setJavaType(String javaType) {
		this.javaType = javaType;
	}

	public String getJdbcType() {
		return jdbcType;
	}

	public void setJdbcType(String jdbcType) {
		this.jdbcType = jdbcType;
	}

	public int getDecimalDigits() {
		return decimalDigits;
	}

	public void setDecimalDigits(int decimalDigits) {
		this.decimalDigits = decimalDigits;
	}

	public Boolean getAutoIncrement() {
		return autoIncrement;
	}

	public void setAutoIncrement(Boolean autoIncrement) {
		this.autoIncrement = autoIncrement;
	}

	public String getTypeName() {
		return typeName;
	}

	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}

	public void setDataType(Integer dataType) {
		this.dataType = dataType;
	}

	public Integer getDataType() {
		return dataType;
	}

	@Override
	public String toString() {
		return "Column [label=" + label + ", comment=" + comment + ", name="
				+ name + ", property=" + property + ", upperProperty="
				+ upperProperty + ", primaryKey=" + primaryKey + ", dataType="
				+ dataType + ", typeName=" + typeName + ", javaType="
				+ javaType + ", jdbcType=" + jdbcType + ", size=" + size
				+ ", decimalDigits=" + decimalDigits + ", autoIncrement="
				+ autoIncrement + "]";
	}

}


text:
<?php

    namespace Neoform\Router;

    use Neoform\Request;
    use Neoform;

    class Builder {

        /**
         * @var Neoform\Router\Config
         */
        protected $config;

        /**
         * @var Neoform\Request\Builder
         */
        protected $requestBuilder;

        /**
         * @var ControllerDetails
         */
        protected $controllerDetails;

        /**
         * @var string[]
         */
        protected $controllerSlugs = [];

        /**
         * @var string[]
         */
        protected $nonControllerSlugs;

        /**
         * @var bool
         */
        protected $userAuthenticationRequired = false;

        /**
         * @var bool
         */
        protected $userForbidden = false;

        /**
         * @param Neoform\Request\Builder $requestBuilder
         * @param Neoform\Router\Config   $config
         * @param array                   $controllerMap
         */
        public function __construct(Neoform\Request\Builder $requestBuilder, Neoform\Router\Config $config, array $controllerMap) {
            $this->requestBuilder = $requestBuilder;
            $this->config         = $config;

            $slugs = $this->requestBuilder->getPath()->getSlugs();

            $this->determineController(
                $slugs,
                $controllerMap
            );

            // Assign the remaining slugs as being "non-controller" slugs
            $this->nonControllerSlugs = $this->controllerSlugs ?
                array_slice($slugs->toArray(), count($this->controllerSlugs)) : $slugs->toArray();

            // Name the slug variables based on the controller config
            $this->applyNamedSlugs();
        }

        /**
         * Determine which controller is to be loaded
         *
         * @param Request\Parameters\Slugs $slugs
         * @param array                    $controllerMap
         */
        protected function determineController(Request\Parameters\Slugs $slugs, array $controllerMap) {

            $controllerRequiresSecure = 0;

            $controller = $controllerMap;

            foreach ($slugs->toArray() as $k => $slug) {

                // Doesn't apply to the first (root) slug
                if ($k === 0) {

                } else if (isset($controller[$slug])) {
                    $controller = $controller[$slug];

                // No more controllers matched
                } else {
                    break;
                }

                // If permissions set, make sure user has matching permissions
                if ($controller['resource_ids'] && ! $this->authenticated($controller['resource_ids'])) {
                    break;
                }

                $this->controllerSlugs[] = $slug;

                $controllerRequiresSecure |= (int) $controller['secure'];

                $this->controllerDetails = new ControllerDetails(
                    $controller['controller_class'],
                    $controller['action_name'],
                    (bool) $controllerRequiresSecure,
                    $controller['slugs']
                );

                if (! $controller['children']) {
                    break;
                }

                $controller = $controller['children'];
            }
        }

        /**
         * Apply the naming of slugs based on the selected controller
         */
        protected function applyNamedSlugs() {
            if ($this->controllerDetails->getNamedSlugs()) {
                foreach ($this->controllerDetails->getNamedSlugs() as $k => $slugName) {
                    // Grab the value of the offset and re-assign it in the slug array with the new name
                    if (isset($this->nonControllerSlugs[$k])) {
                        $this->nonControllerSlugs[$slugName] = $this->nonControllerSlugs[$k];

                        // Remove the old key so as to not change the array element count
                        unset($this->nonControllerSlugs[$k]);
                    }
                }
            }
        }

        /**
         * Determines if this controller is authenticated
         *
         * @param array $resourceIds
         *
         * @return bool
         */
        protected function authenticated(array $resourceIds) {

            $auth = $this->requestBuilder->getSession()->getAuth();

            // If user is logged in
            if (! $auth->isLoggedIn()) {
                $this->userAuthenticationRequired = true;
                return false;
            }

            if (! $auth->getUser()->hasAccess($resourceIds)) {
                $this->userForbidden = ! $this->config->isSilentAccessDenied();
                return false;
            }

            return true;
        }

        /**
         * Builds the router model
         *
         * @return Model
         */
        public function build() {
            return new Model(
                $this->requestBuilder,
                $this->controllerDetails,
                new Request\Parameters\Slugs($this->nonControllerSlugs),
                new Request\Parameters\Slugs($this->controllerSlugs),
                $this->userAuthenticationRequired,
                $this->userForbidden,
                $this->isRedirectRequired()
            );
        }

        /**
         * @return bool
         */
        protected function isRedirectRequired() {
            $baseUrl = $this->requestBuilder->getBaseUrl();

            if (! $baseUrl->isValid()) {
                return false;
            }

            if ($this->controllerDetails->requiresSecure()) {
                if (! $baseUrl->isValidSecure()) {
                    return true;
                }
            } else {
                if (! $baseUrl->isValidRegular()) {
                    return true;
                }
            }

            return false;
        }
    }


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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Hardware Locality (hwloc): hwloc_obj_memory_s::hwloc_obj_memory_page_type_s Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Hardware Locality (hwloc)
    1.10.1

Main Page

Related Pages

Modules

Data Structures

Data Structures

Data Fields

hwloc_obj_memory_s

hwloc_obj_memory_page_type_s

Data Fields

hwloc_obj_memory_s::hwloc_obj_memory_page_type_s Struct Reference
Object Structure and Attributes

#include <hwloc.h>

Data Fields

hwloc_uint64_t 	size

hwloc_uint64_t 	count

Detailed Description

Array of local memory page types, NULL if no local memory and page_types is 0.

The array is sorted by increasing size fields. It contains page_types_len slots.

Field Documentation

          hwloc_uint64_t hwloc_obj_memory_s::hwloc_obj_memory_page_type_s::count

Number of pages of this size.

          hwloc_uint64_t hwloc_obj_memory_s::hwloc_obj_memory_page_type_s::size

Size of pages.

The documentation for this struct was generated from the following file:

hwloc.h

<address class="footer">
Generated on Mon Jan 26 2015 10:38:04 for Hardware Locality (hwloc) by

 1.8.8
</address>


text:
//
// Copyright (c) 2008-2012 Wouter Demuynck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;

namespace BuildTools
{
	internal static class DateTimeOffsetExtensions
	{
		public static int YearsSince(this DateTimeOffset me, DateTimeOffset other)
		{
			// FIX: Only use the date components of the dates.
			me = me.Date;
			other = other.Date;

			// TODO: Throw decent error message from resources.
			if (other > me)
				throw new ArgumentException("The other date must be earlier than the current date.", "other");

			int years = me.Year - other.Year;
			if (me.Month < other.Month) years--;

			return years;
		}

		public static int MonthsSince(this DateTimeOffset me, DateTimeOffset other)
		{
			// FIX: Only use the date components of the dates.
			me = me.Date;
			other = other.Date;

			if (other > me)
				throw new ArgumentException("The other date must be earlier than the current date.", "other");

			int months = 0;
			int years = me.YearsSince(other);

			if (me.Month < other.Month) months = (me.Month + 12) - other.Month;
			else months = me.Month - other.Month;

			months += years * 12;
			return months;
		}

		public static int DaysSince(this DateTimeOffset me, DateTimeOffset other)
		{
			// FIX: Only use the date components of the dates.
			me = me.Date;
			other = other.Date;

			if (other.Ticks > me.Ticks)
				throw new ArgumentException("The other date must be earlier than the current date.", "other");

			return me.Subtract(other).Days;
		}
	}
}


text:
module LocalizationSimplified
  About = {
    :lang => "en",
    :updated => "2007-08-02"
  }

  class ActiveRecord
    # ErrorMessages to override default messages in
    # +ActiveRecord::Errors::@@default_error_messages+
    # This plugin also replaces hardcoded 3 text messages
    # :error_translation is inflected using the Rails
    # inflector.
    #
    # Remember to modify the Inflector with your localized translation
    # of "error" and "errors" in the bottom of this file
    #
    ErrorMessages = {
      :inclusion           => "is not included in the list",
      :exclusion           => "is reserved",
      :invalid             => "is invalid",
      :confirmation        => "doesn't match confirmation",
      :accepted            => "must be accepted",
      :empty               => "can't be empty",
      :blank               => "can't be blank",# alternate formulation: "is required"
      :too_long            => "is too long (maximum is %d characters)",
      :too_short           => "is too short (minimum is %d characters)",
      :wrong_length        => "is the wrong length (should be %d characters)",
      :taken               => "has already been taken",
      :not_a_number        => "is not a number",
      #Jespers additions:
      :error_translation   => "error",
      :error_header        => "%s prohibited this %s from being saved",
      :error_subheader     => "There were problems with the following fields:"
    }
  end

  # Texts to override +distance_of_time_in_words()+
  class DateHelper
    Texts = {
      :less_than_x_seconds => "less than %d seconds",
      :half_a_minute       => "half a minute",
      :less_than_a_minute  => "less than a minute",
      :one_minute          => "1 minute",
      :x_minutes           => "%d minutes",
      :one_hour            => "about 1 hour",
      :x_hours             => "about %d hours",
      :one_day             => "1 day",
      :x_days              => "%d days",
      :one_month           => "1 month",
      :x_months            => "%d months",
      :one_year            => "1 year",
      :x_years             => "%d years"
    }

    # Rails uses Month names in Date and time select boxes
    # (+date_select+ and +datetime_select+ )
    # Currently (as of version 1.1.6), Rails doesn't use daynames
    Monthnames     = [nil] + %w{January February March April May June July August September October November December}
    AbbrMonthnames = [nil] + %w{Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec}
    Daynames       = %w{Sunday Monday Tuesday Wednesday Thursday Friday Saturday}
    AbbrDaynames   = %w{Sun Mon Tue Wed Thu Fri Sat}

    # Date and time format syntax explained in http://www.rubycentral.com/ref/ref_c_time.html#strftime
    # These are sent to strftime that Ruby's date and time handlers use internally
    # Same options as php (that has a better list: http://www.php.net/strftime )
    DateFormats = {
      :default  => "%Y-%m-%d",
      :short    => "%b %e",
      :long     => "%B %e, %Y"
    }

    TimeFormats = {
      :default  => "%a, %d %b %Y %H:%M:%S %z",
      :short    => "%d %b %H:%M",
      :long     => "%B %d, %Y %H:%M"
    }
    # Set the order of +date_select+ and +datetime_select+ boxes
    # Note that at present, the current Rails version only supports ordering of date_select boxes
    DateSelectOrder = {
      :order    => [:year, :month, :day] #default Rails is US ordered: :order => [:year, :month, :day]
    }
  end

  class NumberHelper
    # CurrencyOptions are used as default for +Number#to_currency()+
    # http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M000449
    CurrencyOptions = {
      :unit      => "$",
      :separator => ".",             #unit separator (between integer part and fraction part)
      :delimiter => ",",             #delimiter between each group of thousands. Example: 1.234.567
      :order     => [:unit, :number] #order is at present unsupported in Rails
      #to support for instance Danish format, the order is different: Unit comes last (ex. "1.234,00 dkr.")
    }
  end

  class ArrayHelper
    # Modifies +Array#to_sentence()+
    # http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000274
    ToSentenceTexts = {
      :connector => 'and',
      :skip_last_comma => false
    }
  end
end

# Use the inflector below to pluralize "error" from
# @@default_error_messages[:error_translation] above (if necessary)
# ( ( ActiveSupport::Inflector if ActiveSupport.const_defined?(:Inflector) ) || Inflector ).inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person people'
#   inflect.uncountable %w( information )
# end


text:
import { TSESTree } from '@typescript-eslint/types';
import { Scope } from './Scope';
import { ScopeBase } from './ScopeBase';
import { ScopeType } from './ScopeType';
import { ScopeManager } from '../ScopeManager';
import { ImplicitLibVariableOptions } from '../variable';
declare class GlobalScope extends ScopeBase<ScopeType.global, TSESTree.Program,
/**
 * The global scope has no parent.
 */
null> {
    private readonly implicit;
    constructor(scopeManager: ScopeManager, block: GlobalScope['block']);
    defineImplicitVariable(name: string, options: ImplicitLibVariableOptions): void;
    close(scopeManager: ScopeManager): Scope | null;
}
export { GlobalScope };
//# sourceMappingURL=GlobalScope.d.ts.map


text:
package com.jfinal.plugin.druid;

import javax.servlet.http.HttpServletRequest;

/**
 * 授权
 */
public interface IDruidStatViewAuth {
	boolean isPermitted(HttpServletRequest request);
}


text:
package org.apache.flink.runtime.checkpoint;

/** A checkpoint, pending or completed. */
public interface Checkpoint {
    long getCheckpointID();

    void discard() throws Exception;
}


text:
$(function() {
	var playVideo = $('video');
	var playPause = $('.playPause'); //播放和暂停
	var currentTime = $('.timebar .currentTime'); //当前时间
	var duration = $('.timebar .duration'); //总时间
	var progress = $('.timebar .progress-bar'); //进度条
	var volumebar = $('.volumeBar .volumewrap').find('.progress-bar');
	playVideo[0].volume = 0.4; //初始化音量
	playPause.on('click', function() {
		playControl();
	});
	$('.playContent').on('click', function() {
		playControl();
	}).hover(function() {
		$('.turnoff').stop().animate({
			'right': 0
		}, 500);
	}, function() {
		$('.turnoff').stop().animate({
			'right': -40
		}, 500);
	});
	$(document).click(function() {
		$('.volumeBar').hide();
	});
	playVideo.on('loadedmetadata', function() {
		duration.text(formatSeconds(playVideo[0].duration));
	});

	playVideo.on('timeupdate', function() {
		currentTime.text(formatSeconds(playVideo[0].currentTime));
		progress.css('width', 100 * playVideo[0].currentTime / playVideo[0].duration + '%');
	});
	playVideo.on('ended', function() {
		$('.playTip').removeClass('glyphicon-pause').addClass('glyphicon-play').fadeIn();
		playPause.toggleClass('playIcon');
	});

	$(window).keyup(function(event){
		event = event || window.event;
			if(event.keyCode == 32)playControl();
			if(event.keyCode == 27){
			$('.fullScreen').removeClass('cancleScreen');
			$('#willesPlay .playControll').css({
				'bottom': -48
			}).removeClass('fullControll');
			};
		event.preventDefault();
	});

	//全屏
	$('.fullScreen').on('click', function() {
		if ($(this).hasClass('cancleScreen')) {
			if (document.exitFullscreen) {
				document.exitFullscreen();
			} else if (document.mozExitFullScreen) {
				document.mozExitFullScreen();
			} else if (document.webkitExitFullscreen) {
				document.webkitExitFullscreen();
			}
			$(this).removeClass('cancleScreen');
			$('#willesPlay .playControll').css({
				'bottom': -48
			}).removeClass('fullControll');
		} else {
			if (playVideo[0].requestFullscreen) {
				playVideo[0].requestFullscreen();
			} else if (playVideo[0].mozRequestFullScreen) {
				playVideo[0].mozRequestFullScreen();
			} else if (playVideo[0].webkitRequestFullscreen) {
				playVideo[0].webkitRequestFullscreen();
			} else if (playVideo[0].msRequestFullscreen) {
				playVideo[0].msRequestFullscreen();
			}
			$(this).addClass('cancleScreen');
			$('#willesPlay .playControll').css({
				'left': 0,
				'bottom': 0
			}).addClass('fullControll');
		}
		return false;
	});
	//音量
	$('.volume').on('click', function(e) {
		e = e || window.event;
		$('.volumeBar').toggle();
		e.stopPropagation();
	});
	$('.volumeBar').on('click mousewheel DOMMouseScroll', function(e) {
		e = e || window.event;
		volumeControl(e);
		e.stopPropagation();
		return false;
	});
	$('.timebar .progress').mousedown(function(e) {
		e = e || window.event;
		updatebar(e.pageX);
	});
	//$('.playContent').on('mousewheel DOMMouseScroll',function(e){
	//	volumeControl(e);
	//});
	var updatebar = function(x) {
		var maxduration = playVideo[0].duration; //Video
		var positions = x - progress.offset().left; //Click pos
		var percentage = 100 * positions / $('.timebar .progress').width();
		//Check within range
		if (percentage > 100) {
			percentage = 100;
		}
		if (percentage < 0) {
			percentage = 0;
		}

		//Update progress bar and video currenttime
		progress.css('width', percentage + '%');
		playVideo[0].currentTime = maxduration * percentage / 100;
	};
	//音量控制
	function volumeControl(e) {
		e = e || window.event;
		var eventype = e.type;
		var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));
		var positions = 0;
		var percentage = 0;
		if (eventype == "click") {
			positions = volumebar.offset().top - e.pageY;
			percentage = 100 * (positions + volumebar.height()) / $('.volumeBar .volumewrap').height();
		} else if (eventype == "mousewheel" || eventype == "DOMMouseScroll") {
			percentage = 100 * (volumebar.height() + delta) / $('.volumeBar .volumewrap').height();
		}
		if (percentage < 0) {
			percentage = 0;
			$('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-off');
		}
		if (percentage > 50) {
			$('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-up');
		}
		if (percentage > 0 && percentage <= 50) {
			$('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-down');
		}
		if (percentage >= 100) {
			percentage = 100;
		}
		$('.volumewrap .progress-bar').css('height', percentage + '%');
		playVideo[0].volume = percentage / 100;
		e.stopPropagation();
		e.preventDefault();
	}

	function playControl() {
			playPause.toggleClass('playIcon');
			if (playVideo[0].paused) {
				playVideo[0].play();
				$('.playTip').removeClass('glyphicon-play').addClass('glyphicon-pause').fadeOut();
			} else {
				playVideo[0].pause();
				$('.playTip').removeClass('glyphicon-pause').addClass('glyphicon-play').fadeIn();
			}
		}
		//关灯
	$('.btnLight').click(function(e) {
		e = e || window.event;
		if ($(this).hasClass('on')) {
			$(this).removeClass('on');
			$('body').append('

');
			$('.overlay').css({
				'position': 'absolute',
				'width': 100 + '%',
				'height': $(document).height(),
				'background': '#000',
				'opacity': 1,
				'top': 0,
				'left': 0,
				'z-index': 999
			});
			$('.playContent').css({
				'z-index': 1000,
                'background': '#000',
			});
			$('.playControll').css({
				'bottom': -48,
				'z-index': 1000
			});

			$('.playContent').hover(function() {
				$('.playControll').stop().animate({
					'height': 48

				},500);
			}, function() {
				setTimeout(function() {
					$('.playControll').stop().animate({
						'height': 0,
					}, 500);
				}, 2000)
			});
		} else {
			$(this).addClass('on');
			$('.overlay').remove();
			$('.playControll').css({
				'bottom': 0,
			});
		}
		e.stopPropagation();
		e.preventDefault();
	});
});

//秒转时间
function formatSeconds(value) {
	value = parseInt(value);
	var time;
	if (value > -1) {
		hour = Math.floor(value / 3600);
		min = Math.floor(value / 60) % 60;
		sec = value % 60;
		day = parseInt(hour / 24);
		if (day > 0) {
			hour = hour - 24 * day;
			time = day + "day " + hour + ":";
		} else time = hour + ":";
		if (min < 10) {
			time += "0";
		}
		time += min + ":";
		if (sec < 10) {
			time += "0";
		}
		time += sec;
	}
	return time;
}


text:
require 'rubybvc'
require 'yaml'

delay = 5

puts "Loading configuration..."
config = YAML.load_file('config_4.yml')

puts "\nStarting Demo 3: Get vRouter configuration"

controller = Controller.new(ip_addr: config['controller']['ip_addr'],
  admin_name: config['controller']['username'],
  admin_password: config['controller']['password'])
vrouter = VRouter5600.new(controller: controller, name: config['node']['name'],
  ip_addr: config['node']['ip_addr'], port_number: config['node']['port_num'],
  admin_name: config['node']['username'],
  admin_password: config['node']['password'])
puts "Controller: #{controller.ip}, #{vrouter.name}: #{vrouter.ip}"

puts "\nAdd #{vrouter.name} to controller"
sleep(delay)
response = controller.add_netconf_node(vrouter)
if response.status == NetconfResponseStatus::OK
  puts "#{vrouter.name} added to the controller"
else
  puts "\nDemo terminated: #{response.message}"
  exit
end

puts "\nCheck #{vrouter.name} connection status"
sleep(delay)
response = controller.check_node_conn_status(vrouter.name)
if response.status == NetconfResponseStatus::NODE_CONNECTED
  puts "#{vrouter.name} is connected to the Controller"
else
  puts "\nDemo terminated: #{response.message}"
  exit
end

puts "\nShow configuration of #{vrouter.name}"
sleep(delay)
response = vrouter.get_cfg
if response.status == NetconfResponseStatus::OK
  puts "#{vrouter.name} configuration: #{JSON.pretty_generate response.body}"
else
  puts "\nDemo terminated: #{response.message}"
  exit
end

puts "\nRemove #{vrouter.name} NETCONF node from controller"
sleep(delay)
response = controller.delete_netconf_node(vrouter)
if response.status == NetconfResponseStatus::OK
  puts "#{vrouter.name} was successfully removed from the controller"
else
  puts "\nDemo terminated: #{response.message}"
end

puts "\nEnd of demo 3"


text:
Fetch watcher alerts from Intel 471 Alerts Stream feed.

* **Username** - Email address to access Intel 471.
* **Password** - API key to access Intel 471. In order to get the API key, see [https://titan.intel471.com/api](https://titan.intel471.com/api) .


text:
import {Project} from './project';

export function Group(params = {}) {
  const project = Project();
  return {
    activity: [],
    annotations: [],
    assignedTo: null,
    count: '327482',
    culprit: 'fetchData(app/components/group/suggestedOwners)',
    firstRelease: null,
    firstSeen: '2019-04-05T19:44:05.963Z',
    hasSeen: false,
    id: '1',
    isBookmarked: false,
    isPublic: false,
    isSubscribed: false,
    lastRelease: null,
    lastSeen: '2019-04-11T01:08:59Z',
    level: 'warning',
    logger: null,
    metadata: {function: 'fetchData', type: 'RequestError'},
    numComments: 0,
    participants: [],
    permalink: 'https://foo.io/organizations/foo/issues/1234/',
    platform: 'javascript',
    pluginActions: [],
    pluginContexts: [],
    pluginIssues: [],
    project: {
      platform: 'javascript',
      id: project.id,
      slug: project.slug,
    },
    seenBy: [],
    shareId: null,
    shortId: 'JAVASCRIPT-6QS',
    stats: {
      '24h': [[1517281200, 2], [1517310000, 1]],
      '30d': [[1514764800, 1], [1515024000, 122]],
    },
    status: 'unresolved',
    statusDetails: {},
    subscriptionDetails: null,
    // ex tag: {key: 'browser', name: 'Browser', totalValues: 1}
    tags: [],
    title: 'RequestError: GET /issues/ 404',
    type: 'error',
    userCount: 35097,
    userReportCount: 0,
    ...params,
  };
}


text:
/**
 * Utility methods for testing SQL databases.
 *
 *
Objects defined in this package are only for SIS testing purpose any many change
 * in any future version without notice.

 *
 * @author  Martin Desruisseaux (Geomatys)
 * @author  Alexis Manin (Geomatys)
 * @version 1.2
 * @since   1.0
 * @module
 */
package org.apache.sis.test.sql;